@aibyzero/cm-workflow 0.13.2 → 0.15.0

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 (97) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +28 -2
  4. package/VERSION +1 -1
  5. package/docs/installation.md +18 -3
  6. package/docs/js-workflow-control.md +2 -0
  7. package/docs/user-guide.md +16 -0
  8. package/install.ps1 +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +1 -0
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +53 -22
  12. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +4 -5
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +40 -17
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +103 -23
  15. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -4
  16. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +5 -2
  17. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  18. package/runtime/js/cm-ai/developer-adapter.mjs +17 -5
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +7 -2
  20. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  21. package/runtime/js/cm-ai/execution-store.mjs +25 -5
  22. package/runtime/js/cm-ai/host-check.mjs +20 -1
  23. package/runtime/js/cm-ai/host-conversation-execution.mjs +5 -4
  24. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  25. package/runtime/js/cm-ai/host-qa-executor.mjs +43 -21
  26. package/runtime/js/cm-ai/host-qa-policy.mjs +3 -1
  27. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +41 -3
  28. package/runtime/js/cm-ai/task-runner.mjs +1 -0
  29. package/runtime/js/cm-ai/worker-claude-developer.mjs +2 -1
  30. package/runtime/js/cm-fix/cause-package.mjs +3 -1
  31. package/runtime/js/cm-fix/dossier.mjs +7 -2
  32. package/runtime/js/cm-fix/reproduce.mjs +26 -5
  33. package/runtime/js/cm-init/draft-generation.mjs +3 -2
  34. package/runtime/js/cm-init/draft-inspection.mjs +17 -3
  35. package/runtime/js/cm-init/review-evidence.mjs +1 -1
  36. package/runtime/js/cm-prd/summary.mjs +6 -8
  37. package/runtime/js/cm-security/finalize.mjs +164 -0
  38. package/runtime/js/specs-status.mjs +66 -0
  39. package/scripts/cm-ai-admission.mjs +46 -7
  40. package/scripts/cm-ai-admission.test.mjs +50 -0
  41. package/scripts/cm-ai-batch-host.mjs +72 -10
  42. package/scripts/cm-ai-batch-host.test.mjs +128 -4
  43. package/scripts/cm-ai-batch-run.mjs +351 -17
  44. package/scripts/cm-ai-batch-run.test.mjs +190 -13
  45. package/scripts/cm-ai-bootstrap.test.mjs +10 -3
  46. package/scripts/cm-ai-host.mjs +38 -21
  47. package/scripts/cm-ai-host.test.mjs +75 -5
  48. package/scripts/cm-ai-multi-root.test.mjs +7 -1
  49. package/scripts/cm-ai-nested-execution.test.mjs +8 -2
  50. package/scripts/cm-ai-run.mjs +25 -15
  51. package/scripts/cm-ai-run.test.mjs +48 -0
  52. package/scripts/cm-blocked-reason.test.mjs +104 -0
  53. package/scripts/cm-capability-gate.test.mjs +179 -0
  54. package/scripts/cm-check-host.test.mjs +7 -1
  55. package/scripts/cm-codex-developer-adapter.test.mjs +70 -0
  56. package/scripts/cm-fix-cause-package.test.mjs +18 -1
  57. package/scripts/cm-fix-execution.test.mjs +31 -0
  58. package/scripts/cm-fix-host-review.test.mjs +9 -2
  59. package/scripts/cm-fix-host.test.mjs +2 -1
  60. package/scripts/cm-fix-observation-dossier.test.mjs +2 -0
  61. package/scripts/cm-fix-qa-source.test.mjs +1 -3
  62. package/scripts/cm-fix-reproduce.test.mjs +53 -2
  63. package/scripts/cm-fix-review-recovery.test.mjs +4 -3
  64. package/scripts/cm-host-check.test.mjs +22 -0
  65. package/scripts/cm-host-qa-executor.test.mjs +302 -3
  66. package/scripts/cm-host-qa-policy.test.mjs +34 -0
  67. package/scripts/cm-init-draft-generation.test.mjs +24 -3
  68. package/scripts/cm-init-draft-inspection.test.mjs +80 -0
  69. package/scripts/cm-init-host.mjs +2 -2
  70. package/scripts/cm-init-host.test.mjs +3 -1
  71. package/scripts/cm-init-session.test.mjs +37 -0
  72. package/scripts/cm-log-event.mjs +28 -7
  73. package/scripts/cm-prd-completion.test.mjs +7 -1
  74. package/scripts/cm-prd-design-phase.test.mjs +2 -1
  75. package/scripts/cm-prd-host.test.mjs +3 -2
  76. package/scripts/cm-prd-session-recovery.test.mjs +5 -4
  77. package/scripts/cm-runtime-i18n.mjs +32 -0
  78. package/scripts/cm-runtime-install.mjs +49 -23
  79. package/scripts/cm-runtime.mjs +45 -17
  80. package/scripts/cm-runtime.test.mjs +101 -0
  81. package/scripts/cm-security.mjs +12 -4
  82. package/scripts/cm-security.test.mjs +109 -0
  83. package/scripts/cm-specs-status.test.mjs +130 -0
  84. package/scripts/cm-workflow-config.mjs +4 -0
  85. package/scripts/test-shell-compat.sh +0 -0
  86. package/skills/cm-ai/references/N1-init.md +20 -15
  87. package/skills/cm-ai/references/N6-qa-eval.md +9 -4
  88. package/skills/cm-ai/references/js-host.md +10 -0
  89. package/skills/cm-fix/SKILL.md +5 -4
  90. package/skills/cm-fix/references/js-host.md +13 -0
  91. package/skills/cm-idea/SKILL.md +2 -0
  92. package/skills/cm-init/references/runtime-declaration.md +2 -0
  93. package/skills/cm-prd/SKILL.md +9 -8
  94. package/skills/cm-prd/references/spec-self-check.md +1 -0
  95. package/skills/cm-runtime/SKILL.md +23 -2
  96. package/skills/cm-security/SKILL.md +11 -6
  97. package/skills/cm-security/references/scan-contract.md +45 -1
@@ -0,0 +1,164 @@
1
+ // Final report authority lives here; model input supplies path reviews, never verdicts.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import {inventory} from './scan.mjs';
6
+ import {validBlockedReason} from '../cm-ai/effect-contract.mjs';
7
+
8
+ const need=(ok,code)=>{if(!ok)throw new Error(code);};
9
+ const inside=(root,file)=>file===root||file.startsWith(root+path.sep);
10
+ const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
11
+ const shape=(value,required,optional=[])=>need(object(value)&&required.every(k=>Object.hasOwn(value,k))
12
+ &&Object.keys(value).every(k=>[...required,...optional].includes(k)),'invalid_report_shape');
13
+ const list=(value,max)=>need(Array.isArray(value)&&value.length<=max,'report_array_limit');
14
+ const hex=value=>need(typeof value==='string'&&/^[a-f0-9]{64}$/.test(value),'invalid_digest');
15
+ const choice=(value,choices)=>need(choices.includes(value),'invalid_report_value');
16
+ const text=value=>{try{validBlockedReason(value);}catch{throw new Error('invalid_review_string');}};
17
+ const safePath=value=>{text(value);need(!path.isAbsolute(value)&&!/[\x00-\x1f\\]/.test(value)
18
+ &&value.split('/').every(p=>p&&p!=='.'&&p!=='..'&&p!=='.git'),'invalid_report_path');};
19
+ const integer=value=>need(Number.isSafeInteger(value)&&value>=0,'invalid_report_number');
20
+ const revision=value=>choice(value,['worktree','index']);
21
+ const redacted='[redacted]';
22
+ const reasons=['protected_path_not_read','scanner_control_excluded_review_manually','deleted_review_baseline',
23
+ 'symlink','non_regular','oversize','index_non_regular','index_oversize','source_changed',
24
+ 'no_scannable_files','tool_missing','local_rules_required','no_supported_lockfile_selected',
25
+ 'offline_database_required','timeout','execution_failed','unscanned_files',
26
+ 'offline_database_freshness_and_ecosystem_coverage_unverified','invalid_or_incomplete_report'];
27
+
28
+ function readExternal(project,file){
29
+ need(typeof file==='string','finalize_inputs_required');
30
+ const absolute=path.resolve(file),real=fs.realpathSync(absolute);
31
+ need(!inside(project,absolute)&&!inside(project,real)&&fs.lstatSync(absolute).isFile(),
32
+ 'report_must_be_external_regular_file');
33
+ const fd=fs.openSync(real,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
34
+ try{
35
+ const stat=fs.fstatSync(fd);need(stat.isFile(),'report_must_be_external_regular_file');
36
+ need(stat.size<=32*1024*1024,'report_size_limit');
37
+ const bytes=fs.readFileSync(fd);need(bytes.length<=32*1024*1024,'report_size_limit');
38
+ try{return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes));}
39
+ catch{throw new Error('invalid_report_json');}
40
+ }finally{fs.closeSync(fd);}
41
+ }
42
+
43
+ // Accept only scanner metadata, never arbitrary nested tool output or source bytes.
44
+ function validateScan(scan){
45
+ shape(scan,['schemaVersion','scope','comparison','digest','selected','files','gaps','untrackedExcluded',
46
+ 'businessMaps','tools','findings','aiReview','coverage','result','sourceUnchanged']);
47
+ need(scan.schemaVersion===1&&scan.aiReview==='pending'&&scan.coverage==='PARTIAL','invalid_scan_report');
48
+ choice(scan.scope,['all-tracked','branch-and-tracked-dirty']);hex(scan.digest);
49
+ choice(scan.result,['BLOCKED','FINDINGS','NO_FINDINGS','NO_CHANGES']);
50
+ need(typeof scan.sourceUnchanged==='boolean','completed_scan_required');
51
+ const c=scan.comparison;
52
+ if(scan.scope==='all-tracked'){shape(c,['head','mode']);choice(c.mode,['all']);}
53
+ else{
54
+ shape(c,['baseRef','base','head','branch','comparison','mergeBase','mainOnlyCommits','branchOnlyCommits',
55
+ 'shallow','dirty','remoteFreshness']);
56
+ safePath(c.baseRef);if(c.branch!==null)safePath(c.branch);
57
+ for(const v of [c.base,c.mergeBase])if(v!==null)need(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v),'invalid_comparison');
58
+ choice(c.comparison,['base-tree-to-head-tree']);
59
+ choice(c.remoteFreshness,['local_tracking_ref_not_fetched','local_branch_only']);
60
+ integer(c.mainOnlyCommits);integer(c.branchOnlyCommits);
61
+ need(typeof c.shallow==='boolean'&&typeof c.dirty==='boolean','invalid_comparison');
62
+ }
63
+ need(typeof c.head==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(c.head),'invalid_comparison');
64
+ list(scan.selected,2000);scan.selected.forEach(safePath);
65
+ const selected=new Set(scan.selected);need(selected.size===scan.selected.length,'duplicate_selected_path');
66
+ const selectedPath=value=>{safePath(value);need(selected.has(value),'invalid_scan_path');};
67
+ list(scan.files,4000);
68
+ for(const row of scan.files){shape(row,['path','revision','sha256']);selectedPath(row.path);revision(row.revision);hex(row.sha256);}
69
+ list(scan.gaps,10000);
70
+ for(const row of scan.gaps){shape(row,['reason'],['path']);choice(row.reason,reasons);if(row.path!==undefined)selectedPath(row.path);}
71
+ integer(scan.untrackedExcluded);list(scan.businessMaps,3);
72
+ for(const row of scan.businessMaps){
73
+ shape(row,['path','status','sha256']);choice(row.path,['docs/architecture.md','docs/codebase-context/00-index.md','docs/codebase-context/07-business-logic.md']);
74
+ choice(row.status,['untracked_or_nonregular_excluded','file','deleted','symlink','non_regular','oversize']);
75
+ if(row.sha256!==null)hex(row.sha256);
76
+ }
77
+ list(scan.tools,3);need(scan.tools.length===3,'completed_scan_required');const seen=new Set();
78
+ for(const row of scan.tools){
79
+ shape(row,['tool','status','reason'],['rulesSha256','version','exitCode','unscanned']);
80
+ choice(row.tool,['gitleaks','semgrep','osv']);need(!seen.has(row.tool),'duplicate_scan_tool');seen.add(row.tool);
81
+ choice(row.status,['NOT_RUN','ERROR','FINDINGS','NO_FINDINGS']);if(row.reason!==null)choice(row.reason,reasons);
82
+ if(row.rulesSha256!==undefined)hex(row.rulesSha256);
83
+ if(row.version!==undefined)need(typeof row.version==='string'&&/^(?:unknown|\d+\.\d+\.\d+)$/.test(row.version),'invalid_tool_version');
84
+ if(row.exitCode!==undefined&&row.exitCode!==null)integer(row.exitCode);
85
+ if(row.unscanned!==undefined){list(row.unscanned,4000);for(const item of row.unscanned){shape(item,['path','revision']);selectedPath(item.path);revision(item.revision);}}
86
+ }
87
+ list(scan.findings,100000);
88
+ for(const row of scan.findings){
89
+ shape(row,['path','revision','line','tool','rule','severity','verification']);selectedPath(row.path);revision(row.revision);
90
+ integer(row.line);need(row.line>0,'invalid_finding_line');choice(row.tool,['gitleaks','semgrep','osv']);
91
+ need(typeof row.rule==='string'&&/^[a-zA-Z0-9_.:/-]{1,200}$/.test(row.rule),'invalid_rule_id');
92
+ choice(row.severity,['high','medium','low','unknown']);choice(row.verification,['candidate']);
93
+ }
94
+ need(scan.sourceUnchanged||scan.result==='BLOCKED','invalid_scan_result');
95
+ return scan;
96
+ }
97
+
98
+ function validateReview(review,scan){
99
+ shape(review,['version','scanDigest','paths']);need(review.version===1,'invalid_review_version');
100
+ hex(review.scanDigest);need(review.scanDigest===scan.digest,'review_digest_mismatch');list(review.paths,2000);
101
+ const selected=new Set(scan.selected),seen=new Set();let count=0;
102
+ const paths=review.paths.map(row=>{
103
+ shape(row,['path','status'],['findings','reason']);safePath(row.path);
104
+ need(selected.has(row.path),'review_path_unknown');need(!seen.has(row.path),'review_path_duplicate');seen.add(row.path);
105
+ choice(row.status,['reviewed','not_reviewed']);
106
+ if(row.status==='not_reviewed'){
107
+ shape(row,['path','status','reason']);text(row.reason);
108
+ // Preserve analyst prose, including reasons, under the boundary below.
109
+ return {path:row.path,status:row.status,reason:row.reason};
110
+ }
111
+ shape(row,['path','status','findings']);list(row.findings,200);count+=row.findings.length;
112
+ need(count<=2000,'review_findings_limit');
113
+ const findings=row.findings.map(finding=>{
114
+ shape(finding,['severity','location','attacker','vector','existingControls','impact','confidence','recommendation']);
115
+ Object.values(finding).forEach(text);choice(finding.severity,['high','medium','low']);
116
+ choice(finding.confidence,['static-inference','observed']);
117
+ need(finding.location.startsWith(row.path+':')&&/^[1-9]\d*$/.test(finding.location.slice(row.path.length+1)),
118
+ 'invalid_review_location');
119
+ // Redaction applies to raw tool output and literal secrets, not analyst conclusions.
120
+ // Preserve validated prose verbatim. The model must not paste secrets or source
121
+ // into findings or reasons; JavaScript cannot verify that semantic obligation.
122
+ return {...finding};
123
+ });
124
+ return {path:row.path,status:row.status,findings};
125
+ });
126
+ for(const file of scan.selected)if(!seen.has(file))paths.push({path:file,status:'not_reviewed',reason:'not_reported'});
127
+ return {version:1,scanDigest:review.scanDigest,paths};
128
+ }
129
+
130
+ export function finalize(project,{scanFile,reviewFile}={}){
131
+ project=fs.realpathSync(project);
132
+ const scan=validateScan(readExternal(project,scanFile));
133
+ const reviewInput=readExternal(project,reviewFile);
134
+ const review=validateReview(reviewInput,scan);
135
+ const suppliedReasons=new Set(reviewInput.paths.filter(row=>row.status==='not_reviewed').map(row=>row.path));
136
+ // Reuse the exact scope resolver and hardened Git reader. Comparison identity is
137
+ // part of inventory's digest, so branch/base movement is drift too.
138
+ const current=inventory(project,{all:scan.scope==='all-tracked'});
139
+ const unchanged=current.digest===scan.digest;
140
+ const gaps=[...scan.gaps];
141
+ if(!unchanged)gaps.push({reason:'source_changed_during_review'});
142
+ const summaryGaps=[...gaps];
143
+ for(const row of review.paths)if(row.status==='not_reviewed'){
144
+ gaps.push({path:row.path,reason:row.reason});
145
+ summaryGaps.push({path:row.path,reason:suppliedReasons.has(row.path)?redacted:row.reason});
146
+ }
147
+ const coverage=review.paths.every(row=>row.status==='reviewed')&&!gaps.length
148
+ &&scan.tools.every(row=>['FINDINGS','NO_FINDINGS'].includes(row.status)&&!row.reason)?'FULL':'PARTIAL';
149
+ const findingsCount=scan.findings.length+review.paths.reduce((sum,row)=>sum+(row.findings?.length??0),0);
150
+ // Even FULL coverage with no findings means only "nothing found this round".
151
+ // REVIEWED_PARTIAL is intentional: there is no clean/safe verdict vocabulary.
152
+ const result=scan.result==='BLOCKED'||!unchanged?'BLOCKED':findingsCount?'FINDINGS':!scan.selected.length?'NO_CHANGES':'REVIEWED_PARTIAL';
153
+ const sourceUnchanged=scan.sourceUnchanged&&unchanged;
154
+ const report={...scan,review,gaps,coverage,result,aiReview:'completed',findingsCount,sourceUnchanged,
155
+ sourceWindows:{scan:{sourceUnchanged:scan.sourceUnchanged},review:{sourceUnchanged:unchanged,digest:current.digest}}};
156
+ // Resolve/check TMPDIR before creating anything: the output must remain external.
157
+ const tempRoot=fs.realpathSync(os.tmpdir());need(!inside(project,tempRoot),'external_temp_directory_required');
158
+ const directory=fs.mkdtempSync(path.join(tempRoot,'cm-security-final-'));
159
+ const reportPath=path.join(directory,'report.json');
160
+ try{fs.writeFileSync(reportPath,JSON.stringify(report,null,2)+'\n',{mode:0o600,flag:'wx'});}
161
+ catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
162
+ // Summary stdout excludes analyst prose; the private report retains it verbatim.
163
+ return {result,coverage,reportPath,gaps:summaryGaps,findingsCount,sourceUnchanged};
164
+ }
@@ -0,0 +1,66 @@
1
+ // Shared specs approval storage. Reading legacy data never upgrades its authority.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {randomUUID} from 'node:crypto';
5
+
6
+ const fields=['status','summaryDigest','at','features','specFiles','testCases','approval'];
7
+ const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
8
+ const hex=value=>typeof value==='string'&&/^[a-fA-F0-9]{64}$/.test(value);
9
+ const iso=value=>typeof value==='string'&&/^\d{4}-\d\d-\d\dT/.test(value)&&Number.isFinite(Date.parse(value));
10
+ const need=condition=>{if(!condition)throw new Error('spec_status_invalid');};
11
+
12
+ export function readSpecsStatus(specsDir){
13
+ const target=path.join(specsDir,'.cm-specs-status');
14
+ try{
15
+ // lstat distinguishes a missing file from a dangling, invalid symlink.
16
+ fs.lstatSync(target);
17
+ }catch(error){return {kind:error.code==='ENOENT'?'missing':'invalid'};}
18
+ try{
19
+ const root=fs.realpathSync(specsDir),real=fs.realpathSync(target),relative=path.relative(root,real);
20
+ need(relative!==''&&relative!=='..'&&!relative.startsWith(`..${path.sep}`)&&!path.isAbsolute(relative));
21
+ const source=JSON.parse(fs.readFileSync(real,'utf8'));
22
+ need(record(source)&&['approved','awaiting_review'].includes(source.status));
23
+ // Keep optional fields absent: admission distinguishes legacy omissions.
24
+ const value=Object.fromEntries(fields.filter(key=>Object.hasOwn(source,key)).map(key=>[key,source[key]]));
25
+ if(record(value.approval))value.approval=Object.fromEntries(['response','at']
26
+ .filter(key=>Object.hasOwn(value.approval,key)).map(key=>[key,value.approval[key]]));
27
+ return {kind:'valid',value};
28
+ }catch{return {kind:'invalid'};}
29
+ }
30
+
31
+ export function writeSpecsStatus(specsDir,value,{beforeRename=()=>{}}={}){
32
+ need(record(value)&&['approved','awaiting_review'].includes(value.status));
33
+ const summaryDigest=value.summaryDigest===undefined?null:value.summaryDigest;
34
+ need(summaryDigest===null||hex(summaryDigest));
35
+ need(iso(value.at)&&Array.isArray(value.features)&&value.features.length>0
36
+ &&value.features.every(name=>typeof name==='string'&&/^\d+\.[^/\\]+$/.test(name))
37
+ &&new Set(value.features).size===value.features.length);
38
+ const manifest=rows=>{
39
+ need(Array.isArray(rows));const seen=new Set();
40
+ return rows.map(item=>{
41
+ need(record(item)&&typeof item.path==='string'&&item.path!==''&&!path.isAbsolute(item.path)
42
+ &&!item.path.includes('\\')&&!item.path.split('/').some(part=>['','..','.'].includes(part))
43
+ &&!seen.has(item.path)&&hex(item.sha256));
44
+ seen.add(item.path);return {path:item.path,sha256:item.sha256};
45
+ });
46
+ };
47
+ const approval=value.approval??null;
48
+ need(approval===null||(value.status==='approved'&&record(approval)
49
+ &&typeof approval.response==='string'&&approval.response.trim()!==''&&iso(approval.at)));
50
+ const canonical={status:value.status,summaryDigest,at:value.at,features:[...value.features],
51
+ specFiles:manifest(value.specFiles),testCases:manifest(value.testCases),
52
+ approval:approval===null?null:{response:approval.response,at:approval.at}};
53
+ const bytes=Buffer.from(JSON.stringify(canonical)+'\n'),target=path.join(specsDir,'.cm-specs-status');
54
+ const temporary=path.join(specsDir,`.cm-specs-status-${randomUUID()}`);let fd;
55
+ try{
56
+ fd=fs.openSync(temporary,'wx',0o600);fs.writeFileSync(fd,bytes);fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
57
+ beforeRename();
58
+ fs.renameSync(temporary,target);
59
+ const dir=fs.openSync(specsDir,'r');try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
60
+ need(fs.readFileSync(target).equals(bytes));
61
+ return canonical;
62
+ }finally{
63
+ if(fd!==undefined)fs.closeSync(fd);
64
+ try{fs.unlinkSync(temporary);}catch(error){if(error.code!=='ENOENT')throw error;}
65
+ }
66
+ }
@@ -1,46 +1,85 @@
1
1
  #!/usr/bin/env node
2
- // Product CLI for the shipped read-only cm-ai N1/N2 admission authority.
2
+ // Product CLI for cm-ai N1/N2 inspection and explicit human approval.
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {fileURLToPath} from 'node:url';
6
- import {inspectCmAiAdmission} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
6
+ import {inspectCmAiAdmission,approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
7
+ import {validateRunDefinition} from './cm-ai-run.mjs';
7
8
 
8
- const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes]';
9
+ const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve --approval-response TEXT (no --yes)] [--print-run-definition --scope a,b [--requirements c,d] [--run-id X] [--repository-id Y]]';
9
10
 
10
11
  function parse(argv){
11
12
  const result={codeProjects:[]};
12
13
  for(let index=0;index<argv.length;index++){
13
14
  const flag=argv[index];
14
15
  if(flag==='--help'||flag==='-h')return {help:true};
16
+ if(flag==='--approve'){
17
+ if(result.approve)throw new Error('invalid arguments');
18
+ result.approve=true;continue;
19
+ }
20
+ if(flag==='--print-run-definition'){
21
+ if(result.printRunDefinition)throw new Error('invalid arguments');
22
+ result.printRunDefinition=true;continue;
23
+ }
15
24
  if(flag==='--yes'){if(result.assumeYes||Object.hasOwn(result,'approvalResponse'))throw new Error('approval input is duplicated');result.assumeYes=true;continue;}
16
25
  if(flag==='--code-project'){
17
26
  if(index+1>=argv.length||result.codeProjects.length>=16)throw new Error('invalid arguments');
18
27
  result.codeProjects.push(argv[++index]);continue;
19
28
  }
20
- const key={'--specs-dir':'specsDir','--approval-response':'approvalResponse'}[flag];
29
+ const key={'--specs-dir':'specsDir','--approval-response':'approvalResponse',
30
+ '--scope':'scope','--requirements':'requirements','--run-id':'runId','--repository-id':'repositoryId'}[flag];
21
31
  if(!key||index+1>=argv.length||Object.hasOwn(result,key))throw new Error('invalid arguments');
22
32
  result[key]=argv[++index];
23
33
  }
24
34
  if(!result.specsDir||result.codeProjects.length===0)throw new Error('specs and code project paths are required');
25
35
  if(result.assumeYes&&Object.hasOwn(result,'approvalResponse'))throw new Error('approval input is duplicated');
36
+ if(!result.printRunDefinition&&['scope','requirements','runId','repositoryId'].some(key=>Object.hasOwn(result,key)))
37
+ throw new Error('run definition options require --print-run-definition');
26
38
  return result;
27
39
  }
28
40
 
41
+ function buildRunDefinition(admission,input){
42
+ if(!admission.codeProject)throw new Error('--print-run-definition requires one --code-project');
43
+ let repositoryId=input.repositoryId;
44
+ if(repositoryId===undefined){
45
+ let name;
46
+ try{name=JSON.parse(fs.readFileSync(path.join(admission.codeProject,'package.json'),'utf8')).name;}
47
+ catch(error){if(error.code!=='ENOENT')throw error;}
48
+ repositoryId=name??path.basename(admission.codeProject);
49
+ }
50
+ const list=value=>value===undefined||value===''?[]:value.split(',').map(item=>item.trim());
51
+ const definition={version:1,specsDir:admission.specsDir,codeProject:admission.codeProject,
52
+ feature:admission.nextTask.feature,
53
+ identity:{repositoryId,runId:input.runId??`${admission.nextTask.feature.replace(/^\d+\./,'')}-${admission.nextTask.id}`,
54
+ taskId:admission.nextTask.id,attempt:1},
55
+ scope:list(input.scope),requirements:list(input.requirements)};
56
+ return validateRunDefinition(definition);
57
+ }
58
+
29
59
  export function main(argv=process.argv.slice(2)){
30
60
  let input;
31
61
  try{input=parse(argv);}catch(error){process.stderr.write(`${usage}\nERROR: ${error.message}\n`);return 2;}
32
62
  if(input.help){process.stdout.write(`${usage}\n`);return 0;}
33
- const projectResults=input.codeProjects.map(codeProject=>inspectCmAiAdmission({...input,codeProject}));
63
+ if(input.printRunDefinition&&!Object.hasOwn(input,'scope')){
64
+ process.stderr.write('--print-run-definition 需要 --scope:本任务允许修改的文件,相对代码根,逗号分隔(例:--scope src/todos.js,test/todos.test.js)\n');
65
+ return 2;
66
+ }
67
+ const approval=input.approve?approveCmAiSpecs(input):null;
68
+ const projectResults=approval?.projectResults??input.codeProjects.map(codeProject=>inspectCmAiAdmission({...input,codeProject}));
34
69
  const firstBlocked=projectResults.find(item=>item.state==='blocked');
35
70
  const reference=firstBlocked??projectResults[0];
36
71
  const decision=JSON.stringify({state:reference.state,reason:reference.reason,features:reference.features,nextTask:reference.nextTask});
37
72
  const mismatch=!firstBlocked&&projectResults.some(item=>JSON.stringify({state:item.state,reason:item.reason,features:item.features,nextTask:item.nextTask})!==decision);
38
73
  const selected=mismatch?{...reference,state:'blocked',reason:'project_admission_mismatch',nextTask:null}:reference;
39
- const result={...selected,codeProject:input.codeProjects.length===1?selected.codeProject:null,
74
+ const result={...selected,...(approval?.approveRefused?{approveRefused:approval.approveRefused}:{}),codeProject:input.codeProjects.length===1?selected.codeProject:null,
40
75
  codeProjects:projectResults.map(item=>item.codeProject),
41
76
  projectAdmissions:projectResults.map(item=>({codeProject:item.codeProject,state:item.state,reason:item.reason}))};
77
+ if(input.printRunDefinition&&!result.approveRefused&&result.state==='ready'){
78
+ try{process.stdout.write(`${JSON.stringify(buildRunDefinition(result,input))}\n`);return 0;}
79
+ catch(error){process.stderr.write(`${JSON.stringify({error:{code:error.code??error.message}})}\n`);return 1;}
80
+ }
42
81
  process.stdout.write(`${JSON.stringify(result)}\n`);
43
- return result.state==='blocked'?1:0;
82
+ return result.state==='blocked'||result.approveRefused?1:0;
44
83
  }
45
84
 
46
85
  function isMain(entry){
@@ -6,6 +6,7 @@ import path from 'node:path';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {parseFeatureTaskText,validDependencies} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
9
+ import {validateRunDefinition} from './cm-ai-run.mjs';
9
10
 
10
11
  const entry=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
11
12
  function fixture(run){
@@ -38,6 +39,46 @@ test('product admission reports generic continuation without approving or writin
38
39
  assert.equal(fs.readdirSync(root).length,2);
39
40
  }));
40
41
 
42
+ test('ready admission prints a directly valid run definition without writing the project',()=>fixture(({root,specs,code})=>{
43
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login'],testCases:[]}));
44
+ fs.writeFileSync(path.join(code,'package.json'),JSON.stringify({name:'login-app'}));
45
+ const before=fs.readFileSync(path.join(specs,'.cm-specs-status'));
46
+ const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,
47
+ '--print-run-definition','--scope','src/a.js'],{encoding:'utf8'});
48
+ assert.equal(result.status,0,result.stderr);assert.equal(result.stderr,'');
49
+ assert.equal(result.stdout.trim().split('\n').length,1);
50
+ const definition=JSON.parse(result.stdout);
51
+ assert.deepEqual(validateRunDefinition(definition),definition);
52
+ assert.deepEqual(definition,{version:1,specsDir:specs,codeProject:code,feature:'1.login',
53
+ identity:{repositoryId:'login-app',runId:'login-T-001',taskId:'T-001',attempt:1},scope:['src/a.js'],requirements:[]});
54
+ assert.deepEqual(fs.readFileSync(path.join(specs,'.cm-specs-status')),before);
55
+ assert.deepEqual(fs.readdirSync(root).sort(),['code','specs']);
56
+ assert.deepEqual(fs.readdirSync(code).sort(),['README.md','package.json']);
57
+ assert.deepEqual(fs.readdirSync(specs).sort(),['.cm-specs-status','1.login']);
58
+ }));
59
+
60
+ test('print-run-definition requires explicit scope and emits no draft when omitted',()=>fixture(({specs,code})=>{
61
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login'],testCases:[]}));
62
+ const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,
63
+ '--print-run-definition'],{encoding:'utf8'});
64
+ assert.equal(result.status,2);
65
+ assert.equal(result.stdout,'');
66
+ assert.equal(result.stderr,'--print-run-definition 需要 --scope:本任务允许修改的文件,相对代码根,逗号分隔(例:--scope src/todos.js,test/todos.test.js)\n');
67
+ }));
68
+
69
+ test('print-run-definition preserves non-ready admission output and exit status',()=>fixture(({specs,code})=>{
70
+ const args=[entry,'--specs-dir',specs,'--code-project',code];
71
+ for(const status of ['awaiting_review','invalid']){
72
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status,features:['1.login'],testCases:[]}));
73
+ const original=spawnSync(process.execPath,args,{encoding:'utf8'});
74
+ const printed=spawnSync(process.execPath,[...args,'--print-run-definition','--scope','src/a.js'],{encoding:'utf8'});
75
+ assert.notEqual(JSON.parse(printed.stdout).state,'ready');
76
+ assert.equal(printed.status,original.status);
77
+ assert.equal(printed.stdout,original.stdout);assert.equal(printed.stderr,original.stderr);
78
+ assert(!Object.hasOwn(JSON.parse(printed.stdout),'identity'));
79
+ }
80
+ }));
81
+
41
82
  function writeFeature(specs,name,source){
42
83
  const target=path.join(specs,name);fs.mkdirSync(target,{recursive:true});
43
84
  for(const file of ['requirements.md','design.md'])fs.writeFileSync(path.join(target,file),'# Fixture\n');
@@ -135,3 +176,12 @@ test('three punctuated historical features admit the new feature without changin
135
176
  assert.deepEqual(result.nextTask,{feature:'2.profile',id:'T-002',description:'second'});
136
177
  assert.deepEqual(result.features.map(item=>item.name),names.slice(0,2));
137
178
  }));
179
+
180
+ test('parallel eligibility preserves nextTask and returns only dependency-ready members',()=>fixture(({specs,code})=>{
181
+ fs.writeFileSync(path.join(specs,'1.login','tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n- [ ] T-003: final\n\n- T-003 依赖 T-001, T-002\n');
182
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login']}));
183
+ const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code],{encoding:'utf8'});
184
+ assert.equal(result.status,0,result.stderr);const admission=JSON.parse(result.stdout);
185
+ assert.equal(admission.nextTask.id,'T-001');
186
+ assert.deepEqual(admission.eligibleTasks,[{feature:'1.login',id:'T-001'},{feature:'1.login',id:'T-002'}]);
187
+ }));
@@ -4,17 +4,44 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {fileURLToPath} from 'node:url';
6
6
  import {createCmAiBatch} from './cm-ai-batch-run.mjs';
7
- import {createConversationExecution,readConversationReviewConfiguration,readConversationProtection} from './cm-ai-host.mjs';
7
+ import {createConversationExecution,readConversationReviewConfiguration,readConversationProtection,runReviewPreflight} from './cm-ai-host.mjs';
8
+ import {loadConfig,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
9
+ import {preflightMatches} from '../runtime/js/cm-ai/worker-codex.mjs';
10
+ import {claudePreflightMatches} from '../runtime/js/cm-ai/worker-claude.mjs';
8
11
  import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
9
12
  import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
10
- import {validateHostWorkflowConfiguration} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
13
+ import {validateHostWorkflowConfiguration,featureHasBrowserCases,readBrowserCapability} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
11
14
  import {digest,json,need,shape} from '../runtime/js/cm-ai/effect-contract.mjs';
12
15
 
13
- const usage='cm-ai-batch-host.mjs serve --config PATH --host-context ID --allow-development [--runtime codex|claude] [--review-config PATH] [--allow-review FEATURE/TASK:1|2]... [--allow-qa]';
16
+ const usage='cm-ai-batch-host.mjs serve --config PATH --host-context ID --allow-development [--runtime codex|claude] [--review-config PATH] [--allow-review FEATURE/TASK:1|2]... [--allow-qa] [--browser-qa available|unavailable] [--protected-conversation-config PATH | --protected-config PATH] [--allow-provider-development FEATURE/TASK:1|2]...';
14
17
  const safeCode=error=>typeof error?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(error.code)?error.code:'batch_host_failed';
15
18
 
19
+ async function memberReviewConfiguration(batch,definition,review,runtime){
20
+ try{
21
+ need(review!==null,'review_configuration_required');
22
+ const options={cwd:definition.codeProject,model:review.model,disabledSkills:review.disabledSkills,promptTransport:'stdin'};
23
+ const matches=config=>config.model===review.model&&digest(config.disabledSkills)===digest(review.disabledSkills)
24
+ &&(runtime==='claude'?claudePreflightMatches:preflightMatches)(config.preflight,options);
25
+ const directory=path.join(batch.specsDir,'.reviews','.execution',batch.batchId);
26
+ fs.mkdirSync(directory,{recursive:true,mode:0o700});
27
+ need(fs.realpathSync(directory)===directory,'invalid_preflight_cache');
28
+ const file=path.join(directory,`preflight-${definition.identity.taskId}.json`);
29
+ if(fs.existsSync(file)){
30
+ const info=fs.lstatSync(file);need(info.isFile()&&!info.isSymbolicLink(),'invalid_preflight_cache');
31
+ try{const cached=readConversationReviewConfiguration(file);if(matches(cached))return cached;}
32
+ catch{/* Invalid or obsolete diagnostics require a fresh loopback, never a rewritten fingerprint. */}
33
+ }
34
+ const config=await runReviewPreflight(definition,{model:review.model,runtime,disabledSkills:review.disabledSkills});
35
+ need(matches(config),'review_preflight_failed');
36
+ const temporary=`${file}.${process.pid}.tmp`;
37
+ fs.writeFileSync(temporary,JSON.stringify(config)+'\n',{flag:'wx',mode:0o600});
38
+ try{fs.renameSync(temporary,file);}finally{if(fs.existsSync(temporary))fs.unlinkSync(temporary);}
39
+ return config;
40
+ }catch{need(false,'review_preflight_failed');}
41
+ }
42
+
16
43
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
17
- if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nOptional --protected-conversation-config PATH uses the shared current-host scoped text proposals and native sandbox checks; {checkCommands,timeoutMs}. No extra model call, same Codex/Claude runtime and per-task Review permissions. Optional bundle.bootstraps maps approved bootstrap task keys to {selection}; --allow-bootstrap-write grants only those fixed instruction/scaffold steps. Optional batch.codeProjects uses prefixed paths and checks with codeProject per command; one task remains one completion gate.\n');return 0;}
44
+ if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nOptional --protected-conversation-config PATH uses the shared current-host scoped text proposals and native sandbox checks; {checkCommands,timeoutMs}. No extra model call, same Codex/Claude runtime and per-task Review permissions. Optional --protected-config PATH {model,checkCommands,timeoutMs} enables CLI development only for per-task --allow-provider-development FEATURE/TASK:1|2 grants; mutually exclusive with --protected-conversation-config. Optional bundle.bootstraps maps approved bootstrap task keys to {selection}; --allow-bootstrap-write grants only those fixed instruction/scaffold steps. Optional batch.codeProjects uses prefixed paths and checks with codeProject per command; one task remains one completion gate.\nBatch entry requires a clean Git main checkout (including untracked files); batch_main_dirty lists dirty files before any task or worktree starts. Serial tasks are committed automatically before batch_handoff, with task_commit recording the SHA (null if unchanged). Terminal parallel members preserve WIP on their retained branches and fall back once to serial generation 2 after ready members merge.\n');return 0;}
18
45
  let bridge;
19
46
  try{
20
47
  need(argv.length>=6&&argv[0]==='serve'&&argv[1]==='--config'&&argv[3]==='--host-context'
@@ -32,13 +59,28 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
32
59
  }
33
60
  need(keys.length===Object.keys(workflows).length&&keys.every(key=>Object.hasOwn(workflows,key)),'workflow_task_mismatch');
34
61
  for(const key of keys)if(workflows[key]!==null)validateHostWorkflowConfiguration(workflows[key]);
35
- let review=null,allowQa=false,allowBootstrap=false,runtime=null,protection=null;const approvals=new Set();
62
+ let review=null,allowQa=false,allowBootstrap=false,runtime=null,protection=null,providerConfig=null,browserQaFlag;const approvals=new Set(),developments=new Map();
36
63
  for(let index=6;index<argv.length;index++){
37
64
  const name=argv[index];
38
65
  if(name==='--allow-qa'){need(!allowQa,'invalid_arguments');allowQa=true;}
66
+ else if(name==='--browser-qa'){
67
+ need(browserQaFlag===undefined&&typeof argv[index+1]==='string','invalid_arguments');browserQaFlag=argv[++index];
68
+ }
39
69
  else if(name==='--allow-bootstrap-write'){need(!allowBootstrap&&bootstraps!==null,'invalid_arguments');allowBootstrap=true;}
40
70
  else if(name==='--protected-conversation-config'){
41
- need(protection===null&&typeof argv[index+1]==='string','invalid_arguments');protection=readConversationProtection(argv[++index]);
71
+ need(protection===null&&providerConfig===null&&typeof argv[index+1]==='string','invalid_arguments');protection=readConversationProtection(argv[++index]);
72
+ }
73
+ else if(name==='--protected-config'){
74
+ need(protection===null&&providerConfig===null&&typeof argv[index+1]==='string','invalid_arguments');
75
+ const file=argv[++index],info=fs.lstatSync(file);
76
+ need(info.isFile()&&!info.isSymbolicLink()&&info.size<=64*1024,'invalid_protected_config');
77
+ providerConfig=json(JSON.parse(fs.readFileSync(file,'utf8')));shape(providerConfig,['model','checkCommands','timeoutMs']);
78
+ }
79
+ else if(name==='--allow-provider-development'){
80
+ const approval=argv[++index];need(typeof approval==='string','invalid_arguments');
81
+ const split=approval.lastIndexOf(':'),key=approval.slice(0,split),attempt=approval.slice(split+1);
82
+ need(keys.includes(key)&&['1','2'].includes(attempt),'invalid_arguments');
83
+ need(!developments.has(key),'invalid_arguments');developments.set(key,Number(attempt));
42
84
  }
43
85
  else if(name==='--runtime'){
44
86
  need(runtime===null&&['codex','claude'].includes(argv[index+1]),'invalid_runtime');runtime=argv[++index];
@@ -50,16 +92,36 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
50
92
  need(keys.includes(key)&&['1','2'].includes(attempt),'review_task_mismatch');approvals.add(approval);
51
93
  }else need(false,'invalid_arguments');
52
94
  }
95
+ need(!developments.size||providerConfig!==null,'protected_configuration_required');
96
+ // Same launch-time assertion as the single-task host, evaluated across every
97
+ // task whose approved contract can select a browser case.
98
+ readBrowserCapability(browserQaFlag,keys.some(key=>workflows[key]?.qa!=null
99
+ &&featureHasBrowserCases(batch.specsDir,key.slice(0,key.lastIndexOf('/')),batch.codeProject)));
53
100
  need(!approvals.size||review!==null,'review_configuration_required');
54
101
  need(allowQa||!Object.values(workflows).some(item=>item?.qa!=null),'qa_authorization_required');
55
102
  bridge=createHostToolBridge();
103
+ // The current conversation transport accepts one outstanding host call.
104
+ // Queue those calls only; member runners and independent Review stay concurrent.
105
+ let hostCallTail=Promise.resolve();
106
+ const memberBridge={call(...args){
107
+ const pending=hostCallTail.then(()=>bridge.call(...args));
108
+ hostCallTail=pending.then(()=>{},()=>{});return pending;
109
+ }};
56
110
  const driver=createCmAiBatch({configuration:batch,logHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
57
- executionFor:definition=>{
111
+ runtime:runtime??'codex',checkCommands:(providerConfig??protection)?.checkCommands??null,checkTimeoutMs:(providerConfig??protection)?.timeoutMs??60000,
112
+ executionFor:async(definition,{parallelMember=false}={})=>{
58
113
  const key=`${definition.feature}/${definition.identity.taskId}`;
59
114
  const attempts=[1,2].filter(attempt=>approvals.has(`${key}:${attempt}`));
60
- const execution=createConversationExecution(definition,argv[4],bridge,review,attempts,workflows[key],allowQa,runtime??'codex',
61
- {batchWorkflowsDigest:digest(bootstraps?{workflows,bootstraps}:workflows),qaLogHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
62
- ...(protection?{protection}:{}),...(bootstraps?.[key]?{bootstrap:{...bootstraps[key],allowWrite:allowBootstrap}}:{})});
115
+ const memberReview=parallelMember?await memberReviewConfiguration(batch,definition,review,runtime??'codex'):review;
116
+ const execution=createConversationExecution(definition,argv[4],parallelMember?memberBridge:bridge,memberReview,attempts,workflows[key],allowQa,runtime??'codex',
117
+ {parallelMember,batchWorkflowsDigest:digest(bootstraps?{workflows,bootstraps}:workflows),qaLogHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
118
+ // A protected CLI config also protects unauthorized tasks: they stay on the
119
+ // current-session transport but with the same sandbox checks (protected-text edits).
120
+ ...(protection?{protection}:providerConfig?{protection:{checkCommands:providerConfig.checkCommands,timeoutMs:providerConfig.timeoutMs}}:{}),
121
+ ...(developments.has(key)?{
122
+ providerDevelopment:{model:providerConfig.model,attempt:developments.get(key),
123
+ ...resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),runtime??'codex')},
124
+ }:{}),...(bootstraps?.[key]?{bootstrap:{...bootstraps[key],allowWrite:allowBootstrap}}:{})});
63
125
  // Bind the entire approved capability map before the first task starts,
64
126
  // so a later task's commands/scope cannot silently change during resume.
65
127
  return execution;