@aibyzero/cm-workflow 0.16.5 → 0.16.7

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 (202) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +14 -0
  3. package/CHANGELOG.md +19 -1
  4. package/README.md +17 -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 +96 -6
  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-admission.mjs +34 -10
  27. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  28. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -34
  29. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +93 -31
  30. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
  31. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  32. package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
  33. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  34. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  35. package/runtime/js/cm-ai/drive-bootstrap.mjs +22 -12
  36. package/runtime/js/cm-ai/drive-core.mjs +9 -3
  37. package/runtime/js/cm-ai/durable-runner-state.mjs +146 -14
  38. package/runtime/js/cm-ai/effect-contract.mjs +1 -1
  39. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  40. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  41. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  42. package/runtime/js/cm-ai/external-models.mjs +52 -0
  43. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  44. package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
  45. package/runtime/js/cm-ai/host-check.mjs +30 -4
  46. package/runtime/js/cm-ai/host-conversation-execution.mjs +59 -17
  47. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  48. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  49. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  50. package/runtime/js/cm-ai/host-qa-executor.mjs +54 -8
  51. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
  52. package/runtime/js/cm-ai/host-session.mjs +1 -1
  53. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
  54. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  55. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  56. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  57. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  58. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  59. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  60. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  61. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  62. package/runtime/js/cm-ai/operator-guidance.mjs +89 -0
  63. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  64. package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
  65. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  66. package/runtime/js/cm-ai/review-package.mjs +11 -0
  67. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  68. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  69. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  70. package/runtime/js/cm-ai/task-runner.mjs +176 -25
  71. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  72. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  73. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  74. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  75. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  76. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  77. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  78. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  79. package/runtime/js/cm-fix/execution.mjs +183 -40
  80. package/runtime/js/cm-fix/final-review.mjs +18 -10
  81. package/runtime/js/cm-fix/finish.mjs +2 -19
  82. package/runtime/js/cm-fix/host-review.mjs +25 -6
  83. package/runtime/js/cm-fix/host.mjs +4 -1
  84. package/runtime/js/cm-fix/layout.mjs +1 -1
  85. package/runtime/js/cm-fix/log-events.mjs +29 -0
  86. package/runtime/js/cm-fix/metrics.mjs +3 -2
  87. package/runtime/js/cm-fix/progress.mjs +4 -0
  88. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  89. package/runtime/js/cm-prd/analysis.mjs +5 -2
  90. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  91. package/runtime/js/cm-prd/review-host.mjs +2 -1
  92. package/runtime/js/cm-prd/review-publication.mjs +23 -13
  93. package/runtime/js/cm-prd/review-time.mjs +29 -0
  94. package/runtime/js/cm-prd/session.mjs +53 -6
  95. package/runtime/js/cm-security/finalize.mjs +32 -0
  96. package/runtime/js/cm-test/recovery.mjs +4 -4
  97. package/runtime/review.md +5 -0
  98. package/runtime/task-gates.md +6 -0
  99. package/runtime/workflow-config.md +10 -1
  100. package/scripts/cm-ai-admission.mjs +14 -3
  101. package/scripts/cm-ai-batch-drive.mjs +52 -23
  102. package/scripts/cm-ai-batch-drive.test.mjs +47 -2
  103. package/scripts/cm-ai-batch-host.mjs +44 -16
  104. package/scripts/cm-ai-batch-run.mjs +77 -29
  105. package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
  106. package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
  107. package/scripts/cm-ai-bootstrap.test.mjs +80 -87
  108. package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
  109. package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
  110. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
  111. package/scripts/cm-ai-drive.mjs +73 -28
  112. package/scripts/cm-ai-drive.test.mjs +119 -1
  113. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  114. package/scripts/cm-ai-host.mjs +79 -27
  115. package/scripts/cm-ai-host.test.mjs +88 -0
  116. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  117. package/scripts/cm-ai-progress.test.mjs +521 -0
  118. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  119. package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
  120. package/scripts/cm-ai-review-failure.test.mjs +71 -11
  121. package/scripts/cm-ai-run.mjs +94 -19
  122. package/scripts/cm-ai-run.test.mjs +2 -1
  123. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  124. package/scripts/cm-check-drive.test.mjs +1 -0
  125. package/scripts/cm-check-runtime.sh +11 -0
  126. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  127. package/scripts/cm-claude-probe.test.mjs +1 -1
  128. package/scripts/cm-codex-plugin-metadata.py +83 -0
  129. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  130. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  131. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  132. package/scripts/cm-efficiency-offline.mjs +35 -0
  133. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  134. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  135. package/scripts/cm-efficiency-response.test.mjs +117 -0
  136. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  137. package/scripts/cm-external-batch-host.test.mjs +157 -0
  138. package/scripts/cm-external-fix-host.test.mjs +281 -0
  139. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  140. package/scripts/cm-external-group-models.test.mjs +60 -0
  141. package/scripts/cm-external-model-host.test.mjs +180 -0
  142. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  143. package/scripts/cm-external-models.test.mjs +89 -0
  144. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  145. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  146. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  147. package/scripts/cm-fix-drive.mjs +28 -13
  148. package/scripts/cm-fix-final-review.test.mjs +11 -6
  149. package/scripts/cm-fix-host.mjs +17 -10
  150. package/scripts/cm-fix-large-log.test.mjs +113 -0
  151. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  152. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  153. package/scripts/cm-fix-review-budget.test.mjs +7 -1
  154. package/scripts/cm-host-qa-executor.test.mjs +329 -3
  155. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  156. package/scripts/cm-live-evidence.test.mjs +64 -0
  157. package/scripts/cm-log-event.mjs +34 -7
  158. package/scripts/cm-log-event.py +15 -0
  159. package/scripts/cm-model-setup.mjs +79 -0
  160. package/scripts/cm-prd-drive.mjs +32 -11
  161. package/scripts/cm-prd-drive.test.mjs +15 -0
  162. package/scripts/cm-prd-host.mjs +26 -6
  163. package/scripts/cm-prd-host.test.mjs +4 -0
  164. package/scripts/cm-prd-review-host.test.mjs +17 -0
  165. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  166. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  167. package/scripts/cm-release-smoke.sh +5 -1
  168. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  169. package/scripts/cm-runtime-i18n.mjs +15 -4
  170. package/scripts/cm-runtime-install.mjs +8 -4
  171. package/scripts/cm-runtime.mjs +116 -23
  172. package/scripts/cm-runtime.test.mjs +121 -12
  173. package/scripts/cm-security.test.mjs +32 -0
  174. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  175. package/scripts/cm-task-gate.mjs +146 -10
  176. package/scripts/cm-task-gate.py +1 -0
  177. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  178. package/scripts/cm-test-drive.mjs +10 -4
  179. package/scripts/cm-test-drive.test.mjs +14 -1
  180. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  181. package/scripts/cm-usage-report.py +22 -3
  182. package/scripts/cm-workflow-config.mjs +10 -1
  183. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  184. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  185. package/scripts/fixtures/process-cleanup.mjs +3 -1
  186. package/scripts/test-cm-native-usage.py +62 -0
  187. package/scripts/test-external-model-setup.py +91 -0
  188. package/scripts/test-model-configuration-write.py +201 -0
  189. package/scripts/test-npm-install.py +10 -1
  190. package/skills/cm-ai/SKILL.md +2 -2
  191. package/skills/cm-ai/references/N1-init.md +1 -1
  192. package/skills/cm-ai/references/N8-finish.md +5 -0
  193. package/skills/cm-ai/references/js-host.md +16 -7
  194. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  195. package/skills/cm-fix/SKILL.md +1 -1
  196. package/skills/cm-fix/references/js-host.md +30 -2
  197. package/skills/cm-prd/SKILL.md +5 -4
  198. package/skills/cm-prd/references/spec-self-check.md +3 -1
  199. package/skills/cm-runtime/SKILL.md +29 -6
  200. package/skills/cm-security/SKILL.md +4 -2
  201. package/skills/cm-security/references/scan-contract.md +1 -0
  202. package/templates/cm-workflow.yml +1 -1
@@ -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
+ });
@@ -472,7 +472,135 @@ function verifyLearningRecord(payload,projectRoot){
472
472
  throw new GateError('Learning requires a content-bound handoff');
473
473
  }
474
474
 
475
- export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false}){
475
+ // A single explicitly authorized human continuation after a blocked second
476
+ // round. The ordinary two-attempt chain and original evidence stay intact.
477
+ function correctionPaths(reviewsDir,feature,task){
478
+ requireFeature(feature);requireTaskId(task,'task');
479
+ const info=fs.lstatSync(reviewsDir);
480
+ if(!info.isDirectory()||info.isSymbolicLink())throw new GateError('correction reviews directory must be real');
481
+ const root=fs.realpathSync(reviewsDir),prefix=path.join(root,`${feature}-${task}-human-correction`);
482
+ return {record:prefix+'.json',handoff:prefix+'-handoff.json',review:prefix+'.md',receipt:prefix+'-receipt.json'};
483
+ }
484
+ function absent(file){
485
+ try{fs.lstatSync(file);throw new GateError(`human correction evidence already exists: ${file}`);}
486
+ catch(error){if(error.code!=='ENOENT')throw error;}
487
+ }
488
+ function exactFields(value,fields,label){
489
+ if(value===null||typeof value!=='object'||Array.isArray(value)
490
+ ||!sameSet(new Set(Object.keys(value)),new Set(fields)))throw new GateError(`invalid ${label} fields`);
491
+ }
492
+ function correctionHistory({reviewsDir,feature,task,projectRoot}){
493
+ const handoff=expectedHandoff(reviewsDir,feature,task,2);
494
+ requireExpectedHandoff(handoff,{reviewsDir,feature,task,attempt:2});
495
+ const payload=loadHandoff(handoff,{task,attempt:2});
496
+ if(payload.status!=='ready_for_review'||!payload.implementation_sha256)
497
+ throw new GateError('human correction requires a bound ready attempt 2 handoff');
498
+ validateAttemptChain(reviewsDir,feature,task,2,payload,projectRoot);
499
+ const review=reviewPath(reviewsDir,feature,task,2);
500
+ const header=validateReview(review,{task,attempt:2,handoff,changedFiles:payload.changed_files});
501
+ if(header.verdict!=='blocked'||header.independent!=='true')
502
+ throw new GateError('human correction requires an independent blocked round 2');
503
+ const files=[expectedHandoff(reviewsDir,feature,task,1),reviewPath(reviewsDir,feature,task,1),handoff,review];
504
+ const revisions=files.map(file=>fileRevision(file,PREPARATION_FILE_LIMIT));
505
+ requireRevisions(revisions);
506
+ return {payload,revisions,history:revisions.map(item=>({file:path.basename(item.path),
507
+ sha256:createHash('sha256').update(item.bytes).digest('hex')}))};
508
+ }
509
+ function boundCorrectionHandoff(handoff,task,projectRoot){
510
+ const payload=loadHandoff(handoff,{task,attempt:2});
511
+ if(payload.status!=='ready_for_review')throw new GateError('human correction requires ready_for_review');
512
+ verifyLearningRecord(payload,projectRoot);verifyImplementationBinding(payload,{projectRoot});
513
+ return payload;
514
+ }
515
+ export function prepareHumanCorrection(selectors){
516
+ const {reviewsDir,feature,task,handoff,projectRoot,humanAuthorized,reason}=selectors;
517
+ if(humanAuthorized!==true)throw new GateError('human correction requires explicit human authorization');
518
+ if(typeof reason!=='string'||!reason.trim()||reason.length>2000)
519
+ throw new GateError('human correction requires a concrete bounded reason');
520
+ const paths=correctionPaths(reviewsDir,feature,task);
521
+ absent(paths.record);absent(paths.review);absent(paths.receipt);
522
+ const original=correctionHistory(selectors),draft=fileRevision(handoff,PREPARATION_FILE_LIMIT);
523
+ const payload=boundCorrectionHandoff(handoff,task,projectRoot);
524
+ if(!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
525
+ throw new GateError('human correction must retain the full original reviewed file scope');
526
+ requireRevisions([...original.revisions,draft]);
527
+ // Permit only an identical orphan handoff after interruption before record
528
+ // creation. Published authorization/review/receipt are never overwritten.
529
+ try{absent(paths.handoff);fs.writeFileSync(paths.handoff,draft.bytes,{flag:'wx',mode:0o600});}
530
+ catch(error){
531
+ if(error instanceof GateError&&!fs.existsSync(paths.record)&&fileRevision(paths.handoff,PREPARATION_FILE_LIMIT).bytes.equals(draft.bytes)){}
532
+ else throw error;
533
+ }
534
+ const record={version:1,protocol:'cm-human-correction',feature,task,attempt:2,
535
+ authorization:'explicit-human-confirmation',at:new Date().toISOString(),reason:reason.trim(),
536
+ history:original.history,handoff_sha256:sha256(paths.handoff)};
537
+ requireRevisions(original.revisions);
538
+ boundCorrectionHandoff(paths.handoff,task,projectRoot);
539
+ fs.writeFileSync(paths.record,JSON.stringify(record,null,2)+'\n',{flag:'wx',mode:0o600});
540
+ return {outcome:'ready_for_correction_review',correction:paths.record,handoff:paths.handoff,
541
+ review:paths.review,correction_sha256:sha256(paths.record),attempt:2};
542
+ }
543
+ function inspectHumanCorrection(selectors){
544
+ const {reviewsDir,feature,task,correction,handoff,projectRoot}=selectors;
545
+ const paths=correctionPaths(reviewsDir,feature,task);
546
+ if(typeof correction!=='string'||typeof handoff!=='string'||path.resolve(correction)!==paths.record||path.resolve(handoff)!==paths.handoff)
547
+ throw new GateError('human correction must use its fixed evidence paths');
548
+ const pinned=fileRevision(paths.record,PREPARATION_FILE_LIMIT);
549
+ const record=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(pinned.bytes));
550
+ exactFields(record,['version','protocol','feature','task','attempt','authorization','at','reason','history','handoff_sha256'],'human correction');
551
+ if(record.version!==1n||record.protocol!=='cm-human-correction'||record.feature!==feature||record.task!==task
552
+ ||record.attempt!==2n||record.authorization!=='explicit-human-confirmation'
553
+ ||typeof record.reason!=='string'||!record.reason.trim()||record.reason.length>2000
554
+ ||typeof record.at!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(record.at)||Number.isNaN(Date.parse(record.at)))
555
+ throw new GateError('invalid human correction authorization record');
556
+ const original=correctionHistory(selectors);
557
+ if(canonical(record.history)!==canonical(original.history))throw new GateError('human correction history changed');
558
+ const payload=boundCorrectionHandoff(paths.handoff,task,projectRoot);
559
+ fileRevision(paths.handoff,PREPARATION_FILE_LIMIT);
560
+ if(record.handoff_sha256!==sha256(paths.handoff)
561
+ ||!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
562
+ throw new GateError('human correction handoff changed or omitted original scope');
563
+ requireRevisions([pinned,...original.revisions]);
564
+ return {paths,payload,correctionDigest:sha256(paths.record)};
565
+ }
566
+ export function publishHumanCorrectionReview(selectors){
567
+ const {paths,payload,correctionDigest}=inspectHumanCorrection(selectors);
568
+ absent(paths.receipt);
569
+ const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
570
+ const header=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
571
+ if(header.independent!=='true'||header.correction_sha256!==correctionDigest)
572
+ throw new GateError('human correction requires fresh independent review bound to the correction record');
573
+ requireRevisions([pinned]);
574
+ inspectHumanCorrection(selectors);
575
+ const receipt={version:1,protocol:'cm-human-correction-review',correction_sha256:correctionDigest,
576
+ review_sha256:createHash('sha256').update(pinned.bytes).digest('hex'),verdict:header.verdict};
577
+ fs.writeFileSync(paths.receipt,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
578
+ return {outcome:header.verdict,receipt:paths.receipt};
579
+ }
580
+ function checkHumanCorrection(selectors,stage){
581
+ const {paths,payload,correctionDigest}=inspectHumanCorrection(selectors);
582
+ if(stage==='n4'){
583
+ absent(paths.receipt);
584
+ return {gate:'n4',task:selectors.task,attempt:2,outcome:'ready_for_review',content_bound:true,
585
+ handoff_sha256:sha256(paths.handoff),correction_sha256:correctionDigest};
586
+ }
587
+ const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
588
+ const result=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
589
+ const receiptRevision=fileRevision(paths.receipt,PREPARATION_FILE_LIMIT);
590
+ const receipt=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(receiptRevision.bytes));
591
+ exactFields(receipt,['version','protocol','correction_sha256','review_sha256','verdict'],'human correction receipt');
592
+ if(receipt.version!==1n||receipt.protocol!=='cm-human-correction-review'
593
+ ||receipt.correction_sha256!==correctionDigest||result.correction_sha256!==correctionDigest
594
+ ||receipt.review_sha256!==sha256(paths.review)||receipt.verdict!==result.verdict)
595
+ throw new GateError('human correction review or receipt changed');
596
+ if(result.verdict!=='approved'||result.independent!=='true')throw new GateError('human correction remains blocked');
597
+ requireRevisions([pinned,receiptRevision]);
598
+ return {gate:'n5',task:selectors.task,attempt:2,outcome:'approved',review:paths.review,
599
+ content_bound:true,correction_sha256:correctionDigest};
600
+ }
601
+
602
+ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null}){
603
+ if(correction!==null)return checkHumanCorrection({handoff,reviewsDir,feature,task,projectRoot,correction},'n4');
476
604
  requireTaskId(task,'task');
477
605
  const payload=loadHandoff(handoff,{task});
478
606
  if(payload.status!=='ready_for_review')throw new GateError('N4 requires a ready_for_review handoff');
@@ -484,7 +612,8 @@ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowL
484
612
  return {gate:'n4',task,attempt,outcome:'ready_for_review',handoff_sha256:sha256(handoff),content_bound:contentBound};
485
613
  }
486
614
 
487
- export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false}){
615
+ export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null}){
616
+ if(correction!==null)return checkHumanCorrection({handoff,reviewsDir,feature,task,projectRoot,correction},'n5');
488
617
  requireTaskId(task,'task');
489
618
  const payload=loadHandoff(handoff,{task});
490
619
  if(payload.status!=='ready_for_review')throw new GateError('N5 requires a ready_for_review handoff');
@@ -554,6 +683,10 @@ function pinApproval(selectors){
554
683
  if(!revisions.some(revision=>revision.path===pinned.path))revisions.push(pinned);
555
684
  }
556
685
  }
686
+ if(selectors.correction){
687
+ const paths=correctionPaths(reviewsDir,feature,task);
688
+ for(const file of [paths.record,paths.review,paths.receipt])revisions.push(fileRevision(file,preparationReadLimit));
689
+ }
557
690
  const approval={...checkN5(selectors)};
558
691
  requireRevisions(revisions);
559
692
  return {approval,revisions};
@@ -659,7 +792,7 @@ export function prepareMarkDone(selectors){
659
792
  if(existing&&!sameRevision(existing,pinned))throw new GateError('conflicting revisions for physical preparation evidence');
660
793
  physical.set(pinned.path,pinned);
661
794
  }
662
- if(physical.size>4)throw new GateError('preparation evidence count exceeds bound');
795
+ if(physical.size>(selectors.correction?8:4))throw new GateError('preparation evidence count exceeds bound');
663
796
  const plan={
664
797
  version:1,protocol:'cm-mark-done-plan',feature:selectors.feature,taskId:selectors.task,
665
798
  attempt:approval.attempt,tasksPath:revision.path,mode:Number(BigInt(revision.stat[2])&0o7777n),
@@ -801,17 +934,18 @@ export function checkParallelWrite({repo,assignment}){
801
934
  return {gate:'parallel-write',outcome:'isolated',assignments:result};
802
935
  }
803
936
 
804
- function usage(){return 'usage: cm-task-gate.mjs {validate-handoff|hash-implementation|check-n4|check-n5|prepare-mark-done|verify-mark-done-plan|check-parallel-write} [options]';}
937
+ function usage(){return 'usage: cm-task-gate.mjs {validate-handoff|hash-implementation|check-n4|check-n5|prepare-mark-done|verify-mark-done-plan|prepare-human-correction|publish-human-correction-review|check-parallel-write} [options]';}
805
938
 
806
939
  function parseCli(argv){
807
940
  if(argv.length===0||argv.includes('--help')||argv.includes('-h'))return {help:true};
808
941
  const command=argv[0];
809
- if(!['validate-handoff','hash-implementation','check-n4','check-n5','prepare-mark-done','verify-mark-done-plan','mark-done-locked','check-parallel-write'].includes(command))
942
+ if(!['validate-handoff','hash-implementation','check-n4','check-n5','prepare-mark-done','verify-mark-done-plan','mark-done-locked','prepare-human-correction','publish-human-correction-review','check-parallel-write'].includes(command))
810
943
  throw new GateError('unsupported command');
811
944
  const allowed=command==='validate-handoff'?new Set(['--handoff','--task','--attempt'])
812
945
  :command==='hash-implementation'?new Set(['--project-root','--file'])
813
946
  :command==='check-parallel-write'?new Set(['--repo','--assignment'])
814
- :new Set(['--handoff','--reviews-dir','--feature','--task','--project-root','--allow-legacy-unbound','--require-learning',
947
+ :new Set(['--handoff','--reviews-dir','--feature','--task','--project-root','--allow-legacy-unbound','--require-learning','--correction',
948
+ ...(command==='prepare-human-correction'?['--human-authorized','--reason']:[]),
815
949
  ...(['prepare-mark-done','verify-mark-done-plan','mark-done-locked'].includes(command)?['--tasks']:[]),
816
950
  ...(['verify-mark-done-plan','mark-done-locked'].includes(command)?['--expected-plan-digest']:[])]);
817
951
  const required=command==='validate-handoff'?new Set(['--handoff','--task','--attempt'])
@@ -824,15 +958,15 @@ function parseCli(argv){
824
958
  for(let index=1;index<argv.length;){
825
959
  const flag=argv[index];
826
960
  if(!allowed.has(flag))throw new GateError('invalid arguments');
827
- if(flag==='--allow-legacy-unbound'||flag==='--require-learning'){
828
- const key=flag==='--require-learning'?'requireLearning':'allowLegacyUnbound';
961
+ if(flag==='--allow-legacy-unbound'||flag==='--require-learning'||flag==='--human-authorized'){
962
+ const key=flag==='--human-authorized'?'humanAuthorized':flag==='--require-learning'?'requireLearning':'allowLegacyUnbound';
829
963
  if(Object.hasOwn(values,key))throw new GateError(`duplicate argument: ${flag}`);
830
964
  values[key]=true;index++;continue;
831
965
  }
832
966
  const value=argv[index+1];if(value===undefined)throw new GateError('invalid arguments');
833
967
  const key={'--handoff':'handoff','--reviews-dir':'reviewsDir','--feature':'feature','--task':'task','--attempt':'attempt',
834
968
  '--tasks':'tasksPath','--expected-plan-digest':'expectedPlanDigest','--repo':'repo','--assignment':'assignment',
835
- '--project-root':'projectRoot','--file':'file'}[flag];
969
+ '--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason'}[flag];
836
970
  if(['assignment','file'].includes(key)){
837
971
  if(!Object.hasOwn(values,key))values[key]=[];
838
972
  values[key].push(value);
@@ -845,7 +979,7 @@ function parseCli(argv){
845
979
  for(const flag of required){
846
980
  const key={'--handoff':'handoff','--reviews-dir':'reviewsDir','--feature':'feature','--task':'task','--attempt':'attempt',
847
981
  '--tasks':'tasksPath','--expected-plan-digest':'expectedPlanDigest','--repo':'repo','--assignment':'assignment',
848
- '--project-root':'projectRoot','--file':'file'}[flag];
982
+ '--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason'}[flag];
849
983
  if(!Object.hasOwn(values,key))throw new GateError(`missing argument: ${flag}`);
850
984
  }
851
985
  if(Object.hasOwn(values,'attempt')){
@@ -866,6 +1000,8 @@ export function main(argv=process.argv.slice(2),environment=process.env){
866
1000
  result={gate:'handoff',task:payload.task_id,attempt:payload.attempt,outcome:payload.status};
867
1001
  }else if(args.command==='hash-implementation')result={gate:'implementation-hash',
868
1002
  implementation_sha256:implementationSha256(args.projectRoot,args.file),changed_files:[...args.file].sort((left,right)=>Buffer.compare(Buffer.from(left),Buffer.from(right)))};
1003
+ else if(args.command==='prepare-human-correction')result=prepareHumanCorrection(args);
1004
+ else if(args.command==='publish-human-correction-review')result=publishHumanCorrectionReview(args);
869
1005
  else if(args.command==='check-n4')result=checkN4(args);
870
1006
  else if(args.command==='check-n5')result=checkN5(args);
871
1007
  else if(args.command==='prepare-mark-done')result=prepareMarkDone(args);
@@ -271,6 +271,7 @@ def mark_parser() -> argparse.ArgumentParser:
271
271
  parser.add_argument("--task", required=True)
272
272
  parser.add_argument("--tasks", required=True)
273
273
  parser.add_argument("--project-root")
274
+ parser.add_argument("--correction")
274
275
  parser.add_argument("--allow-legacy-unbound", action="store_true")
275
276
  parser.add_argument("--require-learning", action="store_true")
276
277
  return parser
@@ -124,6 +124,17 @@ test('host returns NO_CHANGES without model or execution, logs close and histori
124
124
  assert.equal(inspectCmTestRecovery(f.config,result).overall,'NO_CHANGES');
125
125
  assert.equal(fs.readFileSync(path.join(f.project,'src/input.mjs'),'utf8'),'dirty user work');
126
126
  });
127
+ test('historical recovery reads only its own rows from a shared log above 32 MiB',async t=>{
128
+ const f=fixture(t);
129
+ const result=await run(f.config,()=>assert.fail('no changes need no callback'));
130
+ // A long-lived project log: other runs' rows, past the former 32 MiB whole-file cap.
131
+ const filler='x'.repeat(4000),line=JSON.stringify({schema_version:1,workflow:'cm-ai',event:'progress',run_id:'other-run',detail:filler})+'\n';
132
+ const fd=fs.openSync(result.logFile,'a');
133
+ try{const block=line.repeat(1024);for(let written=0;written<33*1024*1024;written+=Buffer.byteLength(block))fs.writeSync(fd,block);}
134
+ finally{fs.closeSync(fd);}
135
+ assert(fs.statSync(result.logFile).size>32*1024*1024);
136
+ assert.equal(inspectCmTestRecovery(f.config,result).overall,'NO_CHANGES');
137
+ });
127
138
  test('shared CLI dispatches impact for both runtimes; committed source, report, no execution',async t=>{
128
139
  for(const runtime of ['codex','claude']){
129
140
  const f=fixture(t);f.branch();f.config.runtime=runtime;f.write('src/input.mjs','dirty version');