@aibyzero/cm-workflow 0.16.5 → 0.16.6

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 +14 -0
  3. package/CHANGELOG.md +7 -0
  4. package/README.md +11 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +28 -7
  17. package/docs/js-workflow-control.md +48 -0
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/untested-branches.md +27 -4
  21. package/docs/user-guide.md +23 -8
  22. package/install-codex.sh +28 -11
  23. package/package.json +1 -1
  24. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  25. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  26. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +79 -20
  27. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +1 -4
  28. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
  29. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  30. package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
  31. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  32. package/runtime/js/cm-ai/drive-bootstrap.mjs +20 -10
  33. package/runtime/js/cm-ai/drive-core.mjs +9 -3
  34. package/runtime/js/cm-ai/durable-runner-state.mjs +117 -14
  35. package/runtime/js/cm-ai/effect-contract.mjs +1 -1
  36. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  37. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  38. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  39. package/runtime/js/cm-ai/external-models.mjs +52 -0
  40. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  41. package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
  42. package/runtime/js/cm-ai/host-check.mjs +30 -4
  43. package/runtime/js/cm-ai/host-conversation-execution.mjs +50 -16
  44. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  45. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  46. package/runtime/js/cm-ai/host-qa-executor.mjs +2 -2
  47. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
  48. package/runtime/js/cm-ai/host-session.mjs +1 -1
  49. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
  50. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  51. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  52. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  53. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  54. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  55. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  56. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  57. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  58. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  59. package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
  60. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  61. package/runtime/js/cm-ai/review-package.mjs +11 -0
  62. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  63. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  64. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  65. package/runtime/js/cm-ai/task-runner.mjs +171 -25
  66. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  67. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  68. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  69. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  70. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  71. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  72. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  73. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  74. package/runtime/js/cm-fix/execution.mjs +183 -40
  75. package/runtime/js/cm-fix/final-review.mjs +18 -10
  76. package/runtime/js/cm-fix/host-review.mjs +25 -6
  77. package/runtime/js/cm-fix/host.mjs +4 -1
  78. package/runtime/js/cm-fix/layout.mjs +1 -1
  79. package/runtime/js/cm-fix/progress.mjs +4 -0
  80. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  81. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  82. package/runtime/js/cm-prd/review-publication.mjs +23 -13
  83. package/runtime/js/cm-prd/review-time.mjs +29 -0
  84. package/runtime/js/cm-prd/session.mjs +53 -6
  85. package/runtime/js/cm-security/finalize.mjs +32 -0
  86. package/runtime/review.md +5 -0
  87. package/runtime/task-gates.md +6 -0
  88. package/runtime/workflow-config.md +10 -1
  89. package/scripts/cm-ai-batch-drive.mjs +50 -21
  90. package/scripts/cm-ai-batch-drive.test.mjs +47 -2
  91. package/scripts/cm-ai-batch-host.mjs +37 -14
  92. package/scripts/cm-ai-batch-run.mjs +71 -27
  93. package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
  94. package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
  95. package/scripts/cm-ai-bootstrap.test.mjs +80 -87
  96. package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
  97. package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
  98. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
  99. package/scripts/cm-ai-drive.mjs +59 -25
  100. package/scripts/cm-ai-drive.test.mjs +97 -1
  101. package/scripts/cm-ai-host.mjs +64 -24
  102. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  103. package/scripts/cm-ai-progress.test.mjs +521 -0
  104. package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
  105. package/scripts/cm-ai-review-failure.test.mjs +71 -11
  106. package/scripts/cm-ai-run.mjs +58 -14
  107. package/scripts/cm-ai-run.test.mjs +2 -1
  108. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  109. package/scripts/cm-check-drive.test.mjs +1 -0
  110. package/scripts/cm-check-runtime.sh +11 -0
  111. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  112. package/scripts/cm-claude-probe.test.mjs +1 -1
  113. package/scripts/cm-codex-plugin-metadata.py +83 -0
  114. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  115. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  116. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  117. package/scripts/cm-efficiency-offline.mjs +35 -0
  118. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  119. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  120. package/scripts/cm-efficiency-response.test.mjs +117 -0
  121. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  122. package/scripts/cm-external-batch-host.test.mjs +157 -0
  123. package/scripts/cm-external-fix-host.test.mjs +281 -0
  124. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  125. package/scripts/cm-external-group-models.test.mjs +60 -0
  126. package/scripts/cm-external-model-host.test.mjs +180 -0
  127. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  128. package/scripts/cm-external-models.test.mjs +89 -0
  129. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  130. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  131. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  132. package/scripts/cm-fix-drive.mjs +28 -13
  133. package/scripts/cm-fix-final-review.test.mjs +11 -6
  134. package/scripts/cm-fix-host.mjs +17 -10
  135. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  136. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  137. package/scripts/cm-fix-review-budget.test.mjs +7 -1
  138. package/scripts/cm-host-qa-executor.test.mjs +21 -0
  139. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  140. package/scripts/cm-live-evidence.test.mjs +64 -0
  141. package/scripts/cm-log-event.mjs +8 -2
  142. package/scripts/cm-log-event.py +15 -0
  143. package/scripts/cm-model-setup.mjs +79 -0
  144. package/scripts/cm-prd-drive.mjs +32 -11
  145. package/scripts/cm-prd-drive.test.mjs +15 -0
  146. package/scripts/cm-prd-host.mjs +13 -4
  147. package/scripts/cm-release-smoke.sh +5 -1
  148. package/scripts/cm-runtime-i18n.mjs +15 -4
  149. package/scripts/cm-runtime-install.mjs +8 -4
  150. package/scripts/cm-runtime.mjs +116 -23
  151. package/scripts/cm-runtime.test.mjs +121 -12
  152. package/scripts/cm-security.test.mjs +32 -0
  153. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  154. package/scripts/cm-task-gate.mjs +146 -10
  155. package/scripts/cm-task-gate.py +1 -0
  156. package/scripts/cm-test-drive.mjs +10 -4
  157. package/scripts/cm-test-drive.test.mjs +14 -1
  158. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  159. package/scripts/cm-usage-report.py +22 -3
  160. package/scripts/cm-workflow-config.mjs +10 -1
  161. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  162. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  163. package/scripts/fixtures/process-cleanup.mjs +3 -1
  164. package/scripts/test-cm-native-usage.py +62 -0
  165. package/scripts/test-external-model-setup.py +91 -0
  166. package/scripts/test-model-configuration-write.py +201 -0
  167. package/scripts/test-npm-install.py +10 -1
  168. package/skills/cm-ai/SKILL.md +2 -2
  169. package/skills/cm-ai/references/N8-finish.md +5 -0
  170. package/skills/cm-ai/references/js-host.md +13 -5
  171. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  172. package/skills/cm-fix/SKILL.md +1 -1
  173. package/skills/cm-fix/references/js-host.md +30 -2
  174. package/skills/cm-runtime/SKILL.md +29 -6
  175. package/skills/cm-security/SKILL.md +4 -2
  176. package/skills/cm-security/references/scan-contract.md +1 -0
  177. package/templates/cm-workflow.yml +1 -1
@@ -2,11 +2,12 @@
2
2
  // Standalone runtime preferences; never mutates an existing run or dispatches AI.
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
- import {randomUUID} from 'node:crypto';
5
+ import {randomUUID,createHash} from 'node:crypto';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {ConfigError,findConfig,loadConfig,readConfigText,parseUserRuntimes,
9
- userRuntimesPath,runtimePreset,RUNTIME_PRESETS,resolveRole,runtimesSource} from './cm-workflow-config.mjs';
9
+ userRuntimesPath,runtimePreset,RUNTIME_PRESETS,resolveRole,runtimesSource,
10
+ CONFIG_FILENAMES,previewUserRuntimeConfig} from './cm-workflow-config.mjs';
10
11
  import {editRuntimeDeclaration} from './cm-runtime-edit.mjs';
11
12
  import {runtimeLanguage,runtimeText as t} from './cm-runtime-i18n.mjs';
12
13
  import {askRuntimePreset,runtimeQuestions,PromptCancelled} from './cm-runtime-install.mjs';
@@ -32,11 +33,17 @@ export function atomicRuntimeWrite(file,text,{before=null,privateFile=false}={})
32
33
  fs.renameSync(temporary,file);
33
34
  }finally{if(stat(temporary))fs.unlinkSync(temporary);}
34
35
  }
35
- export function writeUserRuntime(preset,{lang=runtimeLanguage()}={}){
36
- const declaration=runtimePreset(preset),file=userRuntimesPath();
37
- safeTarget(file);
36
+ function userRuntimeText(preset,lang){
37
+ const declaration=runtimePreset(preset);
38
38
  const text=`# ${t('comment',lang)}\nruntimes: {available: ${declaration.runtimes.available}}\npreset: ${preset}\n`;
39
- parseUserRuntimes(text);
39
+ parseUserRuntimes(text);return text;
40
+ }
41
+ export function writeUserRuntime(preset,{lang=runtimeLanguage(),preview}={}){
42
+ if(preview){
43
+ if(preview.scope!=='user'||preview.preset!==preset)throw new ConfigError('runtime preview does not match requested preset/scope');
44
+ return applyRuntimePreview(preview);
45
+ }
46
+ const text=userRuntimeText(preset,lang),file=userRuntimesPath();safeTarget(file);
40
47
  atomicRuntimeWrite(file,text,{before:stat(file)?fs.readFileSync(file):null,privateFile:true});
41
48
  return file;
42
49
  }
@@ -45,20 +52,23 @@ function projectDirectory(raw){
45
52
  if(!fs.statSync(root).isDirectory())throw new ConfigError('project must be a directory');
46
53
  return root;
47
54
  }
48
- export function setProjectRuntime(project,preset){
55
+ function prepareProjectRuntime(project,preset){
49
56
  const root=projectDirectory(project),declaration=runtimePreset(preset);
50
57
  // Reject broken links/directories too, even though findConfig only finds files.
51
- for(const name of ['.cm-workflow.yml','.cm-workflow.yaml','.cm-workflow.json'])safeTarget(path.join(root,name));
58
+ for(const name of CONFIG_FILENAMES)safeTarget(path.join(root,name));
52
59
  const existing=findConfig(root),file=existing??path.join(root,'.cm-workflow.yml');
53
60
  const before=existing?fs.readFileSync(file):null;
54
61
  const original=readConfigText(existing??path.join(scripts,'../templates/cm-workflow.yml'));
55
62
  loadConfig({projectRoot:root,configPath:file,text:original});
56
63
  const text=editRuntimeDeclaration(original,file,declaration);
57
- loadConfig({projectRoot:root,configPath:file,text});
64
+ const effective=loadConfig({projectRoot:root,configPath:file,text});
65
+ return {file,text,before,effective};
66
+ }
67
+ export function setProjectRuntime(project,preset){
68
+ const {file,text,before}=prepareProjectRuntime(project,preset);
58
69
  atomicRuntimeWrite(file,text,{before});return file;
59
70
  }
60
- export function showRuntime(project,{runtime=process.env.CM_RUNTIME||'codex',probe=probeRuntimes,lang=runtimeLanguage()}={}){
61
- const config=loadConfig({projectRoot:project});
71
+ function describeRuntime(config,{runtime=process.env.CM_RUNTIME||'codex',lang=runtimeLanguage()}={}){
62
72
  const preset=Object.keys(RUNTIME_PRESETS).find(name=>{
63
73
  const value=runtimePreset(name);
64
74
  return config.runtimes.available===value.runtimes.available
@@ -67,14 +77,86 @@ export function showRuntime(project,{runtime=process.env.CM_RUNTIME||'codex',pro
67
77
  const lines=[`runtimes.available: ${config.runtimes.available}`,`preset: ${preset}`,`runtimes_source: ${runtimesSource(config)}`];
68
78
  for(const role of ['coder','reviewer']){
69
79
  const resolved=resolveRole(config,role,runtime);
70
- lines.push(`${role}: adapter=${resolved.adapter} source=${resolved.source} route_state=${resolved.route_state}${resolved.route_state==='declared-adapter'?t('declared',lang):''}`);
80
+ lines.push(`${role}: adapter=${resolved.adapter} source=${resolved.source} model=${resolved.model} route_state=${resolved.route_state}${resolved.route_state==='declared-adapter'?t('declared',lang):''}`);
71
81
  }
82
+ return lines.join('\n');
83
+ }
84
+ export function showRuntime(project,{runtime=process.env.CM_RUNTIME||'codex',probe=probeRuntimes,lang=runtimeLanguage()}={}){
85
+ const config=loadConfig({projectRoot:project}),source=runtimesSource(config);
86
+ const file=source==='user'?userRuntimesPath():source==='project'?findConfig(project):null;
87
+ const lines=[describeRuntime(config,{runtime,lang}),`declaration_file: ${file??t('builtin',lang)}`];
72
88
  const wanted=config.runtimes.available==='both'?['codex','claude']:config.runtimes.available==='unknown'?[]:[config.runtimes.available];
73
89
  for(const result of probe(wanted))lines.push(result.available
74
90
  ?t('cli',lang,{runtime:result.runtime})
75
91
  :t('warning',lang,{available:config.runtimes.available,runtime:result.runtime}));
76
92
  return lines.join('\n');
77
93
  }
94
+ const previewPlans=new WeakMap();
95
+ const sha256=value=>createHash('sha256').update(value).digest('hex');
96
+ function snapshot(file){safeTarget(file);return {file,before:stat(file)?Buffer.from(readConfigText(file)):null};}
97
+ function assertSnapshots(snapshots,lang){
98
+ for(const {file,before} of snapshots){
99
+ safeTarget(file);const current=stat(file)?fs.readFileSync(file):null;
100
+ if(before===null?current!==null:current===null||!current.equals(before))throw new ConfigError(t('drift',lang,{file}));
101
+ }
102
+ }
103
+ const runtimeFields=config=>({
104
+ 'runtimes.available':config.runtimes.available,
105
+ ...Object.fromEntries(['coder','reviewer'].flatMap(role=>['adapter','source'].map(field=>[`roles.${role}.${field}`,config.roles[role][field]]))),
106
+ });
107
+ // null project is the installer: preview user defaults only, with no incidental cwd project.
108
+ export function prepareRuntimePreview(project,preset,{user=false,lang=runtimeLanguage()}={}){
109
+ runtimePreset(preset);
110
+ if(project===null&&!user)throw new ConfigError('project is required for a project preview');
111
+ const root=project===null?null:projectDirectory(project),snapshots=root?CONFIG_FILENAMES.map(name=>snapshot(path.join(root,name))):[];
112
+ let current=root?loadConfig({projectRoot:root}):null;
113
+ const userFile=userRuntimesPath();
114
+ if(user||current&&runtimesSource(current)!=='project')snapshots.push(snapshot(userFile));
115
+ if(root)current=loadConfig({projectRoot:root});
116
+ let candidate,changes;
117
+ if(user){
118
+ const previous=snapshots.find(item=>item.file===userFile).before;
119
+ const old=previous===null?null:parseUserRuntimes(previous.toString('utf8'));
120
+ candidate={file:userFile,before:previous,text:userRuntimeText(preset,lang),
121
+ effective:root?previewUserRuntimeConfig({projectRoot:root},preset):null};
122
+ changes=[{field:'runtimes.available',before:old?.runtimes.available??null,after:runtimePreset(preset).runtimes.available},
123
+ {field:'preset',before:old?.preset??null,after:preset}];
124
+ }else{
125
+ if(!findConfig(root))snapshots.push(snapshot(path.join(scripts,'../templates/cm-workflow.yml')));
126
+ candidate=prepareProjectRuntime(root,preset);
127
+ const before=runtimeFields(current),after=runtimeFields(runtimePreset(preset));
128
+ changes=Object.keys(after).map(field=>({field,before:before[field],after:after[field]}));
129
+ }
130
+ assertSnapshots(snapshots,lang);
131
+ const report={scope:user?'user':'project',project:root,target:candidate.file,preset,creates_file:candidate.before===null,changes,
132
+ current:current?describeRuntime(current,{lang}):null,effective:candidate.effective?describeRuntime(candidate.effective,{lang}):null,
133
+ project_overrides_user:user&&current!==null&&runtimesSource(current)==='project'};
134
+ const digest=sha256(JSON.stringify({version:1,report,candidate:sha256(candidate.text),
135
+ inputs:snapshots.map(({file,before})=>({file,sha256:before===null?null:sha256(before)}))}));
136
+ const preview={...report,preview_sha256:digest};
137
+ previewPlans.set(preview,{candidate,snapshots,lang,userFile,root});
138
+ return preview;
139
+ }
140
+ function applyRuntimePreview(preview){
141
+ const plan=previewPlans.get(preview);if(!plan)throw new ConfigError('unknown runtime preview; generate a fresh preview');
142
+ const {candidate,snapshots,lang,userFile,root}=plan;
143
+ if(userRuntimesPath()!==userFile||root&&projectDirectory(root)!==root)throw new ConfigError(t('drift',lang,{file:candidate.file}));
144
+ assertSnapshots(snapshots,lang);
145
+ atomicRuntimeWrite(candidate.file,candidate.text,{before:candidate.before,privateFile:preview.scope==='user'});
146
+ previewPlans.delete(preview);return candidate.file;
147
+ }
148
+ export function formatRuntimePreview(preview,lang=runtimeLanguage()){
149
+ const fields=preview.changes.map(({field,before,after})=>` ${field}: ${before??t('absent',lang)} -> ${after}`).join('\n');
150
+ const impact=preview.scope==='user'?t(preview.project_overrides_user?'overridden':'userImpact',lang):t('projectImpact',lang);
151
+ return t('preview',lang,{file:preview.target,scope:preview.scope,preset:preview.preset,fields,impact,
152
+ current:preview.current??t('notProject',lang),effective:preview.effective??t('notProject',lang)})
153
+ +t('modelWarning',lang)+`preview_sha256: ${preview.preview_sha256}\n`;
154
+ }
155
+ export function advancedRuntimeHelp(lang=runtimeLanguage()){
156
+ return t('advanced',lang,{doc:path.join(scripts,'../runtime/workflow-config.md'),validator:path.join(scripts,'cm-workflow-config.mjs')})
157
+ +`External provider model setup: node ${path.join(scripts,'cm-model-setup.mjs')} configure --provider codex|claude\n`
158
+ +`Single-task opt-in and recovery limits: ${path.join(scripts,'../docs/external-models.md')}\n`;
159
+ }
78
160
  function logSet(preset,source,project){
79
161
  // Reuse cm-log-event.mjs through its required Python platform lock adapter.
80
162
  // No specs/run pointer: this decision is independent of any in-flight run.
@@ -90,30 +172,33 @@ function logSet(preset,source,project){
90
172
  }
91
173
  throw new ConfigError('preference saved, decision log failed: Python 3.9+ lock adapter unavailable');
92
174
  }
93
- const COMMANDS='cm-runtime show [--project PATH]\ncm-runtime set <preset> [--project PATH]\ncm-runtime set --user <preset>\ncm-runtime unset --user';
175
+ const COMMANDS='cm-runtime show [--project PATH]\ncm-runtime preview <preset> [--project PATH | --user] [--json]\ncm-runtime set <preset> [--project PATH | --user] [--expect-preview SHA256]\ncm-runtime unset --user';
94
176
  export async function interactiveRuntime(project,{input=process.stdin,output=process.stdout,lang=runtimeLanguage()}={}){
95
177
  const root=projectDirectory(project),existing=findConfig(root),file=existing??path.join(root,'.cm-workflow.yml');
96
178
  const questions=runtimeQuestions(input,output,lang),ask=questions.ask;
97
179
  try{
180
+ output.write(showRuntime(root,{lang,probe:()=>[]})+'\n');
181
+ let action;do{action=await ask(t('menu',lang));}while(!['','1','2','3'].includes(action));
182
+ if(action===''||action==='1'){output.write(t('kept',lang));return 0;}
183
+ if(action==='3'){output.write(advancedRuntimeHelp(lang));return 0;}
98
184
  const fallback=existing?'1':'2';let scope;
99
185
  do{scope=await ask(t('scope',lang,{project:file,user:userRuntimesPath(),default:fallback}));scope=scope||fallback;}while(!['1','2'].includes(scope));
100
186
  const user=scope==='2';
101
187
  if(!user&&!existing)output.write(t('create',lang,{file}));
102
188
  const preset=await askRuntimePreset(ask,lang);
103
- const target=user?userRuntimesPath():file;
104
- const current=user?(stat(target)?readConfigText(target):t('absent',lang)):showRuntime(root,{lang,probe:()=>[]});
105
- output.write(t('preview',lang,{file:target,preset,current}));
189
+ const preview=prepareRuntimePreview(root,preset,{user,lang});
190
+ output.write(formatRuntimePreview(preview,lang));
106
191
  let confirm;
107
192
  do{confirm=(await ask(t('confirm',lang))).toLowerCase();}while(!['','y','n'].includes(confirm));
108
- if(confirm==='n')throw new PromptCancelled();
109
- saveRuntime(root,preset,user,lang,output);
193
+ if(confirm!=='y')throw new PromptCancelled();
194
+ saveRuntime(root,preset,user,lang,output,preview);
110
195
  output.write(showRuntime(root,{lang})+'\n');return 0;
111
196
  }catch(error){if(error instanceof PromptCancelled){output.write(t('cancelled',lang));return 0;}throw error;}
112
197
  finally{questions.close();}
113
198
  }
114
- function saveRuntime(project,preset,user,lang,output){
199
+ function saveRuntime(project,preset,user,lang,output,preview){
115
200
  runtimePreset(preset);project=projectDirectory(project);
116
- const file=user?writeUserRuntime(preset,{lang}):setProjectRuntime(project,preset);
201
+ const file=preview?applyRuntimePreview(preview):user?writeUserRuntime(preset,{lang}):setProjectRuntime(project,preset);
117
202
  logSet(preset,user?'user':'project',project);
118
203
  output.write(t('saved',lang,{file,preset,source:user?'user':'project'})+'\n');
119
204
  }
@@ -121,18 +206,26 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
121
206
  const USAGE=t('help',lang)+'\n'+COMMANDS;
122
207
  try{
123
208
  if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(USAGE+'\n');return 0;}
124
- const command=argv[0]?.startsWith('--')?undefined:argv[0];const args=command?argv.slice(1):argv;let project=process.cwd(),user=false,preset=null,projectSeen=false;
209
+ const command=argv[0]?.startsWith('--')?undefined:argv[0];const args=command?argv.slice(1):argv;let project=process.cwd(),user=false,preset=null,projectSeen=false,expected=null,json=false;
125
210
  for(let i=0;i<args.length;i++){
126
211
  if(args[i]==='--user'&&!user){user=true;continue;}
127
212
  if(args[i]==='--project'&&!projectSeen&&args[i+1]&&!args[i+1].startsWith('--')){project=args[++i];projectSeen=true;continue;}
128
- if(command==='set'&&!preset&&!args[i].startsWith('--')){preset=args[i];continue;}
213
+ if(['set','preview'].includes(command)&&!preset&&!args[i].startsWith('--')){preset=args[i];continue;}
214
+ if(command==='set'&&args[i]==='--expect-preview'&&expected===null&&/^[a-f0-9]{64}$/.test(args[i+1]??'')){expected=args[++i];continue;}
215
+ if(command==='preview'&&args[i]==='--json'&&!json){json=true;continue;}
129
216
  throw new ConfigError(USAGE);
130
217
  }
131
218
  if(user&&projectSeen)throw new ConfigError('--user cannot be combined with --project');
132
219
  if(!command&&!user){if(!input.isTTY||!output.isTTY){output.write(USAGE+'\n');return 2;}return await interactiveRuntime(project,{input,output,lang});}
133
220
  if(command==='show'&&!user){output.write(showRuntime(project,{lang})+'\n');return 0;}
221
+ if(command==='preview'&&preset){
222
+ const preview=prepareRuntimePreview(project,preset,{user,lang});
223
+ output.write(json?JSON.stringify(preview)+'\n':formatRuntimePreview(preview,lang));return 0;
224
+ }
134
225
  if(command==='set'&&preset){
135
- saveRuntime(project,preset,user,lang,output);return 0;
226
+ const preview=expected===null?null:prepareRuntimePreview(project,preset,{user,lang});
227
+ if(preview&&preview.preview_sha256!==expected)throw new ConfigError(t('drift',lang,{file:preview.target}));
228
+ saveRuntime(project,preset,user,lang,output,preview);return 0;
136
229
  }
137
230
  if(command==='unset'&&user){const file=userRuntimesPath();safeTarget(file);if(stat(file))fs.unlinkSync(file);output.write(t('removed',lang,{file})+'\n');return 0;}
138
231
  throw new ConfigError(USAGE);
@@ -5,8 +5,8 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
- import {loadConfig,runtimePreset,runtimesSource,resolveRole,MAX_CONFIG_BYTES} from './cm-workflow-config.mjs';
9
- import {setProjectRuntime,writeUserRuntime,showRuntime} from './cm-runtime.mjs';
8
+ import {loadConfig,runtimePreset,runtimesSource,resolveRole,MAX_CONFIG_BYTES,previewUserRuntimeConfig} from './cm-workflow-config.mjs';
9
+ import {setProjectRuntime,writeUserRuntime,showRuntime,prepareRuntimePreview} from './cm-runtime.mjs';
10
10
  import {editRuntimeDeclaration} from './cm-runtime-edit.mjs';
11
11
  import {json as strictJson} from '../runtime/js/cm-ai/effect-contract.mjs';
12
12
 
@@ -15,7 +15,7 @@ function fixture(fn){
15
15
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-runtime-')));
16
16
  const old=process.env.CM_WORKFLOW_HOME;
17
17
  process.env.CM_WORKFLOW_HOME=path.join(root,'user');
18
- const env={...process.env,HOME:root,CM_WORKFLOW_LOG_HOME:path.join(root,'logs')};
18
+ const env={...process.env,HOME:root,CM_WORKFLOW_LOG_HOME:path.join(root,'logs'),CM_WORKFLOW_LANG:'en'};
19
19
  const run=(...args)=>spawnSync(process.execPath,[path.join(scripts,'cm-runtime.mjs'),...args],{cwd:root,env,encoding:'utf8'});
20
20
  try{return fn(root,run,env);}finally{if(old===undefined)delete process.env.CM_WORKFLOW_HOME;else process.env.CM_WORKFLOW_HOME=old;fs.rmSync(root,{recursive:true,force:true});}
21
21
  }
@@ -140,6 +140,29 @@ async function wizard(root,answers,lang='en'){
140
140
  io.input.end(answers);const code=await running;return {code,text:io.text()};
141
141
  }
142
142
  test('wizard and installer share the same preset question function',()=>assert.equal(wizardPreset,installerPreset));
143
+ test('entry keeps missing and existing configuration by default, without logs or run writes',()=>wizardFixture(async root=>{
144
+ const empty=await wizard(root,'\n');assert.equal(empty.code,0);assert.match(empty.text,/Keep current configuration/);
145
+ assert.match(empty.text,/runtimes_source: none/);assert.deepEqual(fs.readdirSync(root),[]);
146
+ const file=path.join(root,'.cm-workflow.yml'),run=path.join(root,'.cm-run.json');
147
+ fs.writeFileSync(file,'version: 1\nroles: {coder: {model: custom-alias}}\n');fs.writeFileSync(run,'{"keep":"bound"}\n');
148
+ const before=fs.readFileSync(file),runBefore=fs.readFileSync(run);
149
+ const kept=await wizard(root,'1\n');assert.equal(kept.code,0);assert.match(kept.text,/model=custom-alias/);
150
+ assert.deepEqual(fs.readFileSync(file),before);assert.deepEqual(fs.readFileSync(run),runBefore);
151
+ assert.deepEqual(fs.readdirSync(root).sort(),['.cm-run.json','.cm-workflow.yml']);
152
+ }));
153
+ test('advanced model information is read-only and has no model editing prompt',()=>wizardFixture(async root=>{
154
+ const result=await wizard(root,'3\n');assert.equal(result.code,0);assert.match(result.text,/Advanced model configuration/);
155
+ assert.match(result.text,/cm-workflow-config.mjs/);assert(!result.text.includes('Which AI tools do you have'));
156
+ assert.deepEqual(fs.readdirSync(root),[]);
157
+ }));
158
+ test('Enter at the final confirmation declines the proposed change',()=>wizardFixture(async root=>{
159
+ const result=await wizard(root,'2\n2\n1\n\n');assert.equal(result.code,0);assert.match(result.text,/Confirm\? \[y\/N\]/);
160
+ assert.match(result.text,/Cancelled/);assert.deepEqual(fs.readdirSync(root),[]);
161
+ }));
162
+ test('first-install declaration is optional and Enter skips it',()=>wizardFixture(async root=>{
163
+ const io=tty(),running=promptRuntime([],io.input,io.output);io.input.end('\n');await running;
164
+ assert.match(io.text(),/Configure a user default now|现在配置用户默认/);assert.deepEqual(fs.readdirSync(root),[]);
165
+ }));
143
166
  test('language priority, explicit overrides, locales, Intl and English fallback',()=>{
144
167
  for(const [env,expected] of [
145
168
  [{CM_WORKFLOW_LANG:'en',LC_ALL:'zh_CN.UTF-8'},'en'],
@@ -157,7 +180,7 @@ test('TTY project wizard changes exactly five fields, logs decision and shows re
157
180
  const before='\ufeff# keep\r\nversion: 1\r\nruntimes: {available: codex}\r\nroles:\r\n coder: {adapter: current-ai, source: local, model: default} # keep coder\r\n reviewer: {adapter: current-ai, source: local, model: default}\r\n';
158
181
  const initial=before;
159
182
  fs.writeFileSync(file,initial);
160
- const result=await wizard(root,'1\n3\n1\nY\n');assert.equal(result.code,0,result.text);
183
+ const result=await wizard(root,'2\n1\n3\n1\nY\n');assert.equal(result.code,0,result.text);
161
184
  assert.equal(fs.readFileSync(file,'utf8'),initial.replace('available: codex','available: both').replace('adapter: current-ai','adapter: codex-cli').replace('adapter: current-ai','adapter: claude-cli').replaceAll('source: local','source: subscription'));
162
185
  assert.match(result.text,/Which AI tools do you have/);assert.match(result.text,/Who writes code/);
163
186
  assert.match(result.text,/preset: codex-codes/);assert.match(result.text,/runtimes_source: project/);
@@ -166,21 +189,24 @@ test('TTY project wizard changes exactly five fields, logs decision and shows re
166
189
  assert.equal(event.event,'decision');assert.equal(event.preset,'codex-codes');
167
190
  }));
168
191
  test('missing project defaults to user scope and Chinese preset/comment/output',()=>wizardFixture(async root=>{
169
- const result=await wizard(root,'\n2\nY\n','zh');assert.equal(result.code,0);
192
+ const result=await wizard(root,'2\n\n2\nY\n','zh');assert.equal(result.code,0);
170
193
  assert(!fs.existsSync(path.join(root,'.cm-workflow.yml')));
171
194
  assert.match(fs.readFileSync(path.join(root,'user','runtimes.yml'),'utf8'),/# 用 cm-runtime.*\npreset: claude-only/s);
172
195
  assert.match(result.text,/你手上有哪个 AI 工具/);assert.match(result.text,/确认?/);assert.match(result.text,/runtimes_source: user/);
173
196
  }));
174
197
  test('three empty mandatory answers, refusal, EOF and SIGINT do not write',()=>wizardFixture(async root=>{
175
- for(const answers of ['2\n\n\n\n','2\n1\nn\n','2\n']){
176
- const result=await wizard(root,answers);assert.equal(result.code,0);assert.match(result.text,/Cancelled/);assert.deepEqual(fs.readdirSync(root),[]);
198
+ for(const [lang,cancelled] of [['en',/Cancelled/],['zh',/已放弃/]]){
199
+ for(const answers of ['2\n2\n\n\n\n','2\n2\n1\nn\n','2\n2\n','2\n2\n1\n']){
200
+ const result=await wizard(root,answers,lang);assert.equal(result.code,0);
201
+ assert.match(result.text,cancelled);assert.deepEqual(fs.readdirSync(root),[]);
202
+ }
203
+ const io=tty(),running=main(['--project',root],{...io,lang});process.emit('SIGINT');
204
+ assert.equal(await running,0);assert.match(io.text(),cancelled);assert.deepEqual(fs.readdirSync(root),[]);
177
205
  }
178
- const io=tty(),running=main(['--project',root],io);process.emit('SIGINT');
179
- assert.equal(await running,0);assert.match(io.text(),/Cancelled/);assert.deepEqual(fs.readdirSync(root),[]);
180
206
  }));
181
207
  test('explicit project creation, existing-project scope default and invalid choice retry',()=>wizardFixture(async root=>{
182
- const created=await wizard(root,'1\nwrong\n1\ny\n');assert.equal(created.code,0);assert.match(created.text,/Will create project configuration/);
183
- const changed=await wizard(root,'\n3\n2\n\n');assert.equal(changed.code,0);assert.match(changed.text,/preset: claude-codes/);
208
+ const created=await wizard(root,'2\n1\nwrong\n1\ny\n');assert.equal(created.code,0);assert.match(created.text,/Will create project configuration/);
209
+ const changed=await wizard(root,'2\n\n3\n2\ny\n');assert.equal(changed.code,0);assert.match(changed.text,/preset: claude-codes/);
184
210
  assert.equal(loadConfig({projectRoot:root}).roles.coder.adapter,'claude-cli');
185
211
  }));
186
212
  test('non-TTY no command exits 2 with usage and no writes',()=>fixture((root,run)=>{
@@ -209,10 +235,93 @@ test('installer culture reaches shared prompts and comments; explicit override w
209
235
  for(const [culture,override,expected] of [['zh-CN',undefined,'zh'],['en-US',undefined,'en'],['zh-CN','en','en']]){
210
236
  if(override)process.env.CM_WORKFLOW_LANG=override;else delete process.env.CM_WORKFLOW_LANG;
211
237
  const io=tty(),running=promptRuntime(['--lang',culture],io.input,io.output);
212
- io.input.end('3\n2\n');await running;
238
+ io.input.end('y\n3\n2\ny\n');await running;
213
239
  assert.match(io.text(),expected==='zh'?/你手上有哪个 AI 工具/:/Which AI tools do you have/);
214
240
  const file=path.join(root,'user','runtimes.yml');assert.match(fs.readFileSync(file,'utf8'),expected==='zh'?/# 用 cm-runtime/:/# Use cm-runtime/);
215
241
  fs.unlinkSync(file);
216
242
  }
217
243
  }finally{for(const [key,value] of Object.entries(saved)){if(value===undefined)delete process.env[key];else process.env[key]=value;}}
218
244
  }));
245
+
246
+ test('preview is read-only, reports overrides and retains custom model aliases',()=>fixture((root,run)=>{
247
+ const file=path.join(root,'.cm-workflow.yml');
248
+ const original='version: 1\nruntimes: {available: both}\nroles: {coder: {adapter: codex-cli, source: subscription, model: custom-alias}}\n';
249
+ fs.writeFileSync(file,original);
250
+ const preview=run('preview','claude-only','--user','--json');assert.equal(preview.status,0,preview.stderr);
251
+ const report=JSON.parse(preview.stdout);assert.equal(report.project_overrides_user,true);assert.equal(report.scope,'user');
252
+ assert.equal(report.current,report.effective);assert.match(report.effective,/model=custom-alias/);
253
+ assert(!fs.existsSync(path.join(root,'user')));assert.deepEqual(fs.readdirSync(root),['.cm-workflow.yml']);
254
+ const text=run('preview','claude-codes').stdout;
255
+ assert.match(text,/roles.coder.adapter: codex-cli -> claude-cli/);assert.match(text,/model=custom-alias/);
256
+ assert.match(text,/non-default model may be incompatible/);assert.equal(fs.readFileSync(file,'utf8'),original);
257
+ }));
258
+
259
+ test('candidate user preset uses the shared validator and strict config shape',()=>fixture(root=>{
260
+ const file=path.join(root,'.cm-workflow.yml');
261
+ fs.writeFileSync(file,'version: 1\nroles: {coder: {adapter: claude-cli, source: subscription, model: special}}\n');
262
+ const candidate=previewUserRuntimeConfig({projectRoot:root},'claude-codes');
263
+ assert.equal(runtimesSource(candidate),'user');assert.equal(candidate.roles.coder.model,'special');assert.deepEqual(strictJson(candidate),candidate);
264
+ assert.throws(()=>prepareRuntimePreview(root,'codex-only',{user:true}),/roles.coder.adapter/);
265
+ assert.throws(()=>loadConfig({projectRoot:root,userPreset:'claude-codes'}),/invalid config input/);
266
+ assert(!fs.existsSync(path.join(root,'user')));
267
+ }));
268
+
269
+ test('separate CLI preview and set bind the exact target, preset and inherited inputs',()=>fixture((root,run)=>{
270
+ const preview=(preset,...args)=>{
271
+ const result=run('preview',preset,...args,'--json');assert.equal(result.status,0,result.stderr);return JSON.parse(result.stdout).preview_sha256;
272
+ };
273
+ const digest=preview('claude-codes','--user');
274
+ const wrong=run('set','codex-only','--user','--expect-preview',digest);assert.notEqual(wrong.status,0);assert.match(wrong.stderr,/fresh preview/);
275
+ assert.deepEqual(fs.readdirSync(root),[]);
276
+ const saved=run('set','claude-codes','--user','--expect-preview',digest);assert.equal(saved.status,0,saved.stderr);
277
+ assert.equal(loadConfig({projectRoot:root}).roles.coder.adapter,'claude-cli');
278
+ assert.notEqual(run('set','claude-codes','--user','--expect-preview',digest).status,0);
279
+ const projectDigest=preview('codex-codes');
280
+ writeUserRuntime('codex-only');
281
+ const stale=run('set','codex-codes','--expect-preview',projectDigest);assert.notEqual(stale.status,0);assert.match(stale.stderr,/fresh preview/);
282
+ assert(!fs.existsSync(path.join(root,'.cm-workflow.yml')));
283
+ const latest=preview('codex-codes');fs.writeFileSync(path.join(root,'.cm-workflow.json'),'{"version":1}\n');
284
+ assert.notEqual(run('set','codex-codes','--expect-preview',latest).status,0);
285
+ assert.equal(fs.readFileSync(path.join(root,'.cm-workflow.json'),'utf8'),'{"version":1}\n');
286
+ }));
287
+
288
+ test('project preview save refuses target edits and preserves the external writer',()=>fixture((root,run)=>{
289
+ const file=path.join(root,'.cm-workflow.yml');fs.writeFileSync(file,'version: 1\n');
290
+ const result=run('preview','codex-only','--json');assert.equal(result.status,0,result.stderr);
291
+ const digest=JSON.parse(result.stdout).preview_sha256,external='version: 1\n# external edit\n';
292
+ fs.writeFileSync(file,external);
293
+ const stale=run('set','codex-only','--expect-preview',digest);assert.notEqual(stale.status,0);assert.match(stale.stderr,/fresh preview/);
294
+ assert.equal(fs.readFileSync(file,'utf8'),external);assert(!fs.existsSync(path.join(root,'logs')));
295
+ }));
296
+
297
+ test('TTY confirmation cannot overwrite edits made after its preview',()=>wizardFixture(async root=>{
298
+ const file=path.join(root,'.cm-workflow.yml');fs.writeFileSync(file,'version: 1\n');
299
+ const io=tty(),external='version: 1\n# external edit\n';let changed=false;
300
+ io.output.on('data',chunk=>{if(String(chunk).includes('Confirm?')){fs.writeFileSync(file,external);changed=true;io.input.end('y\n');}});
301
+ const running=main(['--project',root],{...io,lang:'en'});io.input.write('2\n1\n1\n');
302
+ assert.equal(await running,1);assert(changed);assert.equal(fs.readFileSync(file,'utf8'),external);
303
+ assert(!fs.existsSync(path.join(root,'logs')));
304
+ }));
305
+
306
+ test('installer keeps existing defaults, defaults No at final confirmation and refuses drift',()=>wizardFixture(async root=>{
307
+ writeUserRuntime('codex-only');const file=path.join(root,'user','runtimes.yml'),before=fs.readFileSync(file);
308
+ for(const answers of ['\n','n\n2\n\n','n\n2\n']){
309
+ const io=tty(),running=promptRuntime([],io.input,io.output);io.input.end(answers);await running;
310
+ assert.deepEqual(fs.readFileSync(file),before);
311
+ }
312
+ const io=tty();let changed=false;
313
+ io.output.on('data',chunk=>{if(String(chunk).includes('[y/N]')){writeUserRuntime('claude-codes');changed=true;io.input.end('y\n');}});
314
+ const running=promptRuntime([],io.input,io.output);io.input.write('n\n2\n');
315
+ await assert.rejects(running,/fresh preview|重新预览/);assert(changed);
316
+ assert.match(fs.readFileSync(file,'utf8'),/preset: claude-codes/);
317
+ }));
318
+
319
+ test('invalid configuration reports its field and never offers implicit repair',()=>wizardFixture(async root=>{
320
+ const file=path.join(root,'.cm-workflow.yml'),invalid='version: 1\nunknown: true\n';fs.writeFileSync(file,invalid);
321
+ const result=await wizard(root,'2\n1\n1\ny\n');assert.equal(result.code,1);assert(!result.text.includes('Keep current configuration'));
322
+ assert.equal(fs.readFileSync(file,'utf8'),invalid);fs.unlinkSync(file);
323
+ fs.mkdirSync(path.join(root,'user'));const user=path.join(root,'user','runtimes.yml');fs.writeFileSync(user,'preset: broken\n');
324
+ const io=tty(),running=promptRuntime([],io.input,io.output);io.input.end('n\n1\ny\n');await running;
325
+ assert.match(io.text(),/Invalid user default|当前用户级默认无效/);assert.match(io.text(),/runtimes.yml/);
326
+ assert.equal(fs.readFileSync(user,'utf8'),'preset: broken\n');assert(!fs.existsSync(path.join(root,'logs')));
327
+ }));
@@ -250,6 +250,38 @@ function finalizeFixture(t,{all=true}={}){
250
250
  return {...f,report,review,run,scanFile,reviewFile};
251
251
  }
252
252
 
253
+ test('private report names completed checks, skipped configuration and concrete follow-up without changing stdout',t=>{
254
+ const f=finalizeFixture(t),scan=structuredClone(f.report);
255
+ scan.tools=[{tool:'gitleaks',status:'NO_FINDINGS',reason:null,version:'9.0.0'},
256
+ {tool:'semgrep',status:'NOT_RUN',reason:'local_rules_required'},
257
+ {tool:'osv',status:'NOT_RUN',reason:'offline_database_required'}];
258
+ const r=f.run(f.review,scan,{cli:true}),summary=r.output.checkSummary;
259
+ assert.deepEqual(summary.attempted.map(row=>row.tool),['gitleaks']);
260
+ assert.deepEqual(summary.notRun.map(row=>row.tool),['semgrep','osv']);
261
+ assert.match(summary.notRun[0].description,/未指定.*本地规则/);
262
+ assert.match(summary.notRun[1].description,/未提供.*离线数据库/);
263
+ assert.ok(summary.nextSteps.some(row=>row.tool==='semgrep'&&row.action.includes('--semgrep-rules')));
264
+ assert.ok(summary.nextSteps.some(row=>row.tool==='osv'&&row.action.includes('--osv-db')));
265
+ assert.deepEqual(r.output.tools,scan.tools);
266
+ assert.deepEqual(Object.keys(r.value).sort(),['result','coverage','reportPath','gaps','findingsCount','sourceUnchanged'].sort());
267
+ assert.equal(r.value.coverage,'PARTIAL');assert.equal(r.code,3);
268
+ });
269
+
270
+ test('report distinguishes failed attempts, missing tools and unverified offline data freshness',t=>{
271
+ const f=finalizeFixture(t),scan=structuredClone(f.report);
272
+ scan.tools=[{tool:'gitleaks',status:'ERROR',reason:'timeout',version:'unknown'},
273
+ {tool:'semgrep',status:'NOT_RUN',reason:'tool_missing'},
274
+ {tool:'osv',status:'NO_FINDINGS',reason:'offline_database_freshness_and_ecosystem_coverage_unverified',version:'9.0.0'}];
275
+ const r=f.run(f.review,scan),summary=r.output.checkSummary;
276
+ assert.equal(summary.attempted[0].execution,'已尝试,未完成');
277
+ assert.match(summary.attempted[0].description,/超时/);
278
+ assert.equal(summary.notRun[0].execution,'未运行');assert.match(summary.notRun[0].description,/工具不可用/);
279
+ assert.equal(summary.attempted[1].execution,'已完成');
280
+ assert.match(summary.attempted[1].description,/数据库.*新旧.*未知/);
281
+ assert.ok(summary.nextSteps.some(row=>row.tool==='osv'&&/新旧.*生态覆盖/.test(row.action)));
282
+ assert.deepEqual(r.output.tools,scan.tools);assert.equal(r.value.coverage,'PARTIAL');
283
+ });
284
+
253
285
  test('finalize coverage requires every selected path and rejects unknown or malformed review input',t=>{
254
286
  const f=finalizeFixture(t);
255
287
  assert.equal(f.run().value.coverage,'FULL');
@@ -0,0 +1,117 @@
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 {createHash} from 'node:crypto';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {spawnSync} from 'node:child_process';
9
+ import {checkN4,checkN5,implementationSha256,prepareHumanCorrection,publishHumanCorrectionReview,
10
+ prepareMarkDone,verifyMarkDonePlan} from './cm-task-gate.mjs';
11
+
12
+ const sha=file=>createHash('sha256').update(fs.readFileSync(file)).digest('hex');
13
+ function fixture(t){
14
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-human-correction-')));
15
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
16
+ const reviewsDir=path.join(root,'.reviews');fs.mkdirSync(reviewsDir);
17
+ fs.mkdirSync(path.join(root,'src'));const code=path.join(root,'src/example.ts');fs.writeFileSync(code,'old');
18
+ const tasks=path.join(root,'tasks.md');fs.writeFileSync(tasks,'- [ ] T-001: fixture\n');
19
+ const payload=attempt=>({schema_version:1,task_id:'T-001',attempt,status:'ready_for_review',changed_files:['src/example.ts'],
20
+ implementation_sha256:implementationSha256(root,['src/example.ts']),
21
+ verification:[{command:'fixture',status:'passed',evidence:'synthetic fixture'}],
22
+ evidence:['learning: no_relevant_lesson','learning: retrospective no_new_lesson'],blockers:[],scope_deviation:[]});
23
+ const review=(file,handoff,attempt,verdict,correctionDigest=null)=>fs.writeFileSync(file,`---\nat: 2026-09-30T12:00:00Z\nreviewer: codex-subagent\nindependent: true\ntask: T-001\nattempt: ${attempt}\nround: ${attempt}\nverdict: ${verdict}\nblocking_findings: ${verdict==='approved'?0:1}\nhandoff: ${path.basename(handoff)}\nhandoff_sha256: ${sha(handoff)}\n${correctionDigest?`correction_sha256: ${correctionDigest}\n`:''}scope:\n - src/example.ts\n---\n${verdict==='approved'?'Zero findings.':'Blocking fixture finding.'}\n`);
24
+ const history=[];
25
+ for(const [attempt,verdict] of [[1,'changes_requested'],[2,'blocked']]){
26
+ const handoff=path.join(reviewsDir,`login-T-001-a${attempt}-handoff.json`),file=path.join(reviewsDir,`login-T-001-r${attempt}.md`);
27
+ fs.writeFileSync(handoff,JSON.stringify(payload(attempt)));review(file,handoff,attempt,verdict);history.push(handoff,file);
28
+ }
29
+ const original=history.map(sha);fs.writeFileSync(code,'fixed');
30
+ const draft=path.join(root,'draft.json');fs.writeFileSync(draft,JSON.stringify(payload(2)));
31
+ const selectors={handoff:draft,reviewsDir,feature:'login',task:'T-001',projectRoot:root,
32
+ humanAuthorized:true,reason:'Human approved exact selector correction after original blocked round 2.'};
33
+ const prepare=()=>prepareHumanCorrection(selectors);
34
+ const finish=(record,verdict='approved')=>{
35
+ const selected={...selectors,...record,tasksPath:tasks};
36
+ review(record.review,record.handoff,2,verdict,record.correction_sha256);
37
+ publishHumanCorrectionReview(selected);return selected;
38
+ };
39
+ return {root,reviewsDir,code,tasks,draft,history,original,selectors,review,prepare,finish};
40
+ }
41
+
42
+ test('one-shot human correction retains blocked history and completes through the existing locked adapter',t=>{
43
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
44
+ assert.equal(checkN4(selected).outcome,'ready_for_review');
45
+ assert.throws(()=>checkN5(selected));
46
+ const done=f.finish(record);assert.equal(checkN5(done).outcome,'approved');
47
+ assert.throws(()=>checkN4(done),/already exists/);assert.throws(()=>f.prepare(),/already exists/);
48
+ const plan=prepareMarkDone(done);assert.equal(plan.evidence.length,8);
49
+ const args=['mark-done','--handoff',done.handoff,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001',
50
+ '--project-root',f.root,'--tasks',f.tasks,'--correction',done.correction];
51
+ const result=spawnSync(process.env.CM_PYTHON_BIN||'python3',[fileURLToPath(new URL('./cm-task-gate.py',import.meta.url)),...args],{encoding:'utf8'});
52
+ assert.equal(result.status,0,result.stderr);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[x\]/);
53
+ assert.deepEqual(f.history.map(sha),f.original);
54
+ assert.throws(()=>checkN5({...done,handoff:f.history[2],correction:null}),/implementation content changed/);
55
+ });
56
+
57
+ test('correction authorization, original verdict, full scope, and mandatory Learning cannot be omitted',t=>{
58
+ const f=fixture(t);
59
+ assert.throws(()=>prepareHumanCorrection({...f.selectors,humanAuthorized:false}),/authorization/);
60
+ assert.throws(()=>prepareHumanCorrection({...f.selectors,reason:''}),/reason/);
61
+ const draft=JSON.parse(fs.readFileSync(f.draft));draft.evidence=['unbound application'];fs.writeFileSync(f.draft,JSON.stringify(draft));
62
+ assert.throws(()=>prepareHumanCorrection({...f.selectors,allowLegacyUnbound:true}),/Learning/);
63
+ assert.equal(fs.readdirSync(f.reviewsDir).length,4);
64
+ draft.evidence=['learning: no_relevant_lesson','learning: retrospective no_new_lesson'];draft.changed_files=['src/new.ts'];
65
+ fs.writeFileSync(path.join(f.root,'src/new.ts'),'new');draft.implementation_sha256=implementationSha256(f.root,draft.changed_files);
66
+ fs.writeFileSync(f.draft,JSON.stringify(draft));assert.throws(()=>f.prepare(),/full original/);
67
+ f.review(f.history[3],f.history[2],2,'approved');assert.throws(()=>f.prepare(),/blocked round 2/);
68
+ });
69
+
70
+ test('original evidence, correction handoff, implementation and authorization record drift invalidate approval',t=>{
71
+ const f=fixture(t),record=f.prepare(),done=f.finish(record),plan=prepareMarkDone(done);
72
+ for(const file of [...f.history,record.correction,record.handoff,record.review,done.receipt??path.join(f.reviewsDir,'login-T-001-human-correction-receipt.json'),f.code]){
73
+ const bytes=fs.readFileSync(file);fs.appendFileSync(file,'\nchanged');
74
+ assert.throws(()=>checkN5(done),undefined,file);assert.throws(()=>verifyMarkDonePlan(done,plan.planDigest),undefined,file);
75
+ fs.writeFileSync(file,bytes);
76
+ }
77
+ assert.equal(checkN5(done).outcome,'approved');assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
78
+ });
79
+
80
+ test('blocked correction review is sealed once and cannot be replaced by a new approval',t=>{
81
+ const f=fixture(t),record=f.prepare(),done=f.finish(record,'blocked');
82
+ assert.throws(()=>checkN5(done),/remains blocked/);
83
+ assert.throws(()=>publishHumanCorrectionReview(done),/already exists/);
84
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
85
+ assert.throws(()=>checkN5(done),/review or receipt changed/);
86
+ assert.throws(()=>publishHumanCorrectionReview(done),/already exists/);
87
+ assert.throws(()=>f.prepare(),/already exists/);
88
+ });
89
+
90
+ test('old review or self-degraded review cannot authorize a correction',t=>{
91
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
92
+ f.review(record.review,record.handoff,2,'approved');
93
+ assert.throws(()=>publishHumanCorrectionReview(selected),/fresh independent/);
94
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
95
+ fs.writeFileSync(record.review,fs.readFileSync(record.review,'utf8').replace('codex-subagent','self-degraded').replace('independent: true','independent: false').replace('scope:','degraded_reason: fixture\nscope:'));
96
+ assert.throws(()=>publishHumanCorrectionReview(selected),/fresh independent/);
97
+ });
98
+
99
+ test('correction file identities reject symlinks, hardlinks, sibling selection and duplicate record fields',t=>{
100
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
101
+ assert.throws(()=>checkN4({...selected,correction:path.join(f.root,'other.json')}),/fixed evidence/);
102
+ const bytes=fs.readFileSync(record.correction);
103
+ fs.writeFileSync(record.correction,bytes.toString().replace('"version": 1','"version": 1, "version": 1'));
104
+ assert.throws(()=>checkN4(selected),/duplicate key/);fs.writeFileSync(record.correction,bytes);
105
+ const link=path.join(f.root,'alias');fs.linkSync(record.correction,link);
106
+ assert.throws(()=>checkN4(selected),/hardlinked/);fs.unlinkSync(link);
107
+ fs.renameSync(record.correction,link);fs.symlinkSync(link,record.correction);
108
+ assert.throws(()=>checkN4(selected),/non-symlink/);
109
+ });
110
+
111
+ test('CLI human correction refuses missing human authorization and exposes the fixed review record',t=>{
112
+ const f=fixture(t),script=fileURLToPath(new URL('./cm-task-gate.mjs',import.meta.url));
113
+ const args=['prepare-human-correction','--handoff',f.draft,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,'--reason','Explicit human correction'];
114
+ const denied=spawnSync(process.execPath,[script,...args],{encoding:'utf8'});assert.equal(denied.status,1);assert.match(denied.stderr,/authorization/);
115
+ const result=spawnSync(process.execPath,[script,...args,'--human-authorized'],{encoding:'utf8'});
116
+ assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).attempt,2);
117
+ });