@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
@@ -16,7 +16,8 @@ import {createFixFinalReview} from '../runtime/js/cm-fix/final-review.mjs';
16
16
  // Synthetic raw CLI stream through the actual worker/adapter/fix observer.
17
17
  // No provider process, real project, credentials or completion writes.
18
18
  for(const mode of ['progress','tool','late-progress','early-progress','missing-result','wrong-digest','private-event','private-error',
19
- 'startup-notice','early-notice','late-notice','duplicate-notice','changed-notice','notice-only']){
19
+ 'startup-notice','early-notice','late-notice','duplicate-notice','changed-notice','notice-only',
20
+ 'two-notices','eight-notices','ninth-notice','terminal-notice','malformed-notice','unfinished-notice','top-error','turn-failed','duplicate-failure','unknown-item']){
20
21
  test(`fix final review raw Codex stream: ${mode}`,async t=>{
21
22
  const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-progress-')));
22
23
  t.after(()=>fs.rmSync(temp,{recursive:true,force:true}));
@@ -34,9 +35,10 @@ for(const mode of ['progress','tool','late-progress','early-progress','missing-r
34
35
  const authority=createHostReviewAuthority({hostContextId:'author',reviewerId:reviewer.reviewerId,adapterId:reviewer.adapterId,decide:async()=>({status:'approved'})});
35
36
  const signal=new AbortController().signal;
36
37
  await authority.hostDecisionProvider.decide({identity,packageDigest:pkg.packageDigest},signal);
37
- let registered=null,started=null,spawns=0;const events=[];
38
+ let registered=null,started=null,spawns=0,workerResult;const events=[],notices=[];
38
39
  const options={cwd:root,model:'fixture'};
39
40
  const worker=codexWorker({...options,schemaPath:'/unused',cli:'/must-not-run',timeoutMs:1000,
41
+ onNotice:message=>notices.push(message),
40
42
  preflight:{passed:true,cli_model:options.model,config_fingerprint:configFingerprint(options)},
41
43
  spawnProcess(){
42
44
  spawns++;assert(registered);
@@ -52,20 +54,27 @@ for(const mode of ['progress','tool','late-progress','early-progress','missing-r
52
54
  const rows=mode==='notice-only'?[{type:'thread.started',thread_id:'fresh-provider'},notice]:[
53
55
  ...(mode==='early-progress'?progress:[]),...(mode==='early-notice'?[notice]:[]),
54
56
  {type:'thread.started',thread_id:'fresh-provider'},
55
- ...(['startup-notice','duplicate-notice'].includes(mode)?[notice]:[]),
57
+ ...(['startup-notice','duplicate-notice','two-notices'].includes(mode)?[notice]:[]),
56
58
  ...(mode==='duplicate-notice'?[notice]:[]),
57
59
  ...(mode==='changed-notice'?[{...notice,item:{...notice.item,message:notice.item.message+' synthetic unknown diagnostic'}}]:[]),
58
60
  {type:'turn.started'},...(mode==='late-notice'?[notice]:[]),
61
+ ...(['eight-notices','ninth-notice'].includes(mode)?Array.from({length:mode==='eight-notices'?8:9},()=>notice):[]),
62
+ ...(mode==='two-notices'?[{...notice,item:{type:'error',message:'Skill descriptions were shortened to fit the skills context budget. '+'x'.repeat(200),extra:'not retained'}}]:[]),
63
+ ...(mode==='malformed-notice'?[{...notice,item:{type:'error',message:null}}]:[]),
64
+ ...(mode==='unfinished-notice'?[{...notice,type:'item.started'}]:[]),
65
+ ...(['top-error','duplicate-failure'].includes(mode)?[{type:'error',message:'fatal'}]:[]),
66
+ ...(['turn-failed','duplicate-failure'].includes(mode)?[{type:'turn.failed'}]:[]),
67
+ ...(mode==='unknown-item'?[{type:'item.completed',item:{type:'future_item'}}]:[]),
59
68
  ...progress,...(mode==='tool'?[{type:'item.started',item:{type:'command_execution'}}]:[]),
60
69
  ...(mode==='private-event'?[{type:'private-provider-text',item:{type:'private-item-text'}}]:[]),
61
70
  ...(mode==='missing-result'?[]:[{type:'item.completed',item:{type:'agent_message',text:JSON.stringify(result)}}]),
62
- {type:'turn.completed'},...(mode==='late-progress'?progress:[])];
71
+ {type:'turn.completed'},...(mode==='terminal-notice'?[notice]:[]),...(mode==='late-progress'?progress:[])];
63
72
  for(const row of rows){if(child.killed)break;child.stdout.write(JSON.stringify(row)+'\n');}
64
73
  if(!child.killed)close(0);
65
74
  });
66
75
  return child;
67
76
  }});
68
- const adapter=createCodexReviewRun(worker);
77
+ const adapter=createCodexReviewRun(async (...args)=>(workerResult=await worker(...args)));
69
78
  let errorGetterCalls=0;
70
79
  const run=(request,control)=>{
71
80
  if(mode==='private-error')throw Object.defineProperty(new Error('private-provider-text'),'code',
@@ -74,12 +83,28 @@ for(const mode of ['progress','tool','late-progress','early-progress','missing-r
74
83
  };
75
84
  const review=createFixFinalReview({reviewPackage:pkg,configuration,timeoutMs:2000},{authorize:authority.authorize,run});
76
85
  const result=await review({signal,register:r=>{registered=r;},onStarted:id=>{started=id;}});
77
- const success=['progress','startup-notice'].includes(mode);
86
+ const success=['progress','startup-notice','late-notice','duplicate-notice','changed-notice','two-notices','eight-notices'].includes(mode);
78
87
  if(success)assert.equal(result.outcome,'observed');
79
88
  else if(result.outcome==='observed'){
80
89
  assert.equal(result.inspection.observationStatus,'unknown');
81
90
  assert.equal(result.inspection.review,null);
82
91
  }else assert.equal(result.outcome,'unknown');
92
+ if(mode==='two-notices'){
93
+ assert.equal(workerResult.status,'succeeded');
94
+ assert.deepEqual(Object.keys(workerResult).sort(),['status','value']);
95
+ assert.equal(notices.length,2);assert.equal(notices[1].length,200);
96
+ assert(!JSON.stringify(workerResult).includes('not retained'));
97
+ }
98
+ if(mode==='progress'){
99
+ assert.deepEqual(Object.keys(workerResult).sort(),['status','value']);
100
+ assert.deepEqual(events.filter(e=>e.item_type==='error'),[]);
101
+ }
102
+ if(['top-error','turn-failed','duplicate-failure'].includes(mode))assert.equal(workerResult.code,'provider_failed');
103
+ if(['terminal-notice','ninth-notice'].includes(mode))assert.deepEqual(workerResult,{status:'failed',code:'invalid_event'});
104
+ if(mode==='ninth-notice')assert.equal(notices.length,8);
105
+ if(mode==='terminal-notice')assert.equal(notices.length,0);
106
+ if(mode!=='unfinished-notice')assert.deepEqual(events.filter(e=>e.item_type==='error'),[]);
107
+ if(mode==='unknown-item')assert.deepEqual(result.diagnostic,{phase:'event',code:'observation_invalid',event:'item.completed',itemType:'other'});
83
108
  if(mode==='tool')assert.deepEqual(result.diagnostic,{phase:'event',code:'observation_invalid',event:'item.started',itemType:'command_execution'});
84
109
  if(mode==='wrong-digest')assert.deepEqual(result.diagnostic,{phase:'result',code:'review_package_mismatch'});
85
110
  if(mode==='private-event')assert.deepEqual(result.diagnostic,{phase:'event',code:'observation_invalid',event:'other',itemType:'other'});
@@ -88,6 +113,9 @@ for(const mode of ['progress','tool','late-progress','early-progress','missing-r
88
113
  assert.equal(result.completionEligible,false);assert.equal(spawns,mode==='private-error'?0:1);
89
114
  if(success){
90
115
  assert.equal(started,'fresh-provider');assert.equal(result.inspection.review.verdict,'approved');
116
+ const noticeCount=mode==='eight-notices'?8:['duplicate-notice','two-notices'].includes(mode)?2:mode==='progress'?0:1;
117
+ assert.equal(notices.length,noticeCount);
118
+ assert.deepEqual(Object.keys(workerResult).sort(),['status','value']);
91
119
  assert.deepEqual(events.map(e=>e.event),['thread.started','turn.started','item.completed','turn.completed','process_closed']);
92
120
  }
93
121
  await assert.rejects(review({signal,register(){},onStarted(){}}),{code:'final_review_already_attempted'});
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env node
2
+ // Read-only runtime failover aid: report the current CM workflow breakpoint and
3
+ // render a continuation brief for the other runtime. This tool never writes
4
+ // tasks.md, never marks a task done, and never authorizes completion.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import childProcess from 'node:child_process';
8
+ // Single source of truth for role primary/standby; shared with the cm-ai host.
9
+ import {ROLE_ROUTING} from '../runtime/js/cm-ai/runtime-failover.mjs';
10
+
11
+ export {ROLE_ROUTING};
12
+
13
+ export class FailoverError extends Error {
14
+ constructor(message){super(message);this.name='FailoverError';}
15
+ }
16
+
17
+ const TASK_RE=/^T-[A-Za-z0-9][A-Za-z0-9._-]*$/;
18
+ const FEATURE_RE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;
19
+ const RUNTIMES=new Set(['codex','claude']);
20
+ const READ_LIMIT=1024*1024;
21
+
22
+
23
+ function readTextFile(file,label){
24
+ let info;
25
+ try{info=fs.lstatSync(file);}catch(error){throw new FailoverError(`cannot read ${label}: ${file}: ${error.message}`);}
26
+ if(info.isSymbolicLink())throw new FailoverError(`${label} must not be a symlink: ${file}`);
27
+ if(!info.isFile())throw new FailoverError(`${label} must be a regular file: ${file}`);
28
+ if(info.size>READ_LIMIT)throw new FailoverError(`${label} exceeds the ${READ_LIMIT} byte read limit: ${file}`);
29
+ return fs.readFileSync(file,'utf8');
30
+ }
31
+
32
+ function readDirectory(dir,label){
33
+ let info;
34
+ try{info=fs.lstatSync(dir);}catch(error){throw new FailoverError(`cannot read ${label}: ${dir}: ${error.message}`);}
35
+ if(info.isSymbolicLink())throw new FailoverError(`${label} must not be a symlink: ${dir}`);
36
+ if(!info.isDirectory())throw new FailoverError(`${label} must be a directory: ${dir}`);
37
+ return fs.readdirSync(dir,{withFileTypes:true});
38
+ }
39
+
40
+ // `- [ ] T-001: title` / `- [x] T-002: title`; anything else is prose.
41
+ export function parseTasks(text){
42
+ const tasks=[],seen=new Set();
43
+ for(const line of text.split(/\r\n|[\n\r]/)){
44
+ const match=/^[ \t]*-[ \t]+\[([ xX])\][ \t]+(T-[A-Za-z0-9][A-Za-z0-9._-]*)[ \t]*[::][ \t]*(.*)$/.exec(line);
45
+ if(!match)continue;
46
+ const id=match[2];
47
+ if(!TASK_RE.test(id))continue;
48
+ if(seen.has(id))throw new FailoverError(`tasks.md contains a duplicate task id: ${id}`);
49
+ seen.add(id);
50
+ tasks.push({id,done:match[1].toLowerCase()==='x',title:match[3].trim()});
51
+ }
52
+ if(tasks.length===0)throw new FailoverError('tasks.md declares no `- [ ] T-xxx:` task line');
53
+ return tasks;
54
+ }
55
+
56
+ function parseHandoff(file){
57
+ let payload;
58
+ try{payload=JSON.parse(readTextFile(file,'handoff evidence'));}
59
+ catch(error){
60
+ if(error instanceof FailoverError)throw error;
61
+ throw new FailoverError(`handoff evidence is not valid JSON: ${file}: ${error.message}`);
62
+ }
63
+ if(!payload||typeof payload!=='object'||Array.isArray(payload))
64
+ throw new FailoverError(`handoff evidence must be a JSON object: ${file}`);
65
+ const status=payload.status;
66
+ if(status!=='ready_for_review'&&status!=='blocked')
67
+ throw new FailoverError(`handoff evidence has an unknown status: ${file}`);
68
+ const list=(value)=>Array.isArray(value)?value.filter(item=>typeof item==='string'):[];
69
+ return {status,
70
+ blockers:list(payload.blockers),
71
+ scopeDeviation:list(payload.scope_deviation),
72
+ changedFiles:list(payload.changed_files),
73
+ contentBound:typeof payload.implementation_sha256==='string'};
74
+ }
75
+
76
+ // Review evidence carries a closed YAML header; only the verdict is needed here.
77
+ function parseReviewVerdict(file){
78
+ const lines=readTextFile(file,'review evidence').split(/\r\n|[\n\r]/);
79
+ if(lines[0]===undefined||lines[0].trim()!=='---')return null;
80
+ const end=lines.findIndex((line,index)=>index>0&&line.trim()==='---');
81
+ if(end<0)return null;
82
+ for(const line of lines.slice(1,end)){
83
+ const match=/^verdict[ \t]*:[ \t]*(.+)$/.exec(line);
84
+ if(match)return match[1].trim().replace(/^["']+|["']+$/g,'');
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function attemptEvidence(reviewsDir,entries,feature,task){
90
+ const attempts=[];
91
+ for(const attempt of [1,2]){
92
+ const handoffName=`${feature}-${task}-a${attempt}-handoff.json`;
93
+ const reviewName=`${feature}-${task}-r${attempt}.md`;
94
+ const hasHandoff=entries.has(handoffName),hasReview=entries.has(reviewName);
95
+ if(!hasHandoff&&!hasReview)continue;
96
+ attempts.push({attempt,
97
+ handoff:hasHandoff?parseHandoff(path.join(reviewsDir,handoffName)):null,
98
+ handoffPath:hasHandoff?path.join(reviewsDir,handoffName):null,
99
+ verdict:hasReview?parseReviewVerdict(path.join(reviewsDir,reviewName)):null,
100
+ reviewPath:hasReview?path.join(reviewsDir,reviewName):null});
101
+ }
102
+ return attempts;
103
+ }
104
+
105
+ // Exhaustive breakpoint classification. Every branch names the next CM node so
106
+ // the receiving runtime resumes at a declared step instead of guessing.
107
+ export function classifyBreakpoint(task,attempts){
108
+ if(task.done)return {node:'N5',state:'task_done',summary:'任务已在 tasks.md 标记完成'};
109
+ const last=attempts[attempts.length-1]??null;
110
+ if(last===null)return {node:'N3',state:'not_started',summary:'尚无交接证据,从任务执行开始'};
111
+ if(last.handoff===null)
112
+ return {node:'N3',state:'review_without_handoff',attempt:last.attempt,
113
+ summary:`第 ${last.attempt} 次存在审查文件但缺交接证据,需重建交接`};
114
+ if(last.handoff.status==='blocked')
115
+ return {node:'N3',state:'blocked',attempt:last.attempt,
116
+ summary:`第 ${last.attempt} 次交接为 blocked,需先处理阻塞项`,
117
+ blockers:last.handoff.blockers,scopeDeviation:last.handoff.scopeDeviation};
118
+ if(last.verdict===null)
119
+ return {node:'N4',state:'awaiting_review',attempt:last.attempt,
120
+ summary:`第 ${last.attempt} 次交接已 ready_for_review,等待独立审查`,
121
+ changedFiles:last.handoff.changedFiles,contentBound:last.handoff.contentBound};
122
+ if(last.verdict==='approved')
123
+ return {node:'N5',state:'approved',attempt:last.attempt,
124
+ summary:`第 ${last.attempt} 次审查通过,等待标记完成`};
125
+ if(last.verdict==='changes_requested')
126
+ return last.attempt>=2
127
+ ? {node:'N4',state:'changes_exhausted',attempt:last.attempt,
128
+ summary:'第 2 次审查仍要求修改,重试次数已用尽,需人工介入'}
129
+ : {node:'N3',state:'changes_requested',attempt:last.attempt+1,
130
+ summary:`第 ${last.attempt} 次审查要求修改,进入第 ${last.attempt+1} 次尝试`};
131
+ if(last.verdict==='blocked')
132
+ return {node:'N4',state:'review_blocked',attempt:last.attempt,
133
+ summary:`第 ${last.attempt} 次审查判定 blocked,需人工介入`};
134
+ return {node:'N4',state:'unknown_verdict',attempt:last.attempt,
135
+ summary:`第 ${last.attempt} 次审查结论无法识别,需人工确认`};
136
+ }
137
+
138
+ function inspectFeature(featureDir,feature){
139
+ const tasks=parseTasks(readTextFile(path.join(featureDir,'tasks.md'),'tasks.md'));
140
+ const reviewsDir=path.join(featureDir,'.reviews');
141
+ let entries=new Set();
142
+ if(fs.existsSync(reviewsDir))
143
+ entries=new Set(readDirectory(reviewsDir,'reviews directory').filter(e=>e.isFile()).map(e=>e.name));
144
+ const pending=tasks.filter(task=>!task.done);
145
+ const current=pending[0]??null;
146
+ const breakpoint=current===null
147
+ ? {node:'N6',state:'all_tasks_done',summary:'全部任务已标记完成,进入 QA 评估'}
148
+ : classifyBreakpoint(current,attemptEvidence(reviewsDir,entries,feature,current.id));
149
+ return {feature,featureDir,tasks,
150
+ done:tasks.filter(task=>task.done).length,
151
+ total:tasks.length,
152
+ currentTask:current,
153
+ breakpoint};
154
+ }
155
+
156
+ export function inspectSpecs(specsDir){
157
+ const resolved=path.resolve(specsDir);
158
+ if(fs.existsSync(path.join(resolved,'tasks.md'))){
159
+ const feature=path.basename(resolved);
160
+ if(!FEATURE_RE.test(feature))throw new FailoverError(`unsupported feature directory name: ${feature}`);
161
+ return {specsDir:resolved,features:[inspectFeature(resolved,feature)]};
162
+ }
163
+ const features=[];
164
+ for(const entry of readDirectory(resolved,'specs directory')){
165
+ if(!entry.isDirectory()||!FEATURE_RE.test(entry.name))continue;
166
+ const featureDir=path.join(resolved,entry.name);
167
+ if(!fs.existsSync(path.join(featureDir,'tasks.md')))continue;
168
+ features.push(inspectFeature(featureDir,entry.name));
169
+ }
170
+ if(features.length===0)throw new FailoverError(`no feature with tasks.md found under ${resolved}`);
171
+ return {specsDir:resolved,features};
172
+ }
173
+
174
+ // Binary presence only. A resolvable CLI does not prove quota or auth is usable,
175
+ // so the caller must treat `available` as a necessary, not sufficient, signal.
176
+ export function probeRuntimes(runtimes=[...RUNTIMES],{run=null}={}){
177
+ const exec=run??((command)=>{
178
+ const result=childProcess.spawnSync(command,['--version'],
179
+ {encoding:'utf8',timeout:10000,stdio:['ignore','pipe','pipe']});
180
+ if(result.error)return {ok:false,detail:result.error.code??result.error.message};
181
+ if(result.status!==0)return {ok:false,detail:`exit ${result.status}`};
182
+ return {ok:true,detail:(result.stdout??'').trim().split(/\r?\n/)[0]??''};
183
+ });
184
+ return runtimes.map(runtime=>{
185
+ const outcome=exec(runtime);
186
+ return {runtime,available:outcome.ok===true,
187
+ detail:typeof outcome.detail==='string'?outcome.detail.slice(0,200):''};
188
+ });
189
+ }
190
+
191
+ function renderBrief(report,target){
192
+ const routing=Object.entries(ROLE_ROUTING)
193
+ .map(([role,{primary,standby}])=>` - ${role}: 主 ${primary} / 备 ${standby}`).join('\n');
194
+ const blocks=report.features.map(feature=>{
195
+ const {breakpoint:point,currentTask:task}=feature;
196
+ const lines=[`## Feature ${feature.feature}(${feature.done}/${feature.total} 任务已完成)`,
197
+ `- specs 目录: ${feature.featureDir}`,
198
+ `- 断点节点: ${point.node}(${point.state})`,
199
+ `- 断点说明: ${point.summary}`];
200
+ if(task)lines.push(`- 当前任务: ${task.id} — ${task.title}`);
201
+ if(point.attempt!==undefined)lines.push(`- 尝试轮次: 第 ${point.attempt} 次`);
202
+ if(point.blockers?.length)lines.push(`- 阻塞项: ${point.blockers.join(';')}`);
203
+ if(point.scopeDeviation?.length)lines.push(`- 范围偏离: ${point.scopeDeviation.join(';')}`);
204
+ if(point.changedFiles?.length)
205
+ lines.push(`- 已改文件: ${point.changedFiles.join('、')}`,
206
+ `- 内容绑定: ${point.contentBound?'已绑定 implementation_sha256':'缺失,N4 需要重建交接'}`);
207
+ return lines.join('\n');
208
+ });
209
+ return [`# CM 断点交接简报 → ${target}`,'',
210
+ '在目标运行时开启新会话,粘贴本简报,再按其中的断点节点续跑。',
211
+ '',
212
+ `角色主从(${target} 为本次接管方):`,routing,'',
213
+ ...blocks,'',
214
+ '## 接管约束','',
215
+ '- 本简报只描述落盘状态,不是完成授权;tasks.md 仍是任务状态的唯一真相。',
216
+ '- 续跑方必须自行复跑该任务声明的验证命令,不得沿用本简报里的历史结论。',
217
+ '- N4 独立审查不得由实现者本人完成;跨运行时接管时同样成立。',
218
+ '- 交接证据的 implementation_sha256 与实际文件绑定,任何改动都会使旧审查失效。'].join('\n');
219
+ }
220
+
221
+ function renderStatus(report){
222
+ const lines=[`specs: ${report.specsDir}`];
223
+ for(const feature of report.features){
224
+ lines.push('',`[${feature.feature}] ${feature.done}/${feature.total} 完成`,
225
+ ` 断点: ${feature.breakpoint.node} (${feature.breakpoint.state})`,
226
+ ` 说明: ${feature.breakpoint.summary}`);
227
+ if(feature.currentTask)lines.push(` 当前任务: ${feature.currentTask.id} — ${feature.currentTask.title}`);
228
+ }
229
+ return lines.join('\n');
230
+ }
231
+
232
+ function parseArgv(argv){
233
+ const options={};
234
+ for(let index=0;index<argv.length;index++){
235
+ const token=argv[index];
236
+ if(!token.startsWith('--'))throw new FailoverError(`unexpected argument: ${token}`);
237
+ const key=token.slice(2);
238
+ if(key==='json'){options.json=true;continue;}
239
+ const value=argv[++index];
240
+ if(value===undefined||value.startsWith('--'))throw new FailoverError(`missing value for --${key}`);
241
+ options[key]=value;
242
+ }
243
+ return options;
244
+ }
245
+
246
+ const USAGE=`用法: node scripts/cm-failover.mjs <command> [options]
247
+
248
+ 命令:
249
+ status --specs {dir} [--json] 只读报告当前断点
250
+ handoff --specs {dir} --to {codex|claude} [--json]
251
+ 生成给另一端的续跑简报
252
+ probe [--json] 探测 codex/claude CLI 是否可解析
253
+
254
+ 说明: 本工具只读。它不写 tasks.md、不标记完成、不授权发布,
255
+ probe 的 available 只代表 CLI 可解析,不代表配额或鉴权可用。`;
256
+
257
+ export function main(argv){
258
+ const [command,...rest]=argv;
259
+ if(command===undefined||command==='--help'||command==='-h')return {text:USAGE,code:0};
260
+ const options=parseArgv(rest);
261
+ if(command==='probe'){
262
+ const results=probeRuntimes();
263
+ return options.json
264
+ ? {text:JSON.stringify({runtimes:results,routing:ROLE_ROUTING},null,2),code:0}
265
+ : {text:results.map(r=>`${r.runtime}: ${r.available?'可解析':'不可用'}${r.detail?` (${r.detail})`:''}`)
266
+ .join('\n')+'\n注意: 可解析 != 配额可用。',code:0};
267
+ }
268
+ if(command!=='status'&&command!=='handoff')throw new FailoverError(`unknown command: ${command}`);
269
+ if(typeof options.specs!=='string')throw new FailoverError('--specs is required');
270
+ const report=inspectSpecs(options.specs);
271
+ if(command==='status')
272
+ return {text:options.json?JSON.stringify(report,null,2):renderStatus(report),code:0};
273
+ if(typeof options.to!=='string'||!RUNTIMES.has(options.to))
274
+ throw new FailoverError('--to must be codex or claude');
275
+ return {text:options.json
276
+ ? JSON.stringify({target:options.to,routing:ROLE_ROUTING,brief:renderBrief(report,options.to),...report},null,2)
277
+ : renderBrief(report,options.to),code:0};
278
+ }
279
+
280
+ const invoked=process.argv[1]!==undefined
281
+ &&fs.realpathSync(process.argv[1])===fs.realpathSync(new URL(import.meta.url).pathname);
282
+ if(invoked){
283
+ try{const {text,code}=main(process.argv.slice(2));process.stdout.write(`${text}\n`);process.exit(code);}
284
+ catch(error){
285
+ if(!(error instanceof FailoverError))throw error;
286
+ process.stderr.write(`cm-failover: ${error.message}\n`);process.exit(1);
287
+ }
288
+ }
@@ -0,0 +1,184 @@
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 {main,inspectSpecs,parseTasks,classifyBreakpoint,probeRuntimes,
7
+ ROLE_ROUTING,FailoverError} from './cm-failover.mjs';
8
+
9
+ function sandbox(){
10
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-failover-')));
11
+ test.after(()=>fs.rmSync(root,{recursive:true,force:true}));
12
+ return root;
13
+ }
14
+
15
+ function feature(root,name,tasks){
16
+ const dir=path.join(root,name);
17
+ fs.mkdirSync(path.join(dir,'.reviews'),{recursive:true});
18
+ fs.writeFileSync(path.join(dir,'tasks.md'),
19
+ `# ${name}\n\n${tasks.map(t=>`- [${t.done?'x':' '}] ${t.id}: ${t.title}`).join('\n')}\n`);
20
+ return dir;
21
+ }
22
+
23
+ function handoff(dir,name,task,attempt,payload){
24
+ fs.writeFileSync(path.join(dir,'.reviews',`${name}-${task}-a${attempt}-handoff.json`),
25
+ JSON.stringify({schema_version:1,task_id:task,attempt,status:'ready_for_review',
26
+ changed_files:['src/a.ts'],implementation_sha256:'a'.repeat(64),
27
+ verification:[{command:'npm test',status:'passed',evidence:'ok'}],
28
+ evidence:['log'],blockers:[],scope_deviation:[],...payload}));
29
+ }
30
+
31
+ function review(dir,name,task,attempt,verdict){
32
+ fs.writeFileSync(path.join(dir,'.reviews',`${name}-${task}-r${attempt}.md`),
33
+ `---\nverdict: ${verdict}\nindependent: true\nscope:\n - src/a.ts\n---\n\n审查正文。\n`);
34
+ }
35
+
36
+ test('parseTasks 读取勾选状态并拒绝重复任务号',()=>{
37
+ const tasks=parseTasks('- [x] T-001: 建基线\n闲话\n- [ ] T-002: 接入检查\n');
38
+ assert.deepEqual(tasks.map(t=>[t.id,t.done,t.title]),
39
+ [['T-001',true,'建基线'],['T-002',false,'接入检查']]);
40
+ assert.throws(()=>parseTasks('- [ ] T-1: a\n- [ ] T-1: b\n'),FailoverError);
41
+ assert.throws(()=>parseTasks('# 没有任务行\n'),FailoverError);
42
+ });
43
+
44
+ test('全角冒号与大写 X 同样被识别',()=>{
45
+ const tasks=parseTasks('- [X] T-001:全角标题\n');
46
+ assert.deepEqual(tasks,[{id:'T-001',done:true,title:'全角标题'}]);
47
+ });
48
+
49
+ test('断点分类穷举每条分支',()=>{
50
+ const task={id:'T-001',done:false,title:'t'};
51
+ assert.equal(classifyBreakpoint({...task,done:true},[]).node,'N5');
52
+ assert.equal(classifyBreakpoint(task,[]).state,'not_started');
53
+ assert.equal(classifyBreakpoint(task,[{attempt:1,handoff:null,verdict:'approved'}]).state,
54
+ 'review_without_handoff');
55
+ assert.equal(classifyBreakpoint(task,
56
+ [{attempt:1,handoff:{status:'blocked',blockers:['x'],scopeDeviation:[]},verdict:null}]).state,'blocked');
57
+ const awaiting=classifyBreakpoint(task,
58
+ [{attempt:1,handoff:{status:'ready_for_review',changedFiles:['a'],contentBound:true},verdict:null}]);
59
+ assert.equal(awaiting.node,'N4');assert.equal(awaiting.state,'awaiting_review');
60
+ assert.equal(classifyBreakpoint(task,
61
+ [{attempt:1,handoff:{status:'ready_for_review'},verdict:'approved'}]).node,'N5');
62
+ const retry=classifyBreakpoint(task,
63
+ [{attempt:1,handoff:{status:'ready_for_review'},verdict:'changes_requested'}]);
64
+ assert.equal(retry.node,'N3');assert.equal(retry.attempt,2);
65
+ assert.equal(classifyBreakpoint(task,
66
+ [{attempt:2,handoff:{status:'ready_for_review'},verdict:'changes_requested'}]).state,'changes_exhausted');
67
+ assert.equal(classifyBreakpoint(task,
68
+ [{attempt:1,handoff:{status:'ready_for_review'},verdict:'blocked'}]).state,'review_blocked');
69
+ assert.equal(classifyBreakpoint(task,
70
+ [{attempt:1,handoff:{status:'ready_for_review'},verdict:'weird'}]).state,'unknown_verdict');
71
+ });
72
+
73
+ test('inspectSpecs 定位第一个未完成任务的断点',()=>{
74
+ const root=sandbox();
75
+ const dir=feature(root,'1.demo',[{id:'T-001',title:'a',done:true},{id:'T-002',title:'b',done:false}]);
76
+ handoff(dir,'1.demo','T-002',1,{});
77
+ const report=inspectSpecs(root);
78
+ assert.equal(report.features.length,1);
79
+ const only=report.features[0];
80
+ assert.equal(only.done,1);assert.equal(only.total,2);
81
+ assert.equal(only.currentTask.id,'T-002');
82
+ assert.equal(only.breakpoint.node,'N4');
83
+ assert.equal(only.breakpoint.contentBound,true);
84
+ });
85
+
86
+ test('直接指向 feature 目录与指向 specs 根等价',()=>{
87
+ const root=sandbox();
88
+ const dir=feature(root,'1.demo',[{id:'T-001',title:'a',done:false}]);
89
+ assert.equal(inspectSpecs(dir).features[0].feature,'1.demo');
90
+ assert.equal(inspectSpecs(root).features[0].feature,'1.demo');
91
+ });
92
+
93
+ test('全部完成后断点推进到 QA',()=>{
94
+ const root=sandbox();
95
+ feature(root,'1.demo',[{id:'T-001',title:'a',done:true}]);
96
+ assert.equal(inspectSpecs(root).features[0].breakpoint.node,'N6');
97
+ });
98
+
99
+ test('blocked 交接把阻塞项带进简报',()=>{
100
+ const root=sandbox();
101
+ const dir=feature(root,'1.demo',[{id:'T-001',title:'a',done:false}]);
102
+ handoff(dir,'1.demo','T-001',1,{status:'blocked',blockers:['缺少测试夹具'],
103
+ verification:[{command:'npm test',status:'failed',evidence:'red'}]});
104
+ const {text}=main(['handoff','--specs',root,'--to','codex']);
105
+ assert.match(text,/缺少测试夹具/);
106
+ assert.match(text,/N3(blocked)/);
107
+ });
108
+
109
+ test('第二次审查通过后断点是 N5 而非重复审查',()=>{
110
+ const root=sandbox();
111
+ const dir=feature(root,'1.demo',[{id:'T-001',title:'a',done:false}]);
112
+ handoff(dir,'1.demo','T-001',1,{});review(dir,'1.demo','T-001',1,'changes_requested');
113
+ handoff(dir,'1.demo','T-001',2,{attempt:2});review(dir,'1.demo','T-001',2,'approved');
114
+ assert.equal(inspectSpecs(root).features[0].breakpoint.node,'N5');
115
+ });
116
+
117
+ test('简报声明接管约束且不冒充完成授权',()=>{
118
+ const root=sandbox();
119
+ feature(root,'1.demo',[{id:'T-001',title:'a',done:false}]);
120
+ const {text}=main(['handoff','--specs',root,'--to','claude']);
121
+ assert.match(text,/不是完成授权/);
122
+ assert.match(text,/独立审查不得由实现者本人完成/);
123
+ assert.match(text,/developer: 主 codex \/ 备 claude/);
124
+ assert.match(text,/reviewer: 主 claude \/ 备 codex/);
125
+ });
126
+
127
+ test('角色主从与 runtime 契约一致',()=>{
128
+ assert.equal(ROLE_ROUTING.developer.primary,'codex');
129
+ assert.equal(ROLE_ROUTING.reviewer.primary,'claude');
130
+ for(const {primary,standby} of Object.values(ROLE_ROUTING))assert.notEqual(primary,standby);
131
+ });
132
+
133
+ test('工具全程只读,不改写 tasks.md',()=>{
134
+ const root=sandbox();
135
+ const dir=feature(root,'1.demo',[{id:'T-001',title:'a',done:false}]);
136
+ const tasksPath=path.join(dir,'tasks.md');
137
+ const before=fs.readFileSync(tasksPath,'utf8');
138
+ const entries=fs.readdirSync(path.join(dir,'.reviews'));
139
+ main(['status','--specs',root]);main(['handoff','--specs',root,'--to','codex']);
140
+ main(['status','--specs',root,'--json']);
141
+ assert.equal(fs.readFileSync(tasksPath,'utf8'),before);
142
+ assert.deepEqual(fs.readdirSync(path.join(dir,'.reviews')),entries);
143
+ });
144
+
145
+ test('拒绝 symlink 形式的 tasks.md',()=>{
146
+ const root=sandbox();
147
+ const real=path.join(root,'real.md');fs.writeFileSync(real,'- [ ] T-001: a\n');
148
+ const dir=path.join(root,'1.demo');fs.mkdirSync(dir);
149
+ fs.symlinkSync(real,path.join(dir,'tasks.md'));
150
+ assert.throws(()=>inspectSpecs(dir),/must not be a symlink/);
151
+ });
152
+
153
+ test('损坏的交接证据报错而不是静默跳过',()=>{
154
+ const root=sandbox();
155
+ const dir=feature(root,'1.demo',[{id:'T-001',title:'a',done:false}]);
156
+ fs.writeFileSync(path.join(dir,'.reviews','1.demo-T-001-a1-handoff.json'),'{不是 JSON');
157
+ assert.throws(()=>inspectSpecs(root),/not valid JSON/);
158
+ });
159
+
160
+ test('未知状态的交接证据被拒绝',()=>{
161
+ const root=sandbox();
162
+ const dir=feature(root,'1.demo',[{id:'T-001',title:'a',done:false}]);
163
+ handoff(dir,'1.demo','T-001',1,{status:'done'});
164
+ assert.throws(()=>inspectSpecs(root),/unknown status/);
165
+ });
166
+
167
+ test('probe 只报告可解析性并明说不等于配额可用',()=>{
168
+ const results=probeRuntimes(['codex','claude'],
169
+ {run:(command)=>command==='codex'?{ok:true,detail:'codex 1.0'}:{ok:false,detail:'ENOENT'}});
170
+ assert.deepEqual(results,[{runtime:'codex',available:true,detail:'codex 1.0'},
171
+ {runtime:'claude',available:false,detail:'ENOENT'}]);
172
+ const {text}=main(['probe']);
173
+ assert.match(text,/可解析 != 配额可用/);
174
+ });
175
+
176
+ test('CLI 参数校验',()=>{
177
+ const root=sandbox();
178
+ feature(root,'1.demo',[{id:'T-001',title:'a',done:false}]);
179
+ assert.throws(()=>main(['status']),/--specs is required/);
180
+ assert.throws(()=>main(['handoff','--specs',root,'--to','gemini']),/must be codex or claude/);
181
+ assert.throws(()=>main(['bogus','--specs',root]),/unknown command/);
182
+ assert.throws(()=>main(['status','--specs']),/missing value/);
183
+ assert.match(main(['--help']).text,/只读/);
184
+ });
@@ -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 os from 'node:os';
@@ -12,6 +12,12 @@ import {checkN4} from './cm-task-gate.mjs';
12
12
  import {fixCompletionProjection} from '../runtime/js/cm-fix/finish.mjs';
13
13
  import {loadConfig,resolveRole} from './cm-workflow-config.mjs';
14
14
 
15
+ // Keep runtime declarations and log mirrors independent of the invoking user's home.
16
+ const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-host-review-home-'));
17
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
18
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
19
+ after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
20
+
15
21
  for(const runtime of ['codex','claude']){
16
22
  test(`${runtime} CLI cause review requires opt-in and matching diagnostic, then resumes without dispatch`,async()=>{
17
23
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-host-review-')));