@aibyzero/cm-workflow 0.16.3 → 0.16.5

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 (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +55 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/next-steps.md +14 -24
  9. package/docs/runtime-failover.md +1 -1
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  12. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
  15. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  16. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  17. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  18. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  19. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  21. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  22. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  24. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  25. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  27. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  28. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  29. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  30. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  31. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  32. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  34. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  38. package/runtime/js/cm-ai/host-session.mjs +20 -5
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  43. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  44. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  45. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  46. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  47. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  48. package/runtime/js/cm-ai/review-package.mjs +427 -31
  49. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  50. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  52. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  53. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  54. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  56. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  57. package/runtime/js/cm-fix/execution.mjs +109 -25
  58. package/runtime/js/cm-fix/host-review.mjs +7 -3
  59. package/runtime/js/cm-fix/host.mjs +3 -1
  60. package/runtime/js/cm-fix/progress.mjs +1 -0
  61. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  62. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  63. package/runtime/js/cm-prd/analysis.mjs +2 -1
  64. package/runtime/js/cm-prd/change.mjs +28 -10
  65. package/runtime/js/cm-prd/draft.mjs +5 -2
  66. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  67. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  68. package/runtime/js/cm-prd/self-check.mjs +6 -3
  69. package/runtime/js/cm-prd/summary.mjs +6 -2
  70. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  71. package/runtime/js/spec-task-line.mjs +117 -0
  72. package/runtime/js/specs-status.mjs +14 -3
  73. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  74. package/scripts/cm-ai-admission.mjs +19 -10
  75. package/scripts/cm-ai-admission.test.mjs +65 -1
  76. package/scripts/cm-ai-batch-drive.mjs +93 -21
  77. package/scripts/cm-ai-batch-drive.test.mjs +171 -3
  78. package/scripts/cm-ai-batch-host.mjs +37 -13
  79. package/scripts/cm-ai-batch-host.test.mjs +26 -0
  80. package/scripts/cm-ai-batch-run.mjs +33 -10
  81. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  82. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  84. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  85. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  86. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  87. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  88. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  89. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  90. package/scripts/cm-ai-drive.mjs +480 -47
  91. package/scripts/cm-ai-drive.test.mjs +247 -10
  92. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  93. package/scripts/cm-ai-host.mjs +89 -25
  94. package/scripts/cm-ai-host.test.mjs +274 -12
  95. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  96. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  97. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  98. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  99. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  100. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  101. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  102. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  103. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  104. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  105. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  106. package/scripts/cm-ai-run.mjs +160 -60
  107. package/scripts/cm-ai-run.test.mjs +4 -3
  108. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  109. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  110. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  111. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  112. package/scripts/cm-ai-supersede.test.mjs +571 -17
  113. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  114. package/scripts/cm-capability-gate.test.mjs +21 -2
  115. package/scripts/cm-check-drive.mjs +4 -3
  116. package/scripts/cm-check-drive.test.mjs +17 -1
  117. package/scripts/cm-check-entry.mjs +13 -2
  118. package/scripts/cm-check-host.mjs +2 -2
  119. package/scripts/cm-check-host.test.mjs +57 -1
  120. package/scripts/cm-check-runtime.sh +16 -7
  121. package/scripts/cm-claude-developer-worker.test.mjs +43 -2
  122. package/scripts/cm-claude-probe.test.mjs +9 -1
  123. package/scripts/cm-claude-review-stream.test.mjs +68 -0
  124. package/scripts/cm-claude-worker.test.mjs +11 -4
  125. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  126. package/scripts/cm-failover.mjs +8 -8
  127. package/scripts/cm-fix-abandon.test.mjs +123 -5
  128. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  129. package/scripts/cm-fix-drive.mjs +45 -13
  130. package/scripts/cm-fix-drive.test.mjs +36 -1
  131. package/scripts/cm-fix-host.mjs +9 -6
  132. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  133. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  134. package/scripts/cm-host-check.test.mjs +6 -3
  135. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  136. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  137. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  138. package/scripts/cm-log-event.mjs +17 -0
  139. package/scripts/cm-log-event.test.mjs +31 -0
  140. package/scripts/cm-prd-completion.test.mjs +105 -2
  141. package/scripts/cm-prd-draft.test.mjs +14 -0
  142. package/scripts/cm-prd-drive.mjs +13 -7
  143. package/scripts/cm-prd-drive.test.mjs +10 -0
  144. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  145. package/scripts/cm-prd-review-gate.mjs +126 -81
  146. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  147. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  148. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  149. package/scripts/cm-prd-self-check.test.mjs +6 -0
  150. package/scripts/cm-prd-summary.test.mjs +40 -0
  151. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  152. package/scripts/cm-review-inventory.test.mjs +253 -1
  153. package/scripts/cm-spec-manifest.mjs +28 -10
  154. package/scripts/cm-spec-manifest.test.mjs +8 -4
  155. package/scripts/cm-spec-task-line.test.mjs +138 -0
  156. package/scripts/cm-specs-status.test.mjs +31 -1
  157. package/scripts/cm-task-gate.mjs +18 -10
  158. package/scripts/cm-task-gate.py +1 -1
  159. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  160. package/scripts/fixtures/claude-review-process.mjs +1 -0
  161. package/scripts/fixtures/process-cleanup.mjs +99 -0
  162. package/scripts/test-cm-log-event.py +2 -0
  163. package/scripts/test-cm-prd-review-gate.py +2 -1
  164. package/scripts/test-npm-install.py +1 -1
  165. package/scripts/test-scan-public-safety.py +1 -1
  166. package/scripts/test-shell-compat.sh +67 -0
  167. package/scripts/test-spec-manifest.py +16 -8
  168. package/scripts/test-task-gate.py +2 -2
  169. package/scripts/test-workflow-config.py +1 -0
  170. package/scripts/validate-public-repo.py +1 -0
  171. package/skills/cm-ai/references/N1-init.md +1 -1
  172. package/skills/cm-ai/references/js-host.md +264 -40
  173. package/skills/cm-check/SKILL.md +6 -1
  174. package/skills/cm-check/references/js-host.md +3 -3
  175. package/skills/cm-fix/references/js-host.md +22 -1
  176. package/skills/cm-prd/references/js-change-recovery.md +30 -0
  177. package/skills/cm-prd/references/js-host.md +6 -0
@@ -8,6 +8,7 @@ import childProcess from 'node:child_process';
8
8
  import {fileURLToPath} from 'node:url';
9
9
  import {inspectFixWalkthrough,readFixWalkthrough,fixWalkthroughBinding} from '../runtime/js/cm-fix/walkthrough.mjs';
10
10
  import {inspectFixRegressionFailure} from '../runtime/js/cm-fix/regression-evidence.mjs';
11
+ import {taskDeclarations,approvedTaskGrammar,TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
11
12
 
12
13
  const TASK_RE=/^T-[A-Za-z0-9][A-Za-z0-9._-]*$/;
13
14
  const REVIEWERS=new Set(['codex-subagent','codex-cli','claude-cli','self-degraded']);
@@ -601,27 +602,34 @@ function splitLinesKeepEnds(text){
601
602
  if(start<text.length)lines.push({start,text:text.slice(start)});
602
603
  return lines;
603
604
  }
604
-
605
605
  function withoutLineEnding(line){return line.replace(/(?:\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029])$/,'');}
606
606
  function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');}
607
607
 
608
+ // An approval recorded with taskGrammar 2 uses the shared declaration grammar
609
+ // (spec-task-line.mjs): fenced examples are never flipped. Approvals recorded
610
+ // earlier keep the exact original mark-done match on the bytes they approved.
608
611
  function parseTaskTarget(task,tasksPath,revision){
609
612
  let text;
610
- try{text=new TextDecoder('utf-8',{fatal:true}).decode(revision.bytes);}
613
+ try{text=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(revision.bytes);}
611
614
  catch(error){throw new GateError(`cannot read tasks file ${tasksPath}: ${error.message}`);}
612
- const pattern=new RegExp(`^(\\s*-\\s*)\\[([ xX])\\](\\s+${escapeRegExp(task)}(?=[:\\s]|$).*)$`);
613
- const matches=[];
614
- for(const line of splitLinesKeepEnds(text)){
615
- const match=pattern.exec(withoutLineEnding(line.text));
616
- if(match)matches.push({line,match});
615
+ let matches;
616
+ if(approvedTaskGrammar(path.dirname(path.dirname(tasksPath)))===TASK_GRAMMAR)
617
+ matches=taskDeclarations(text).filter(item=>item.id===task).map(item=>({start:item.start,markOffset:item.markOffset,completed:item.completed}));
618
+ else{
619
+ const pattern=new RegExp(`^(\\s*-\\s*)\\[([ xX])\\](\\s+${escapeRegExp(task)}(?=[:\\s]|$).*)$`);
620
+ matches=[];
621
+ for(const line of splitLinesKeepEnds(text)){
622
+ const match=pattern.exec(withoutLineEnding(line.text));
623
+ if(match)matches.push({start:line.start,markOffset:match[1].length+1,completed:match[2].toLowerCase()==='x'});
624
+ }
617
625
  }
618
626
  if(matches.length!==1)throw new GateError(`tasks file must contain exactly one checkbox for ${task}`);
619
- return {text,...matches[0]};
627
+ return {text,declaration:matches[0]};
620
628
  }
621
629
 
622
630
  function taskAfterBytes(target,original){
623
- if(target.match[2].toLowerCase()==='x')return original;
624
- const characterOffset=target.line.start+target.match[1].length+1;
631
+ if(target.declaration.completed)return original;
632
+ const characterOffset=target.declaration.start+target.declaration.markOffset;
625
633
  const byteOffset=Buffer.byteLength(target.text.slice(0,characterOffset));
626
634
  if(original[byteOffset]!==32)throw new GateError('task checkbox byte offset mismatch');
627
635
  return Buffer.concat([original.subarray(0,byteOffset),Buffer.from('x'),original.subarray(byteOffset+1)]);
@@ -245,7 +245,7 @@ def task_writer(reviews: Path, tasks: Path, feature: str) -> Iterator[Path]:
245
245
 
246
246
  def run_js(arguments: Sequence[str], *, environment: Mapping[str, str] | None = None, capture: bool = False):
247
247
  entry = Path(__file__).resolve().with_name("cm-task-gate.mjs")
248
- return subprocess.run(["node", str(entry), *arguments], check=False, text=True, capture_output=capture, env=dict(environment) if environment is not None else None)
248
+ return subprocess.run(["node", str(entry), *arguments], check=False, text=True, encoding="utf-8", capture_output=capture, env=dict(environment) if environment is not None else None)
249
249
 
250
250
 
251
251
  def read_js_object(arguments: Sequence[str], *, environment: Mapping[str, str] | None = None) -> dict[str, object]:
@@ -60,9 +60,12 @@ test('remote default selects main unpushed commits; detached HEAD works; ambiguo
60
60
  f.git('branch','-D','main','master');assert.throws(()=>inspectBranchComparison(f.project),/cm_test_main_missing/);
61
61
  });
62
62
  test('non-Git and unborn repositories do not fall back to whole-worktree analysis',t=>{
63
- const f=fixture(t);fs.rmSync(path.join(f.project,'.git'),{recursive:true});
64
- assert.throws(()=>inspectBranchComparison(f.project),/cm_test_git_required/);
65
- f.git('init','-q','-b','main');assert.throws(()=>inspectBranchComparison(f.project),/cm_test_head_required/);
63
+ const project=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-impact-non-git-')));
64
+ t.after(()=>fs.rmSync(project,{recursive:true,force:true}));
65
+ assert.throws(()=>inspectBranchComparison(project),/cm_test_git_required/);
66
+ const initialized=spawnSync('git',['-C',project,'init','-q','-b','main'],{encoding:'utf8'});
67
+ assert.equal(initialized.status,0,initialized.stderr);
68
+ assert.throws(()=>inspectBranchComparison(project),/cm_test_head_required/);
66
69
  });
67
70
  test('two-tip diff includes main-only additions and tracks rename/deletion plus both committed sides',t=>{
68
71
  const f=fixture(t);f.write('old name.txt','old content\n');f.write('gone.txt','removed content\n');f.commit();
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // Synthetic stdout protocol fixture only, never a model-generated review.
3
3
  import {randomUUID} from 'node:crypto';
4
+ if(process.argv.includes('--version')){process.stdout.write('2.1.274 (Claude Code)\n');process.exit(0);}
4
5
  let prompt='';for await(const part of process.stdin)prompt+=part;
5
6
  if(process.env.ANTHROPIC_API_KEY==='cm-synthetic-local-probe'){
6
7
  const base=process.env.ANTHROPIC_BASE_URL;
@@ -0,0 +1,99 @@
1
+ // Test-only process hygiene for synthetic CLI fixtures. Runtime code never
2
+ // imports this module.
3
+ //
4
+ // Timeout fixtures deliberately stay busy (setInterval) and are often spawned
5
+ // detached by the host under test, so killing the host or losing the test
6
+ // process used to orphan them for good. Two independent guards apply:
7
+ // 1. ownerGuardSource(): the fixture itself exits once the *test process*
8
+ // that created it is gone, or after a hard ceiling. It watches the test
9
+ // process rather than its direct parent, so an orphan caused by a
10
+ // production cleanup regression stays observable while the test runs.
11
+ // 2. killFixtureProcesses(): the test kills the processes that provably belong
12
+ // to its temp dir (see fixtureProcesses), plus the groups they lead.
13
+ import {spawnSync} from 'node:child_process';
14
+
15
+ export const FIXTURE_MAX_LIFETIME_MS=300000;
16
+ export const ownerTag=(ownerPid=process.pid)=>`cm-fixture-owner:${ownerPid}`;
17
+
18
+ // Valid as the first statement of CommonJS, `node -e` and ESM sources.
19
+ export function ownerGuardSource({ownerPid=process.pid,maxLifetimeMs=FIXTURE_MAX_LIFETIME_MS}={}){
20
+ if(!Number.isSafeInteger(ownerPid)||ownerPid<1||!Number.isSafeInteger(maxLifetimeMs)||maxLifetimeMs<1)
21
+ throw Error('invalid_owner_guard');
22
+ return `;(()=>{/*${ownerTag(ownerPid)}*/const owner=${ownerPid},deadline=Date.now()+${maxLifetimeMs};`
23
+ +`const stop=()=>{try{process.kill(process.pid,'SIGKILL');}catch{process.exit(137);}};`
24
+ +`const timer=setInterval(()=>{let alive=true;try{process.kill(owner,0);}catch(error){alive=error?.code==='EPERM';}`
25
+ +`if(!alive||Date.now()>=deadline)stop();},200);timer.unref?.();})();\n`;
26
+ }
27
+
28
+ // Insert the guard after an optional shebang line.
29
+ export function guardFixtureSource(source,options){
30
+ const guard=ownerGuardSource(options);
31
+ if(!source.startsWith('#!'))return guard+source;
32
+ const newline=source.indexOf('\n');
33
+ return newline===-1?`${source}\n${guard}`:source.slice(0,newline+1)+guard+source.slice(newline+1);
34
+ }
35
+
36
+ function listProcesses(){
37
+ const listed=spawnSync('ps',['-axww','-o','pid=,ppid=,pgid=,command='],{encoding:'utf8',maxBuffer:64*1024*1024});
38
+ if(listed.status!==0)throw Error(`ps failed: ${listed.stderr}`);
39
+ const rows=[];
40
+ for(const line of listed.stdout.split('\n')){
41
+ const match=line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
42
+ if(!match)continue;
43
+ const [pid,ppid,pgid]=match.slice(1,4).map(Number);rows.push({pid,ppid,pgid,command:match[4]});
44
+ }
45
+ return rows;
46
+ }
47
+ const interpreters=new Set([process.execPath,'node','/bin/sh','sh']);
48
+
49
+ // Only processes that provably belong to this test, never one that merely
50
+ // mentions the root (a user's grep/tail/lsof of a fixture path survives):
51
+ // - a descendant of this test process whose command line carries the root
52
+ // (hosts and drivers the test spawned), or
53
+ // - a program run from inside the root: argv[0] under it, or node/sh running
54
+ // a script under it (fake CLIs, which may be orphaned by a killed host).
55
+ // Fixture roots come from mkdtemp and contain no whitespace.
56
+ export function fixtureProcesses(root){
57
+ if(typeof root!=='string'||!root.startsWith('/')||root.length<8||/\s/.test(root))throw Error('invalid_fixture_marker');
58
+ if(process.platform==='win32')return [];
59
+ const rows=listProcesses(),parents=new Map(rows.map(row=>[row.pid,row.ppid]));
60
+ const descends=pid=>{
61
+ for(let current=parents.get(pid),hops=0;current>1&&hops<4096;current=parents.get(current),hops++)
62
+ if(current===process.pid)return true;
63
+ return false;
64
+ };
65
+ const inside=value=>typeof value==='string'&&value.startsWith(root+'/');
66
+ return rows.filter(row=>{
67
+ if(row.pid===process.pid||!row.command.includes(root))return false;
68
+ const [program,script]=row.command.split(/\s+/);
69
+ return inside(program)||(interpreters.has(program)&&inside(script))||descends(row.pid);
70
+ });
71
+ }
72
+
73
+ function ownProcessGroup(){
74
+ const row=listProcesses().find(entry=>entry.pid===process.pid);
75
+ return row?.pgid??process.pid;
76
+ }
77
+ const pause=ms=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms);
78
+
79
+ // Synchronous so it also fits finally blocks, t.after and watchdog callbacks.
80
+ export function killFixtureProcesses(root,{waitMs=5000}={}){
81
+ const found=fixtureProcesses(root);
82
+ const own=found.length?ownProcessGroup():null;
83
+ for(const row of found){
84
+ // Only a group whose leader is itself a fixture process (spawned detached by
85
+ // the host under test) is taken whole; never this test's own group.
86
+ if(row.pgid===row.pid&&row.pgid!==own)try{process.kill(-row.pgid,'SIGKILL');}catch{}
87
+ try{process.kill(row.pid,'SIGKILL');}catch{}
88
+ }
89
+ const deadline=Date.now()+waitMs;
90
+ let remaining=found.length?fixtureProcesses(root):[];
91
+ while(remaining.length&&Date.now()<deadline){pause(50);remaining=fixtureProcesses(root);}
92
+ if(remaining.length)throw Error(`fixture processes survived SIGKILL: ${remaining.map(row=>row.pid).join(',')}`);
93
+ return found;
94
+ }
95
+
96
+ export function killProcessGroup(pid){
97
+ if(!Number.isSafeInteger(pid)||pid<2)return;
98
+ try{process.kill(-pid,'SIGKILL');}catch{}
99
+ }
@@ -32,6 +32,7 @@ def invoke(
32
32
  cwd=ROOT,
33
33
  env=env,
34
34
  text=True,
35
+ encoding="utf-8",
35
36
  capture_output=True,
36
37
  check=False,
37
38
  )
@@ -1082,6 +1083,7 @@ def main() -> int:
1082
1083
  cwd=ROOT,
1083
1084
  env=concurrent_env,
1084
1085
  text=True,
1086
+ encoding="utf-8",
1085
1087
  stdout=subprocess.PIPE,
1086
1088
  stderr=subprocess.PIPE,
1087
1089
  )
@@ -24,6 +24,7 @@ def invoke(*args: str, expected_exit: int = 0) -> dict[str, object]:
24
24
  [os.environ.get("CM_NODE_BIN", "node") if SCRIPT.suffix == ".mjs" else sys.executable, str(SCRIPT), *args],
25
25
  cwd=ROOT,
26
26
  text=True,
27
+ encoding="utf-8",
27
28
  capture_output=True,
28
29
  check=False,
29
30
  )
@@ -41,7 +42,7 @@ def invoke(*args: str, expected_exit: int = 0) -> dict[str, object]:
41
42
  command = [sys.executable if other.suffix == ".py" else os.environ.get("CM_NODE_BIN", "node"), str(other), "inspect"]
42
43
  for flag in ("--stage", "--feature", "--evidence", "--receipt"):
43
44
  command.extend([flag, args[args.index(flag) + 1]])
44
- checked = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
45
+ checked = subprocess.run(command, cwd=ROOT, text=True, encoding="utf-8", capture_output=True, check=False)
45
46
  if checked.returncode != 0 or json.loads(checked.stdout).get("outcome") != "completed":
46
47
  raise AssertionError(f"cross-runtime receipt rejected: {checked.stderr}")
47
48
  return json.loads(result.stdout) if result.stdout.strip() else {"stderr": result.stderr}
@@ -19,7 +19,7 @@ ROOT = Path(__file__).resolve().parent.parent
19
19
 
20
20
 
21
21
  def run(args, *, cwd=ROOT, env=None, expected=0, input=None):
22
- result = subprocess.run(args, cwd=cwd, env=env, input=input, text=True,
22
+ result = subprocess.run(args, cwd=cwd, env=env, input=input, text=True, encoding="utf-8",
23
23
  stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
24
24
  if result.returncode != expected:
25
25
  raise AssertionError(f"{args[0]} exited {result.returncode}, expected {expected}\n{result.stdout}")
@@ -38,7 +38,7 @@ class PublicSafetyTests(unittest.TestCase):
38
38
  )
39
39
  return subprocess.run(
40
40
  [sys.executable, str(script)], cwd=root,
41
- capture_output=True, text=True, check=False,
41
+ capture_output=True, text=True, encoding="utf-8", check=False,
42
42
  )
43
43
 
44
44
  def test_reviewed_loopback_literals_and_local_port_templates(self):
@@ -387,6 +387,73 @@ if command -v pwsh >/dev/null 2>&1; then
387
387
  fi
388
388
  fi
389
389
 
390
+ # route_state is only meaningful against the runtime actually running the check.
391
+ # Without --runtime (or CM_RUNTIME) the checker must say so instead of assuming
392
+ # Codex and reporting the other runtime's role as declared-but-not-dispatched.
393
+ ROUTE_PROJECT="$TMP_ROOT/route-project"
394
+ mkdir -p "$ROUTE_PROJECT"
395
+ cat > "$ROUTE_PROJECT/.cm-workflow.yml" <<'ROUTE_YML'
396
+ version: 1
397
+ runtimes:
398
+ available: both
399
+ roles:
400
+ coder:
401
+ adapter: codex-cli
402
+ model: default
403
+ source: subscription
404
+ reviewer:
405
+ adapter: claude-cli
406
+ model: default
407
+ source: subscription
408
+ ROUTE_YML
409
+
410
+ route_line() {
411
+ grep "^runtime declaration \[both\] $2:" "$1" || true
412
+ }
413
+
414
+ env -u CM_RUNTIME "$ROOT/scripts/cm-check-runtime.sh" --project "$ROUTE_PROJECT" \
415
+ >"$TMP_ROOT/route-unset.out" 2>&1 || true
416
+ if ! route_line "$TMP_ROOT/route-unset.out" coder | grep -q '未判定'; then
417
+ cat "$TMP_ROOT/route-unset.out" >&2
418
+ fail "an unnamed runtime must report 未判定 instead of guessing one"
419
+ fi
420
+ if route_line "$TMP_ROOT/route-unset.out" reviewer | grep -q '已声明未派发'; then
421
+ cat "$TMP_ROOT/route-unset.out" >&2
422
+ fail "an unnamed runtime must not claim the reviewer was never dispatched"
423
+ fi
424
+
425
+ for rt in codex claude; do
426
+ env -u CM_RUNTIME "$ROOT/scripts/cm-check-runtime.sh" --project "$ROUTE_PROJECT" --runtime "$rt" \
427
+ >"$TMP_ROOT/route-$rt.out" 2>&1 || true
428
+ if [ "$rt" = codex ]; then own=coder; other=reviewer; else own=reviewer; other=coder; fi
429
+ if ! route_line "$TMP_ROOT/route-$rt.out" "$own" | grep -q 'route_state=current-runtime'; then
430
+ cat "$TMP_ROOT/route-$rt.out" >&2
431
+ fail "--runtime $rt must label $own as the current runtime"
432
+ fi
433
+ if ! route_line "$TMP_ROOT/route-$rt.out" "$other" | grep -q '已声明未派发'; then
434
+ cat "$TMP_ROOT/route-$rt.out" >&2
435
+ fail "--runtime $rt must label $other as declared but not dispatched"
436
+ fi
437
+ done
438
+
439
+ CM_RUNTIME=claude "$ROOT/scripts/cm-check-runtime.sh" --project "$ROUTE_PROJECT" \
440
+ >"$TMP_ROOT/route-env.out" 2>&1 || true
441
+ if ! route_line "$TMP_ROOT/route-env.out" reviewer | grep -q 'route_state=current-runtime'; then
442
+ cat "$TMP_ROOT/route-env.out" >&2
443
+ fail "CM_RUNTIME must still name the current runtime when no flag is passed"
444
+ fi
445
+
446
+ for bad in pi CODEX ""; do
447
+ if env -u CM_RUNTIME "$ROOT/scripts/cm-check-runtime.sh" --project "$ROUTE_PROJECT" --runtime "$bad" \
448
+ >"$TMP_ROOT/route-bad.out" 2>&1; then
449
+ fail "--runtime $bad must be rejected"
450
+ fi
451
+ done
452
+ if "$ROOT/scripts/cm-check-runtime.sh" --project "$ROUTE_PROJECT" --runtime \
453
+ >"$TMP_ROOT/route-missing.out" 2>&1; then
454
+ fail "--runtime without a value must be rejected"
455
+ fi
456
+
390
457
  if ! command -v pwsh >/dev/null 2>&1; then
391
458
  echo "PowerShell runtime declaration fixtures: SKIPPED (pwsh unavailable)"
392
459
  fi
@@ -16,11 +16,12 @@ ROOT = Path(__file__).resolve().parents[1]
16
16
  SCRIPT = ROOT / "scripts" / "cm-spec-manifest.py"
17
17
 
18
18
 
19
- def invoke(*args: str, expected_exit: int = 0) -> subprocess.CompletedProcess[str]:
19
+ def invoke(*args: str, expected_exit: int = 0, oracle_exit: int | None = None) -> subprocess.CompletedProcess[str]:
20
20
  result = subprocess.run(
21
21
  [sys.executable, str(SCRIPT), *args],
22
22
  cwd=ROOT,
23
23
  text=True,
24
+ encoding="utf-8",
24
25
  capture_output=True,
25
26
  check=False,
26
27
  )
@@ -28,15 +29,18 @@ def invoke(*args: str, expected_exit: int = 0) -> subprocess.CompletedProcess[st
28
29
  # not against two entrypoints which now execute the same implementation.
29
30
  oracle = subprocess.run(
30
31
  [sys.executable, str(ROOT / "scripts" / "fixtures" / "spec-manifest-python-oracle.py"), *args],
31
- cwd=ROOT, text=True, capture_output=True, check=False,
32
+ cwd=ROOT, text=True, encoding="utf-8", capture_output=True, check=False,
32
33
  )
33
34
  javascript = subprocess.run(
34
35
  [os.environ.get("CM_NODE_BIN", "node"), str(ROOT / "scripts" / "cm-spec-manifest.mjs"), *args],
35
- cwd=ROOT, text=True, capture_output=True, check=False,
36
+ cwd=ROOT, text=True, encoding="utf-8", capture_output=True, check=False,
36
37
  )
37
- if javascript.returncode != result.returncode or oracle.returncode != result.returncode:
38
+ # oracle_exit marks a deliberate post-migration grammar change: the frozen
39
+ # oracle keeps its old answer and must not be compared byte for byte.
40
+ expected_oracle = result.returncode if oracle_exit is None else oracle_exit
41
+ if javascript.returncode != result.returncode or oracle.returncode != expected_oracle:
38
42
  raise AssertionError(f"JS/Python exit mismatch: {javascript.stderr} / {result.stderr}")
39
- if result.returncode == 0 and not (
43
+ if result.returncode == 0 and oracle_exit is None and not (
40
44
  json.loads(javascript.stdout) == json.loads(result.stdout) == json.loads(oracle.stdout)
41
45
  ):
42
46
  raise AssertionError("JS/Python semantic manifest mismatch")
@@ -176,13 +180,17 @@ def main() -> int:
176
180
  ),
177
181
  encoding="utf-8",
178
182
  )
179
- indented_example = invoke(
183
+ # The shared tasks.md grammar (runtime/js/spec-task-line.mjs) reads an
184
+ # indented task line as a declaration, exactly as admission and N5 do,
185
+ # so its checkbox is runtime state. The frozen oracle still mismatches.
186
+ indented_task = invoke(
180
187
  str(specs),
181
188
  "--status-file",
182
189
  str(status),
183
- expected_exit=1,
190
+ expected_exit=0,
191
+ oracle_exit=1,
184
192
  )
185
- assert "approved spec manifest does not match" in indented_example.stderr
193
+ assert json.loads(indented_task.stdout)["status"] == "matched"
186
194
 
187
195
  (feature / "tasks.md").write_text(tasks_completed, encoding="utf-8")
188
196
 
@@ -29,10 +29,10 @@ def main() -> int:
29
29
 
30
30
  arguments = ["check-n4", "--help"]
31
31
  direct = subprocess.run(
32
- ["node", str(JS_GATE), *arguments], text=True, capture_output=True, check=False
32
+ ["node", str(JS_GATE), *arguments], text=True, encoding="utf-8", capture_output=True, check=False
33
33
  )
34
34
  compatibility = subprocess.run(
35
- [sys.executable, str(PYTHON_GATE), *arguments], text=True, capture_output=True, check=False
35
+ [sys.executable, str(PYTHON_GATE), *arguments], text=True, encoding="utf-8", capture_output=True, check=False
36
36
  )
37
37
  assert compatibility.returncode == direct.returncode
38
38
  assert compatibility.stdout == direct.stdout
@@ -16,6 +16,7 @@ def main() -> int:
16
16
  check=False,
17
17
  capture_output=True,
18
18
  text=True,
19
+ encoding="utf-8",
19
20
  env={**os.environ, "CM_PYTHON_BIN": sys.executable},
20
21
  )
21
22
  if result.returncode != 0:
@@ -34,6 +34,7 @@ CM_AI_RUNTIME = (
34
34
  "codex-review-adapter.mjs",
35
35
  "contracts.mjs",
36
36
  "durable-runner-state.mjs",
37
+ "diagnostic-reason.mjs",
37
38
  "effect-contract.mjs",
38
39
  "execution-store.mjs",
39
40
  "gate-bridge.mjs",
@@ -44,7 +44,7 @@
44
44
  以 JS admission 的结果为准;模型不得自行拼写或修改 `.cm-specs-status`:
45
45
 
46
46
  - `ready` / `complete` → 沿用现有准入结果;旧版无 `specFiles` 的文件仍可读取,不在本节点自行补造批准证据。
47
- - `awaiting_spec_approval` → 展示规格摘要卡(无卡时可现场汇总,但不得据此生成或替换 `summaryDigest`),等用户明确回复“开始”。泛化授权语(“继续”“按最优解处理”“你看着办”)不构成审批,须回问“规格摘要卡确认开始吗?”(实跑失守:泛化授权曾被误视为审批通过)。
47
+ - `awaiting_spec_approval` → 展示规格摘要卡(无卡时可现场汇总,但不得据此生成或替换 `summaryDigest`),请用户明确回复“开始”。JS 仅接受“开始”“开始吧”“可以开始”“确认开始”“开始执行”“现在开始”,可带尾部中英文句末标点和空白;泛化授权语(“继续”“可以”“好”“好的”“OK”“按最优解处理”“你看着办”“行”)仍不构成审批,未命中时明确提示回复“开始”(实跑失守:泛化授权曾被误视为审批通过)。
48
48
  - 取得明确回复后运行以下写入口,`--approval-response` 传用户原话;多个代码项目全部传入:
49
49
 
50
50
  ```bash