@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
@@ -0,0 +1,206 @@
1
+ // Synthetic control-flow fixtures, not proof of a model's semantic judgement
2
+ // or production token/time savings. No classifier or provider is invoked.
3
+ import test from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
10
+ import {checkPrdDraftMechanics} from '../runtime/js/cm-prd/self-check.mjs';
11
+ import {savePrdDesign,savePrdDraft} from '../runtime/js/cm-prd/draft-save.mjs';
12
+ import {runPrdHostReview} from '../runtime/js/cm-prd/review-host.mjs';
13
+ import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
14
+ import {claimPrdReview,recordPrdReview} from './cm-prd-review-gate.mjs';
15
+ import {buildManifest} from './cm-spec-manifest.mjs';
16
+ import {inspectCmAiAdmission} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
17
+ import {loadConfig,resolveRole,runtimePreset} from './cm-workflow-config.mjs';
18
+
19
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
20
+ const sourceCases={schemaVersion:'1.0',feature:'list',cases:['Render list','Confirm deletion','Style feedback'].map((title,i)=>({
21
+ id:`TC-00${i+1}`,origin:'user',kind:'logic',blocking:true,acIds:[`AC-00${i+1}`],taskIds:['T-001'],
22
+ title,preconditions:['Local fixture'],steps:[title],expected:[`${title} works`],cleanup:['Restore fixture']}))};
23
+ const documents=()=>[
24
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Reversible list feedback\n'+sourceCases.cases.map(c=>`- [ ] [${c.acIds[0]}] ${c.expected[0]}`).join('\n')},
25
+ {path:'design.md',content:'## 方案摘要\nLocal list component, one reversible objective.\n## 接口契约\nListView remains unchanged.'}];
26
+ const draft=(tasks='- [ ] T-001: List feedback ~15min',mapping=['T-001','T-001','T-001'])=>({
27
+ status:'draft',summary:'Synthetic task boundaries',features:[{name:'list',testCasesReason:null,
28
+ documents:[...documents(),{path:'tasks.md',content:tasks},{path:'test-cases.json',content:JSON.stringify({
29
+ ...sourceCases,cases:sourceCases.cases.map((c,i)=>({...c,taskIds:[mapping[i]]}))})}]}]});
30
+ function checked(payload,failed=null){
31
+ return {draftDigest:payload.draft.draftDigest,features:payload.draft.features.map(f=>({directory:f.directory,
32
+ checks:payload.draft.mechanicalSelfCheck.pending.map(id=>({id,status:id===failed?'failed':'passed',
33
+ evidence:[id===failed?'Synthetic boundary finding: authentication and local list changes have independent rollback.':'Synthetic context reference']}))}))};
34
+ }
35
+ function fixture(t,text='Local list feedback, one verifiable reversible objective.'){
36
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-task-grouping-')));
37
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));fs.mkdirSync(path.join(dir,'docs'));
38
+ fs.writeFileSync(path.join(dir,'docs/input.md'),text);
39
+ const cases=path.join(dir,'user-cases.md');fs.writeFileSync(cases,JSON.stringify(sourceCases));
40
+ const config=path.join(dir,'.cm-workflow.json');fs.writeFileSync(config,JSON.stringify({
41
+ version:1,...runtimePreset('claude-codes'),policies:{generate_cases:false}}));
42
+ const configBytes=fs.readFileSync(config),caseBytes=fs.readFileSync(cases);
43
+ const input={skillDir:path.join(root,'skills/cm-prd'),project:dir,specs:dir,cases};
44
+ const calls=[];
45
+ const make=({generate,checkContext=async payload=>checked(payload),restored=null}={})=>createCmPrdAnalysis({
46
+ input,runtime:'codex',restored,record:async()=>{},
47
+ analyze:async payload=>{calls.push('analyze');assert.deepEqual(payload.sources.userCases.content,caseBytes.toString());
48
+ return {status:'analyzed',summary:text,sourcePaths:['docs/input.md',cases],openQuestions:[]};},
49
+ generate:async payload=>{calls.push('generate');assert.deepEqual(payload.role,resolveRole(loadConfig({projectRoot:dir}),'planner','codex'));
50
+ assert.equal(payload.userCases.content,caseBytes.toString());assert.equal(payload.generateCases,false);return generate(payload);},
51
+ checkContext:async payload=>{calls.push('self-check');return checkContext(payload);}});
52
+ const unchanged=()=>{assert.deepEqual(fs.readFileSync(config),configBytes);assert.deepEqual(fs.readFileSync(cases),caseBytes);};
53
+ return {dir,input,calls,make,unchanged};
54
+ }
55
+ async function review(f,host,inspect){
56
+ savePrdDraft({specs:f.dir,writeEnabled:true,getDraft:()=>host.currentDraftForSave()});
57
+ const prepare=()=>host.prepareReview('split','1.list');
58
+ const original=prepare();
59
+ const result=await runPrdHostReview({specs:f.dir,prepared:original,authorContextId:'author',writeEnabled:true,mode:'independent',
60
+ revalidate:prepare,signal:new AbortController().signal,review:async payload=>{
61
+ f.calls.push('review');inspect?.(payload);
62
+ return {reviewer:'codex-subagent',contextId:'fresh-reviewer',independent:true,at:'2026-10-06T00:00:00.000Z',
63
+ result:{verdict:'approved',packageDigest:payload.package.packageDigest,examinedPaths:payload.examinedPaths,findings:[],summary:'Synthetic scope review'}};
64
+ }});
65
+ assert.equal(result.status,'review_recorded');
66
+ // The durable gate, rather than the supplied synthetic verdict, controls repeats.
67
+ assert.equal((await runPrdHostReview({specs:f.dir,prepared:prepare(),authorContextId:'author',writeEnabled:true,mode:'independent',
68
+ revalidate:prepare,signal:new AbortController().signal,review:async()=>assert.fail('second review')})).status,'review_existing');
69
+ assert.equal(prepare().packageDigest,original.packageDigest);return original;
70
+ }
71
+
72
+ test('first full plan reaches planner and one split review; grouped task retains every user case and AC',async t=>{
73
+ const f=fixture(t);const host=f.make({generate:async payload=>{
74
+ assert.equal(payload.phase,'full_draft');assert.equal(payload.revision,null);
75
+ assert.match(payload.instructions,/FIRST task planning only/);
76
+ assert.match(payload.instructions,/independently verifiable and reversible objective/);return draft();
77
+ }});
78
+ await host.advance('Analyze');assert.equal((await host.plan('First plan')).stage,'draft_ready');
79
+ const planned=host.status().draft;
80
+ assert.deepEqual(planned.mechanicalSelfCheck.features,[{directory:'1.list',tasks:1,acceptanceCriteria:3}]);
81
+ const cases=JSON.parse(planned.features[0].documents.find(d=>d.path==='test-cases.json').content);
82
+ assert.deepEqual(cases,sourceCases);assert.equal(planned.mechanicalSelfCheck.completeSelfCheck,false);
83
+ await host.verify();
84
+ await review(f,host,payload=>{
85
+ assert.match(payload.instructions,/assess submitted task boundaries/);
86
+ assert.match(payload.instructions,/high or unknown risk/);
87
+ assert.match(payload.instructions,/every AC, original test and verification prerequisite retained/);
88
+ assert.equal(payload.authorContextId,'author');assert.equal(payload.mode,'independent');
89
+ assert.deepEqual(payload.package.artifacts.map(a=>a.path).sort(),planned.features[0].documents.map(d=>'1.list/'+d.path).sort());
90
+ });
91
+ assert.deepEqual(f.calls,['analyze','generate','self-check','review']);f.unchanged();
92
+ assert.equal(host.status().completionAuthorized,false);
93
+ assert(!fs.existsSync(path.join(f.dir,'.cm-specs-status')));
94
+ });
95
+
96
+ test('first tasks after accepted design receive the same rules without another design/classifier call',async t=>{
97
+ const f=fixture(t);let generations=0;
98
+ const host=f.make({generate:async payload=>{
99
+ if(++generations===1){assert.equal(payload.phase,'design');assert.doesNotMatch(payload.instructions,/FIRST task planning only/);
100
+ return {status:'design',summary:'Local design',features:[{name:'list',documents:documents()}]};}
101
+ assert.equal(payload.phase,'tasks_after_design');assert.match(payload.instructions,/FIRST task planning only/);
102
+ assert.deepEqual(payload.acceptedDesign.features[0].documents,documents());return draft();
103
+ }});
104
+ await host.advance('Analyze');await host.plan('Design',{designOnly:true});
105
+ const ready=host.status().designDraft;
106
+ host.selectDesignReviews({draftDigest:ready.draftDigest,risks:[{feature:'1.list',signals:{greenfieldAdr:false,
107
+ architectureOrDataFlow:false,newRuntimeDependencyOrToolchain:false,publicContractDataOrSecurity:false,fiveOrMoreFunctions:false},
108
+ evidence:['Local component; no design-risk trigger']} ]});
109
+ savePrdDesign({specs:f.dir,writeEnabled:true,getDraft:()=>host.currentDesignForSave()});
110
+ await host.plan('First tasks');await host.verify();await review(f,host);
111
+ assert.deepEqual(f.calls,['analyze','generate','generate','self-check','review']);f.unchanged();
112
+ });
113
+
114
+ test('high/unknown-risk boundary rules reach the planner; existing semantic finding blocks review readiness',async t=>{
115
+ const f=fixture(t,'Local list and authentication; another module risk is unknown.');
116
+ const host=f.make({generate:async payload=>{
117
+ assert.match(payload.instructions,/Keep high-risk work, unknown-risk work/);
118
+ assert.match(payload.instructions,/not keyword risk classification or another model call/);
119
+ assert.match(payload.analysis.summary,/authentication.*unknown/);return draft();
120
+ },checkContext:async payload=>checked(payload,'task_boundary_and_existing_asset_overlap')});
121
+ await host.advance('Analyze');await host.plan('Plan with actual boundaries');
122
+ assert.equal(host.status().draft.mechanicalSelfCheck.status,'mechanical_subset_passed');
123
+ assert.equal((await host.verify()).stage,'self_check_failed');
124
+ assert.throws(()=>host.prepareReview('split','1.list'),/prd_review_not_ready/);
125
+ assert.deepEqual(f.calls,['analyze','generate','self-check']);f.unchanged();
126
+ });
127
+
128
+ test('explicit user split reaches planner unchanged; same-component independent tasks and cases remain intact',async t=>{
129
+ const request='Keep rendering and deletion confirmation as independent tasks for different owners.';
130
+ const f=fixture(t,request),tasks='- [ ] T-001: Render and style list\n- [ ] T-002: Confirm deletion';
131
+ const host=f.make({generate:async payload=>{
132
+ assert(payload.userAnswers.some(m=>m.text===request));assert(payload.messages.some(m=>m.text===request));
133
+ assert.match(payload.instructions,/explicit user requests for independent tasks/);return draft(tasks,['T-001','T-002','T-001']);
134
+ }});
135
+ await host.advance(request);await host.plan(request);await host.verify();
136
+ const planned=host.status().draft;assert.equal(planned.mechanicalSelfCheck.features[0].tasks,2);
137
+ assert.equal(planned.features[0].documents.find(d=>d.path==='tasks.md').content,tasks);
138
+ const cases=JSON.parse(planned.features[0].documents.find(d=>d.path==='test-cases.json').content);
139
+ cases.cases.forEach((c,i)=>{const {taskIds,...semantics}=c,{taskIds:old,...original}=sourceCases.cases[i];assert.deepEqual(semantics,original);});
140
+ await review(f,host,payload=>assert.match(payload.instructions,/explicit user independence/));f.unchanged();
141
+ });
142
+
143
+ test('contract-first DAG remains separate; cycles, task cap and lost AC coverage still fail mechanically',async t=>{
144
+ const f=fixture(t),tasks='- [ ] T-001: Freeze interface and throwing placeholder\n- [ ] T-002: Implement interface\n- [ ] T-003: Call interface\n- T-002 依赖 T-001\n- T-003 依赖 T-001';
145
+ const host=f.make({generate:async payload=>{
146
+ assert.match(payload.instructions,/preserve legitimate contract-first tasks and real dependencies/);
147
+ return draft(tasks,['T-001','T-002','T-003']);
148
+ }});
149
+ await host.advance('Analyze');await host.plan('Contract before implementation');
150
+ const planned=host.status().draft;assert.equal(planned.mechanicalSelfCheck.features[0].tasks,3);
151
+ assert.equal(planned.features[0].documents.find(d=>d.path==='tasks.md').content,tasks);
152
+ const changed=structuredClone(planned),task=changed.features[0].documents.find(d=>d.path==='tasks.md');
153
+ task.content+='\n- T-001 依赖 T-002';assert(checkPrdDraftMechanics(changed).findings.some(f=>f.code==='dependencies_invalid'));
154
+ task.content=Array.from({length:16},(_,i)=>`- [ ] T-${String(i+1).padStart(3,'0')}: Independent`).join('\n');
155
+ assert(checkPrdDraftMechanics(changed).findings.some(f=>f.code==='task_limit_exceeded'));
156
+ task.content=tasks;const cases=JSON.parse(changed.features[0].documents.find(d=>d.path==='test-cases.json').content);
157
+ cases.cases.pop();changed.features[0].documents.find(d=>d.path==='test-cases.json').content=JSON.stringify(cases);
158
+ assert(checkPrdDraftMechanics(changed).findings.some(f=>f.code==='acceptance_test_coverage_missing'));f.unchanged();
159
+ });
160
+
161
+ test('existing failed draft and restored revision receive no first-plan regrouping; IDs and bytes survive',async t=>{
162
+ const f=fixture(t);let generations=0;
163
+ const host=f.make({generate:async()=>{generations++;return draft('- [ ] T-001: Existing first\n- [ ] T-002: Existing second',['T-001','T-002','T-001']);},
164
+ checkContext:async payload=>checked(payload,'acceptance_verifiability')});
165
+ await host.advance('Analyze');await host.plan('Original plan');await host.verify();
166
+ const checkpoint=host.checkpoint(),bytes=JSON.stringify(checkpoint);
167
+ const restored=f.make({restored:checkpoint,generate:async payload=>{
168
+ assert.doesNotMatch(payload.instructions,/FIRST task planning only/);assert.equal(payload.revision.round,2);
169
+ assert.equal(JSON.stringify(payload.revision.draft),JSON.stringify(checkpoint.draft));return draft('- [ ] T-001: Existing first\n- [ ] T-002: Existing second',['T-001','T-002','T-001']);
170
+ }});
171
+ assert.equal(JSON.stringify(restored.checkpoint()),bytes);
172
+ await restored.plan('Correct only the finding');
173
+ assert.equal(restored.status().draft.draftDigest,checkpoint.draft.draftDigest);
174
+ assert.equal(JSON.stringify(checkpoint),bytes);assert.equal(generations,1);f.unchanged();
175
+ });
176
+
177
+ test('approved task boundary drift remains blocked and does not rewrite approval or repartition tasks',async t=>{
178
+ const f=fixture(t),feature=path.join(f.dir,'1.list');fs.mkdirSync(feature);
179
+ for(const d of draft().features[0].documents)fs.writeFileSync(path.join(feature,d.path),d.content);
180
+ const file=path.join(f.dir,'.cm-specs-status');fs.writeFileSync(file,JSON.stringify({status:'approved',features:['1.list'],specFiles:buildManifest(f.dir)}));
181
+ const approval=fs.readFileSync(file),options={specsDir:f.dir,codeProject:f.dir};
182
+ assert.equal(inspectCmAiAdmission(options).state,'ready');
183
+ const task=path.join(feature,'tasks.md');fs.appendFileSync(task,'\n- [ ] T-002: Expanded objective');
184
+ const changed=fs.readFileSync(task),blocked=inspectCmAiAdmission(options);
185
+ assert.equal(blocked.state,'blocked');assert.equal(blocked.reason,'spec_drift');
186
+ assert.deepEqual(fs.readFileSync(file),approval);assert.deepEqual(fs.readFileSync(task),changed);f.unchanged();
187
+ });
188
+
189
+ test('old split package instructions/digest survive claimed, r1 and completed gates with zero reviewer calls',async t=>{
190
+ for(const state of ['claimed','r1','completed']){
191
+ const f=fixture(t),raw=draft(),inspected={draftDigest:'a'.repeat(64),features:[{...raw.features[0],directory:'1.list'}]};
192
+ const prepare=()=>preparePrdReview({specs:f.dir,draft:inspected,stage:'split',feature:'1.list'}),ready=prepare();
193
+ assert.equal(ready.reviewPackage.instructions,'Apply original Step 10.6 to the functional requirements, complete task list and selected design sections. Respect prior design review and do not repeat it. No second attempt.');
194
+ fs.mkdirSync(path.join(f.dir,'.reviews'));claimPrdReview({...ready.paths,package_sha256:ready.packageDigest});
195
+ if(state!=='claimed'){
196
+ fs.mkdirSync(path.join(f.dir,'1.list'));for(const doc of raw.features[0].documents)fs.writeFileSync(path.join(f.dir,'1.list',doc.path),doc.content);
197
+ fs.writeFileSync(ready.paths.evidence,'---\nat: 2026-10-06T00:00:00Z\nreviewer: codex-subagent\nindependent: true\nscope:\n - 1.list/tasks.md\n---\nOriginal review');
198
+ if(state==='completed')recordPrdReview({...ready.paths,disposition:'no_findings',finding_count:0,unresolved_count:0,
199
+ artifact:raw.features[0].documents.map(doc=>path.join(f.dir,'1.list',doc.path))});
200
+ }
201
+ assert.equal(prepare().packageDigest,ready.packageDigest);const before=JSON.stringify(prepare());
202
+ const result=await runPrdHostReview({specs:f.dir,prepared:prepare(),authorContextId:'author',writeEnabled:true,mode:'independent',
203
+ revalidate:prepare,signal:new AbortController().signal,review:async()=>assert.fail('old attempt redispatched')});
204
+ assert.equal(result.status,'review_existing');assert.equal(JSON.stringify(prepare()),before);f.unchanged();
205
+ }
206
+ });
@@ -5,6 +5,10 @@ set -euo pipefail
5
5
  ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
6
6
  SOURCE_CODEX_HOME="${CODEX_HOME:-$HOME/.codex}"
7
7
  SOURCE_CREATOR="$SOURCE_CODEX_HOME/skills/.system/plugin-creator"
8
+ if [ ! -f "$SOURCE_CREATOR/scripts/create_basic_plugin.py" ] &&
9
+ [ -f "$SOURCE_CODEX_HOME/.tmp/plugins/.agents/skills/plugin-creator/scripts/create_basic_plugin.py" ]; then
10
+ SOURCE_CREATOR="$SOURCE_CODEX_HOME/.tmp/plugins/.agents/skills/plugin-creator"
11
+ fi
8
12
  TMP_ROOT=""
9
13
  PYTHON_BIN=""
10
14
 
@@ -33,7 +37,7 @@ trap 'exit 143' TERM
33
37
 
34
38
  command -v byz >/dev/null 2>&1 || blocked "byz command not found"
35
39
  command -v codex >/dev/null 2>&1 || blocked "codex command not found"
36
- [ -d "$SOURCE_CREATOR" ] || blocked "Codex plugin creator not found at $SOURCE_CREATOR"
40
+ [ -f "$SOURCE_CREATOR/scripts/create_basic_plugin.py" ] || blocked "Codex plugin creator not found at $SOURCE_CREATOR"
37
41
  for candidate in python3 python; do
38
42
  if command -v "$candidate" >/dev/null 2>&1 &&
39
43
  "$candidate" -c 'import sys; raise SystemExit(sys.version_info < (3, 9))' >/dev/null 2>&1; then
@@ -14,14 +14,16 @@ const terminal=(r,result)=>({version:1,invocationId:r.invocationId,contextId:r.c
14
14
  async function fixture(fn){
15
15
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-scope-recovery-')));
16
16
  try{
17
- fs.writeFileSync(path.join(root,'code.js'),'before');fs.writeFileSync(path.join(root,'AGENTS.md'),'unchanged instructions');
17
+ fs.writeFileSync(path.join(root,'code.js'),'before');fs.writeFileSync(path.join(root,'notes.md'),'unchanged notes');
18
18
  fs.writeFileSync(path.join(root,'requirements.md'),'fixture');
19
19
  // V1 fixture journal: no native task writes or real provider calls.
20
20
  const records=[];
21
21
  const store={snapshot:()=>structuredClone({identity,records,revision:digest(records)}),
22
22
  append:({expectedRevision,...record})=>{assert.equal(expectedRevision,digest(records));records.push(structuredClone(record));}};
23
23
  let commits=0;
24
- const options={root,identity,scope:['code.js','AGENTS.md'],requirements:['requirements.md'],excludedContexts:['main'],
24
+ // notes.md stays unchanged in scope. Not AGENTS.md: that is a protected path the
25
+ // developer adapter refuses, and the runner now blocks it before dispatch.
26
+ const options={root,identity,scope:['code.js','notes.md'],requirements:['requirements.md'],excludedContexts:['main'],
25
27
  developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:r=>{
26
28
  fs.writeFileSync(path.join(root,'code.js'),'after');return terminal(r,{outcome:'implemented'});}},
27
29
  reviewers:[{id:'reviewer',provider:'claude',requestedModel:'fixture',allowed:true,available:true,contexts:['r1','r2'],
@@ -45,7 +47,7 @@ for(const legacy of [false,true])test(`scope package resumes review and completi
45
47
  }
46
48
  const runner=f.make('resume'),reviewed=await runner.executeEffect(f.effect('review'));
47
49
  assert.equal(reviewed.state,'approved');
48
- assert.equal(reviewed.receipt.result.examinedPaths.includes('AGENTS.md'),!legacy);
50
+ assert.equal(reviewed.receipt.result.examinedPaths.includes('notes.md'),!legacy);
49
51
  const receipt=JSON.stringify(reviewed.receipt);
50
52
  assert.equal((await f.make('resume').executeEffect(f.effect('complete'))).state,'fixture_completed');
51
53
  assert.equal(JSON.stringify(f.make('resume').status().receipt),receipt);
@@ -6,16 +6,27 @@ export function runtimeLanguage(env=process.env,intlLocale=()=>Intl.DateTimeForm
6
6
  try{return /^zh/i.test(intlLocale()||'')?'zh':'en';}catch{return 'en';}
7
7
  }
8
8
  export const messages={
9
+ menu:{zh:'运行时配置:[1] 保留当前配置(推荐,默认) [2] 修改运行时预设 [3] 查看高级模型配置说明 [1]: ',en:'Runtime configuration: [1] Keep current configuration (recommended, default) [2] Change runtime preset [3] Advanced model configuration [1]: '},
10
+ kept:{zh:'已保留当前配置,未写入文件。\n',en:'Kept current configuration; no files written.\n'},
11
+ builtin:{zh:'内置默认(未声明)',en:'Built-in defaults (undeclared)'},
9
12
  tools:{zh:'你手上有哪个 AI 工具?[1] 只有 Codex [2] 只有 Claude [3] 两个都有: ',en:'Which AI tools do you have? [1] Codex only [2] Claude only [3] Both: '},
10
13
  coder:{zh:'谁写代码?[1] Codex(Claude 审,推荐) [2] Claude(Codex 审): ',en:'Who writes code? [1] Codex (Claude reviews, recommended) [2] Claude (Codex reviews): '},
11
14
  scope:{zh:'改哪一层?[1] 当前项目({project}) [2] 用户级默认({user}) [{default}]: ',en:'Which scope? [1] Current project ({project}) [2] User default ({user}) [{default}]: '},
12
15
  create:{zh:'将从模板新建项目配置:{file}\n',en:'Will create project configuration from the template: {file}\n'},
13
16
  current:{zh:'当前用户级默认: {available} / {preset}\n',en:'Current user default: {available} / {preset}\n'},
14
- invalid:{zh:'当前用户级默认无效: {error}\n',en:'Invalid user default: {error}\n'},
17
+ invalid:{zh:'当前用户级默认无效({file}): {error};文件已保留,请先修正后重试。\n',en:'Invalid user default ({file}): {error}; file preserved. Correct it before retrying.\n'},
15
18
  keep:{zh:'保留?[Y/n] ',en:'Keep it? [Y/n] '},
16
- preview:{zh:'将写入: {file}\n预设: {preset}\n当前值:\n{current}\n',en:'Will write: {file}\nPreset: {preset}\nCurrent value:\n{current}\n'},
19
+ configure:{zh:'现在配置用户默认?可跳过,稍后用 cm-runtime 配置。[y/N] ',en:'Configure a user default now? Optional; use cm-runtime later. [y/N] '},
20
+ preview:{zh:'将写入: {file}\n范围: {scope}\n预设: {preset}\n写入字段(当前值 -> 候选值):\n{fields}\n影响: {impact}\n当前项目有效值:\n{current}\n保存后当前项目有效值:\n{effective}\n',en:'Will write: {file}\nScope: {scope}\nPreset: {preset}\nFields to write (current -> candidate):\n{fields}\nImpact: {impact}\nCurrent project effective values:\n{current}\nProject effective values after saving:\n{effective}\n'},
21
+ overridden:{zh:'项目已声明 runtimes.available,当前项目继续使用项目声明;用户默认仅供未声明的项目继承。已有 run 不变。',en:'The project declares runtimes.available and overrides this user default; only undeclared projects inherit it. Existing runs unchanged.'},
22
+ userImpact:{zh:'只影响未声明 runtimes.available 的项目;项目显式角色字段仍优先,其他项目须各自校验。已有 run 不变。',en:'Applies only to projects without runtimes.available; explicit project role fields still win. Other projects require their own validation. Existing runs unchanged.'},
23
+ projectImpact:{zh:'当前项目将使用此声明,只影响新 run。模型别名和其他已有字段保留。',en:'This project will use the declaration for new runs. Model aliases and other existing fields are retained.'},
24
+ notProject:{zh:'安装器只配置用户默认,未核对任何项目的有效值。',en:'Installer configures user defaults only; no project effective values were checked.'},
25
+ modelWarning:{zh:'模型别名原样保留;更换 adapter 后,非默认模型未必兼容。校验通过仅证明配置合同有效,不证明模型可调用或配额可用。\n',en:'Model aliases are retained; a non-default model may be incompatible with a changed adapter. Validation proves the configuration contract only, not model access or quota.\n'},
26
+ drift:{zh:'预览后的配置已改变: {file};未保存,请重新预览并确认。',en:'Configuration changed after preview: {file}; not saved. Generate a fresh preview and confirm again.'},
27
+ advanced:{zh:'高级模型配置说明:建议保留当前默认,仅在有明确需要时手工编辑项目 .cm-workflow.yml 的模型别名。\n合同说明: {doc}\n校验: node "{validator}" --project "<项目路径>" --print-effective\n校验不证明 provider 兼容或配额可用;预设切换保留模型别名。\nunset --user 只删除用户默认,项目声明仍优先,不是恢复所有默认值。\n',en:'Advanced model configuration: keep current defaults unless you have a specific need; edit model aliases manually in the project .cm-workflow.yml.\nContract: {doc}\nValidate: node "{validator}" --project "<project path>" --print-effective\nValidation does not prove provider compatibility or quota; preset changes preserve model aliases.\nunset --user removes only user defaults; project declarations still win. It is not a reset of all settings.\n'},
17
28
  absent:{zh:'未声明',en:'Undeclared'},
18
- confirm:{zh:'确认?[Y/n] ',en:'Confirm? [Y/n] '},
29
+ confirm:{zh:'确认?[y/N] ',en:'Confirm? [y/N] '},
19
30
  cancelled:{zh:'已放弃,未修改运行时声明。\n',en:'Cancelled; runtime declaration unchanged.\n'},
20
31
  installed:{zh:'✓ 用户级运行时默认已写入 {file} ({preset})\n',en:'✓ User runtime default saved to {file} ({preset})\n'},
21
32
  comment:{zh:'用 cm-runtime set --user <preset> 修改用户级默认。',en:'Use cm-runtime set --user <preset> to change the user default.'},
@@ -24,7 +35,7 @@ export const messages={
24
35
  warning:{zh:'WARN: runtimes.available 声明 {available},但本机 {runtime} CLI 不可解析(可解析≠配额可用)',en:'WARN: runtimes.available declares {available}, but {runtime} CLI is not resolvable (presence does not prove quota)'},
25
36
  saved:{zh:'已保存 {file}: {preset} ({source});已有 run 不变',en:'Saved {file}: {preset} ({source}); existing runs unchanged'},
26
37
  removed:{zh:'已删除用户默认: {file};项目声明仍优先',en:'Removed user default: {file}; project declarations still take precedence'},
27
- help:{zh:'cm-runtime [--project PATH]:无参数在 TTY 下进入交互向导;非 TTY 显示用法并退出 2。',en:'cm-runtime [--project PATH]: no command opens the interactive wizard in a TTY; non-TTY prints usage and exits 2.'},
38
+ help:{zh:'cm-runtime [--project PATH]:无参数在 TTY 下先查看配置,默认保留;非 TTY 显示用法并退出 2。',en:'cm-runtime [--project PATH]: no command shows current configuration in a TTY and defaults to keeping it; non-TTY prints usage and exits 2.'},
28
39
  failed:{zh:'运行时声明未完成: {error}',en:'Runtime declaration incomplete: {error}'},
29
40
  };
30
41
  export function runtimeText(key,lang=runtimeLanguage(),values={}){
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import {fileURLToPath} from 'node:url';
6
6
  import {createInterface} from 'node:readline';
7
7
  import {userRuntimesPath,readConfigText,parseUserRuntimes} from './cm-workflow-config.mjs';
8
- import {writeUserRuntime} from './cm-runtime.mjs';
8
+ import {writeUserRuntime,prepareRuntimePreview,formatRuntimePreview} from './cm-runtime.mjs';
9
9
  import {runtimeLanguage,runtimeText as t} from './cm-runtime-i18n.mjs';
10
10
 
11
11
  export class PromptCancelled extends Error {}
@@ -54,12 +54,16 @@ export async function promptRuntime(argv=process.argv.slice(2),input=process.std
54
54
  try{
55
55
  const current=parseUserRuntimes(readConfigText(file));
56
56
  output.write(t('current',lang,{available:current.runtimes.available,preset:current.preset}));
57
- }catch(error){output.write(t('invalid',lang,{error:error.message}));}
57
+ }catch(error){output.write(t('invalid',lang,{file,error:error.message}));return;}
58
58
  const keep=await ask(t('keep',lang));
59
59
  if(keep!=='n'&&keep!=='N')return;
60
- }
60
+ }else if((await ask(t('configure',lang))).toLowerCase()!=='y')return;
61
61
  const preset=await askRuntimePreset(ask,lang);
62
- output.write(t('installed',lang,{file:writeUserRuntime(preset,{lang}),preset}));
62
+ const preview=prepareRuntimePreview(null,preset,{user:true,lang});
63
+ output.write(formatRuntimePreview(preview,lang));
64
+ let confirm;do{confirm=(await ask(t('confirm',lang))).toLowerCase();}while(!['','y','n'].includes(confirm));
65
+ if(confirm!=='y')throw new PromptCancelled();
66
+ output.write(t('installed',lang,{file:writeUserRuntime(preset,{lang,preview}),preset}));
63
67
  }catch(error){if(error instanceof PromptCancelled)output.write(t('cancelled',lang));else throw error;}
64
68
  finally{questions.close();}
65
69
  }
@@ -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);