@aibyzero/cm-workflow 0.16.1 → 0.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +179 -0
  4. package/README.md +2 -2
  5. package/VERSION +1 -1
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +46 -7
  8. package/docs/next-steps.md +110 -0
  9. package/docs/untested-branches.md +79 -0
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
  12. package/runtime/js/cm-ai/cm-ai-admission.mjs +5 -0
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
  15. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
  16. package/runtime/js/cm-ai/drive-core.mjs +68 -0
  17. package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
  18. package/runtime/js/cm-ai/effect-contract.mjs +38 -5
  19. package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
  20. package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
  21. package/runtime/js/cm-ai/host-handoff.mjs +9 -14
  22. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
  23. package/runtime/js/cm-ai/host-session.mjs +2 -2
  24. package/runtime/js/cm-ai/host.mjs +1 -1
  25. package/runtime/js/cm-ai/metrics-table.mjs +22 -0
  26. package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
  27. package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
  28. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
  29. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
  30. package/runtime/js/cm-ai/task-runner.mjs +41 -8
  31. package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
  32. package/runtime/js/cm-fix/cause-package.mjs +21 -0
  33. package/runtime/js/cm-fix/dossier.mjs +40 -1
  34. package/runtime/js/cm-fix/execution.mjs +369 -83
  35. package/runtime/js/cm-fix/host.mjs +7 -3
  36. package/runtime/js/cm-fix/layout.mjs +34 -0
  37. package/runtime/js/cm-fix/metrics.mjs +2 -4
  38. package/runtime/js/cm-fix/progress.mjs +14 -0
  39. package/runtime/js/cm-fix/protected-edits.mjs +1 -1
  40. package/runtime/js/cm-fix/red-test.mjs +7 -6
  41. package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
  42. package/runtime/js/cm-fix/regression.mjs +16 -10
  43. package/runtime/js/cm-fix/repair.mjs +16 -13
  44. package/runtime/js/cm-fix/test-author.mjs +2 -1
  45. package/runtime/js/cm-fix/test-extension.mjs +45 -0
  46. package/runtime/js/cm-fix/walkthrough.mjs +8 -2
  47. package/runtime/js/cm-prd/accepted-design.mjs +28 -9
  48. package/runtime/js/cm-prd/analysis.mjs +68 -16
  49. package/runtime/js/cm-prd/change.mjs +21 -1
  50. package/runtime/js/cm-prd/draft-save.mjs +96 -2
  51. package/runtime/js/cm-prd/failed-correction.mjs +51 -0
  52. package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
  53. package/runtime/js/cm-prd/review-correction.mjs +3 -0
  54. package/runtime/js/cm-prd/review-disposition.mjs +33 -15
  55. package/runtime/js/cm-prd/review-findings.mjs +2 -2
  56. package/runtime/js/cm-prd/review-host.mjs +2 -0
  57. package/runtime/js/cm-prd/review-preparation.mjs +28 -1
  58. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  59. package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
  60. package/runtime/js/cm-prd/session.mjs +5 -5
  61. package/runtime/js/cm-prd/split-design.mjs +67 -0
  62. package/runtime/js/cm-prd/summary.mjs +53 -8
  63. package/runtime/js/cm-refactor/workflow.mjs +103 -21
  64. package/scripts/audit-untested-enums.mjs +59 -0
  65. package/scripts/cm-ai-batch-drive.mjs +251 -0
  66. package/scripts/cm-ai-batch-drive.test.mjs +152 -0
  67. package/scripts/cm-ai-contracts.test.mjs +30 -0
  68. package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
  69. package/scripts/cm-ai-drive.mjs +334 -0
  70. package/scripts/cm-ai-drive.test.mjs +251 -0
  71. package/scripts/cm-ai-execution-diagnostic.test.mjs +25 -0
  72. package/scripts/cm-ai-fix-integration.test.mjs +1 -1
  73. package/scripts/cm-ai-host.mjs +41 -18
  74. package/scripts/cm-ai-host.test.mjs +37 -0
  75. package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
  76. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
  77. package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
  78. package/scripts/cm-ai-review-timeout.test.mjs +30 -0
  79. package/scripts/cm-ai-run.mjs +59 -11
  80. package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
  81. package/scripts/cm-ai-session-chain.test.mjs +261 -0
  82. package/scripts/cm-ai-supersede.test.mjs +320 -0
  83. package/scripts/cm-check-drive.mjs +93 -0
  84. package/scripts/cm-check-drive.test.mjs +62 -0
  85. package/scripts/cm-check-host.test.mjs +47 -0
  86. package/scripts/cm-claude-probe.test.mjs +117 -2
  87. package/scripts/cm-fix-abandon.test.mjs +383 -0
  88. package/scripts/cm-fix-cause-package.test.mjs +31 -1
  89. package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
  90. package/scripts/cm-fix-drive.mjs +168 -0
  91. package/scripts/cm-fix-drive.test.mjs +117 -0
  92. package/scripts/cm-fix-escalation.test.mjs +214 -0
  93. package/scripts/cm-fix-execution.test.mjs +67 -0
  94. package/scripts/cm-fix-host.mjs +4 -2
  95. package/scripts/cm-fix-metrics.test.mjs +32 -0
  96. package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
  97. package/scripts/cm-fix-qa-source.test.mjs +3 -3
  98. package/scripts/cm-fix-session-chain.test.mjs +244 -0
  99. package/scripts/cm-fix-test-extension.test.mjs +246 -0
  100. package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
  101. package/scripts/cm-host-handoff.test.mjs +37 -0
  102. package/scripts/cm-idea-drive.mjs +99 -0
  103. package/scripts/cm-idea-drive.test.mjs +50 -0
  104. package/scripts/cm-init-drive.mjs +191 -0
  105. package/scripts/cm-init-drive.test.mjs +59 -0
  106. package/scripts/cm-log-event.mjs +9 -0
  107. package/scripts/cm-prd-design-phase.test.mjs +355 -15
  108. package/scripts/cm-prd-drive.mjs +308 -0
  109. package/scripts/cm-prd-drive.test.mjs +154 -0
  110. package/scripts/cm-prd-host.mjs +46 -17
  111. package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
  112. package/scripts/cm-prd-review-disposition.test.mjs +133 -7
  113. package/scripts/cm-prd-review-gate.mjs +23 -4
  114. package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
  115. package/scripts/cm-prd-summary.test.mjs +48 -4
  116. package/scripts/cm-refactor-drive.mjs +237 -0
  117. package/scripts/cm-refactor-drive.test.mjs +77 -0
  118. package/scripts/cm-refactor-gaps.test.mjs +276 -0
  119. package/scripts/cm-refactor-host.test.mjs +1 -48
  120. package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
  121. package/scripts/cm-release-smoke.sh +14 -0
  122. package/scripts/cm-test-drive.mjs +132 -0
  123. package/scripts/cm-test-drive.test.mjs +91 -0
  124. package/scripts/cm-test-session.test.mjs +117 -0
  125. package/scripts/correction-check.test.mjs +38 -0
  126. package/scripts/fixtures/claude-model-marker.mjs +6 -0
  127. package/scripts/fixtures/claude-review-process.mjs +7 -0
  128. package/scripts/fixtures/cm-refactor.mjs +56 -0
  129. package/skills/cm-ai/SKILL.md +1 -1
  130. package/skills/cm-ai/references/N4-review.md +2 -0
  131. package/skills/cm-ai/references/N8-finish.md +1 -0
  132. package/skills/cm-ai/references/js-host.md +80 -3
  133. package/skills/cm-check/references/js-host.md +2 -0
  134. package/skills/cm-fix/SKILL.md +11 -4
  135. package/skills/cm-fix/references/js-host.md +67 -2
  136. package/skills/cm-fix/references/test-extension.md +57 -0
  137. package/skills/cm-idea/references/js-host.md +2 -0
  138. package/skills/cm-init/references/js-host.md +2 -0
  139. package/skills/cm-prd/SKILL.md +8 -8
  140. package/skills/cm-prd/references/js-change-recovery.md +41 -0
  141. package/skills/cm-prd/references/js-host.md +64 -2
  142. package/skills/cm-prd/references/spec-self-check.md +14 -2
  143. package/skills/cm-refactor/SKILL.md +5 -0
  144. package/skills/cm-refactor/references/js-batch.md +3 -1
  145. package/skills/cm-refactor/references/js-host.md +49 -0
  146. package/skills/cm-test/references/js-host.md +5 -0
  147. package/skills/cm-test/references/unit-coverage.md +2 -2
@@ -0,0 +1,246 @@
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 {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
7
+ import {createFixHost} from '../runtime/js/cm-fix/host.mjs';
8
+ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
9
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
10
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ import {captureReviewBaseline,readReviewSourceFiles} from '../runtime/js/cm-ai/review-package.mjs';
12
+ import {readTestExtensionPlan,verifyExtensionFiles,extendRevisionReviewBaseline,inventory} from '../runtime/js/cm-fix/test-extension.mjs';
13
+
14
+ // Real temporary files/commands/owner/CLI; model responses and diagnostics are
15
+ // synthetic. No live provider, XBrief writes, installation or Git operations.
16
+ async function fixture(t,mode='changes_requested',hooks={}){
17
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-review-recovery-')));
18
+ const cwd=path.join(root,'code');fs.mkdirSync(cwd);
19
+ const logHome=process.env.CM_WORKFLOW_LOG_HOME;process.env.CM_WORKFLOW_LOG_HOME=path.join(root,'mirror');
20
+ t.after(()=>{if(logHome===undefined)delete process.env.CM_WORKFLOW_LOG_HOME;else process.env.CM_WORKFLOW_LOG_HOME=logHome;fs.rmSync(root,{recursive:true,force:true});});
21
+ fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
22
+ fs.writeFileSync(path.join(cwd,'red.mjs'),"import {value} from './value.mjs';if(value!==2){console.error('BUG');process.exit(1)}");
23
+ fs.writeFileSync(path.join(cwd,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1)");
24
+ fs.writeFileSync(path.join(cwd,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
25
+ const config={identity:{repositoryId:'fixture',runId:'recovery',taskId:'T-FIX-one',attempt:1},defect:'Wrong value',
26
+ reproduction:{cwd,command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000},
27
+ redTest:{cwd,testFiles:['red.mjs'],command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000},
28
+ baseline:{cwd,testFiles:['existing.mjs'],commands:[{id:'existing',command:[process.execPath,'existing.mjs']}],timeoutMs:2000},
29
+ repair:{scope:['value.mjs'],requirements:['value.mjs']},
30
+ walkthrough:{timeoutMs:2000,flows:[{id:'value',modules:['value'],steps:['Read value'],expected:['value is 2'],kind:'commands',command:[process.execPath,'red.mjs']}]}};
31
+ const permissions=['--allow-cause-review','--allow-reproduction','--allow-red-test','--allow-baseline','--allow-repair','--allow-regression','--allow-final-review','--allow-walkthrough','--allow-finish'];
32
+ const model='synthetic',review={model,disabledSkills:[],preflight:{passed:true,cli_model:model,prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd,model,disabledSkills:[]})}};
33
+ let calls=0,repairs=0,authors=0;
34
+ const workerFactory=()=>async({prompt},{onEvent})=>{
35
+ calls++;const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);
36
+ const thread=calls===1||mode==='reuse-thread'||['reuse-first-thread','revision-reuses-lost-thread'].includes(mode)&&calls===3?'old-thread':`new-thread-${calls}`;
37
+ onEvent({event:'thread.started',provider_thread:thread});
38
+ if(calls===1&&!['approved','changes_requested','cause-tests'].includes(mode)||mode==='loss-again'
39
+ ||['twice-then-success','reuse-first-thread'].includes(mode)&&calls<=2)throw Error('Synthetic lost result');
40
+ const verdict=mode==='changes_requested'&&calls===1||mode==='revision-reuses-lost-thread'&&calls===2?'changes_requested':'approved';
41
+ for(const event of [{event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},
42
+ {event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
43
+ return {status:'succeeded',value:{verdict,packageDigest:data.reviewPackage.packageDigest,examinedPaths:data.examinedPaths,
44
+ findings:verdict==='changes_requested'?[{id:'F1',severity:'P2',path:'value.mjs',message:'Add missing boundary coverage',evidence:'Fixture'}]:[],summary:'Synthetic'}};
45
+ };
46
+ const reviewHost=createFixReviewHost({codeProject:cwd,hostContextId:'fixture-host',review,permissions,workerFactory});
47
+ const configuration={hostContextId:'fixture-host',...config,causeReview:reviewHost.reviewer};delete configuration.identity;
48
+ const learning={contextDigest:digest([]),files:[],application:{contextDigest:digest([]),status:'no_relevant_lesson',summary:'No fixture instructions'}};
49
+ const bridge={async call(kind){
50
+ if(kind==='fix_diagnose')return {status:'diagnosed',rootCause:'Wrong value',plan:'Correct value',affectedPaths:mode==='cause-tests'?['value.mjs','red.mjs']:['value.mjs'],affectedModules:mode==='cause-tests'?['value','two','three']:['value'],crossLayer:false,investigation:{discardedAlternatives:[],boundaryAnalysis:null}};
51
+ if(kind==='fix_test_author'){authors++;if(hooks.author)await hooks.author(cwd);else fs.appendFileSync(path.join(cwd,'red.mjs'),'\n// additional boundary assertion\nif(!Number.isInteger(value))process.exit(2);');return {outcome:'authored'};}
52
+ if(kind==='fix_repair'){repairs++;if(!(hooks.noSourceRevision&&repairs>1))fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=2;'+(repairs>1?' // revised':''));return {outcome:'repaired'};}
53
+ if(kind==='fix_retrospective')return {status:'no_new_lesson',candidates:[],reason:null};
54
+ throw Error(kind);
55
+ }};
56
+ if(mode==='cause-tests'){configuration.testAuthor={requirements:['value.mjs']};delete configuration.walkthrough;}
57
+ const options={identity:config.identity,configuration,create:true};
58
+ let owner=openFixExecution(options,{...reviewHost.execution,bridge,prepare:async()=>learning});
59
+ t.after(()=>owner.close());
60
+ const host=createFixHost({owner,config,permissions,authority:reviewHost.authority,finalAuthority:reviewHost.finalAuthority});
61
+ if(mode==='cause-tests'){
62
+ await owner.advance({authorized:true});
63
+ const pkg=owner.causeReviewPackage();await reviewHost.authority.hostDecisionProvider.decide({identity:config.identity,packageDigest:pkg.packageDigest},new AbortController().signal);
64
+ await owner.reviewCause();
65
+ return {owner:()=>owner,cwd,options,authors:()=>authors,reviewHost};
66
+ }
67
+ for(const operation of ['advance','red_test','baseline','repair','regression','retrospective','handoff','final_review'])
68
+ await host.handle({requestId:operation,operation});
69
+ const specsRoot=path.join(cwd,'docs/fixes'),statePath=path.join(specsRoot,'.reviews/.execution/recovery/state.json');
70
+ const bytes=fs.readFileSync(statePath),state=JSON.parse(bytes),registered=state.records.find(r=>r.id==='fix-final-registered').payload;
71
+ const request={requestId:'recover',operation:'recover_final_review',invocationId:registered.request.invocationId,
72
+ packageDigest:registered.request.payload.reviewPackage.packageDigest,previousInvocationStopped:true,reason:'Human authorized one continuation; previous process stopped'};
73
+ const reopen=()=>{owner.close();owner=openFixExecution({...options,create:false},{...reviewHost.execution,bridge,prepare:async()=>learning});return owner;};
74
+ return {cwd,statePath,bytes,state,request,reopen,host:()=>createFixHost({owner,config,permissions,authority:reviewHost.authority,finalAuthority:reviewHost.finalAuthority}),owner:()=>owner,calls:()=>calls,repairs:()=>repairs,authors:()=>authors,options};
75
+ }
76
+
77
+ const plan={testFiles:['red.mjs'],command:[process.execPath,'red.mjs'],reason:'Coverage: integer boundary omitted by round 1 tests; original failure remains archived.',findingIds:['F1']};
78
+ test('F56 F4 revision test-author executes and retains original red evidence',async t=>{
79
+ const f=await fixture(t),owner=f.owner();owner.publishReview();
80
+ const before=JSON.parse(fs.readFileSync(f.statePath)).records;
81
+ assert.throws(()=>openFixExecution({...f.options,identity:{...f.options.identity,runId:'other-run'}}),{code:'fix_evidence_name_taken'});
82
+ const red=owner.status().redTest,bytes=fs.readFileSync(path.join(f.cwd,'docs/fixes',red.output.path));
83
+ await owner.prepareRevision({authorized:true,tests:plan});
84
+ await owner.authorTests({authorized:true});
85
+ assert.equal(f.authors(),1,'F4 authorTests never dispatched in revision_prepared');
86
+ assert.equal(owner.status().stage,'revision_test_check_required');
87
+ await owner.runRevisionTests({authorized:true});
88
+ assert.equal(owner.status().stage,'revision_prepared');
89
+ await owner.repair({authorized:true});await owner.runRegression({authorized:true});
90
+ assert.equal(owner.status().stage,'revision_handoff_required');
91
+ await owner.retrospect();owner.createHandoff();
92
+ assert.equal(owner.status().stage,'revision_final_review_required');
93
+ assert.deepEqual(owner.status().redTest,red);
94
+ assert.deepEqual(fs.readFileSync(path.join(f.cwd,'docs/fixes',red.output.path)),bytes);
95
+ assert.deepEqual(JSON.parse(fs.readFileSync(f.statePath)).records.slice(0,before.length),before);
96
+ assert.equal(f.reopen().status().stage,'revision_final_review_required');
97
+ for(const operation of ['final_review','publish_review','check_n5','post_review_regression','walkthrough','finish'])await f.host().handle({requestId:operation,operation});
98
+ assert.equal(f.reopen().status().stage,'completed');
99
+ });
100
+ test('F56 F6 reviewed affected test accepts only registered author changes',async t=>{
101
+ const f=await fixture(t,'cause-tests'),owner=f.owner();
102
+ assert.equal(owner.status().stage,'test_author_required');
103
+ const stateFile=path.join(f.cwd,'docs/fixes/.reviews/.execution/recovery/state.json');
104
+ const history=JSON.parse(fs.readFileSync(stateFile)).records;
105
+ const causeFile=path.join(f.cwd,'docs/fixes/.reviews/fix-one-cause-r1.md'),receipt=fs.readFileSync(causeFile);
106
+ await owner.authorTests({authorized:true});
107
+ assert.equal(owner.status().stage,'red_test_required');
108
+ assert.deepEqual(JSON.parse(fs.readFileSync(stateFile)).records.slice(0,history.length),history);
109
+ assert.deepEqual(fs.readFileSync(causeFile),receipt);
110
+ await owner.runRedTest({authorized:true});assert.equal(owner.status().stage,'baseline_required');
111
+ fs.appendFileSync(path.join(f.cwd,'value.mjs'),' // unauthorized source change');
112
+ assert.equal(owner.status().stage,'cause_review_drift');
113
+ fs.writeFileSync(path.join(f.cwd,'value.mjs'),'export const value=1;');
114
+ fs.appendFileSync(causeFile,'tampered');
115
+ assert.equal(owner.status().stage,'cause_review_evidence_required');
116
+ });
117
+
118
+ test('F56 coverage-only revision does not require a fake business edit',async t=>{
119
+ const f=await fixture(t,'changes_requested',{noSourceRevision:true}),owner=f.owner();owner.publishReview();
120
+ await owner.prepareRevision({authorized:true,tests:plan});await owner.authorTests({authorized:true});await owner.runRevisionTests({authorized:true});
121
+ await owner.repair({authorized:true});
122
+ assert.equal(owner.status().stage,'revision_regression_required');
123
+ assert.deepEqual(owner.status().revisionRepair.changedFiles,[]);
124
+ await owner.runRegression({authorized:true});await owner.retrospect();owner.createHandoff();
125
+ assert.equal(owner.status().stage,'revision_final_review_required');
126
+ });
127
+
128
+ test('F56 extension accepts a new file and extended baseline test in the same review',async t=>{
129
+ const f=await fixture(t,'changes_requested',{author(cwd){
130
+ fs.appendFileSync(path.join(cwd,'existing.mjs'),';if(!Number.isInteger(value))process.exit(2);');
131
+ fs.writeFileSync(path.join(cwd,'boundary.mjs'),"import {value} from './value.mjs';if(value!==2)process.exit(3)");
132
+ }}),owner=f.owner();owner.publishReview();
133
+ const selected={...plan,testFiles:['boundary.mjs','existing.mjs'],command:[process.execPath,'--test','boundary.mjs','existing.mjs']};
134
+ await owner.prepareRevision({authorized:true,tests:selected});await owner.authorTests({authorized:true});
135
+ assert.equal(owner.status().stage,'revision_test_check_required');
136
+ const before=owner.status().baseline;
137
+ assert.equal((await owner.repair({authorized:true})).stage,'revision_test_check_required');
138
+ await owner.runRevisionTests({authorized:true});await owner.repair({authorized:true});await owner.runRegression({authorized:true});
139
+ assert.equal(owner.status().stage,'revision_handoff_required');
140
+ await owner.retrospect();owner.createHandoff();
141
+ const pkg=owner.finalReviewPackage();
142
+ assert(pkg.changes.some(change=>change.path==='boundary.mjs'&&change.before===null));
143
+ assert(pkg.changes.some(change=>change.path==='existing.mjs'&&change.before!==null));
144
+ assert.deepEqual(owner.status().baseline,before);
145
+ });
146
+
147
+ test('F56 coverage failure is recorded honestly and must pass after repair',async t=>{
148
+ const f=await fixture(t),owner=f.owner();owner.publishReview();
149
+ await owner.prepareRevision({authorized:true,tests:{...plan,command:[process.execPath,'-e','process.exit(5)']}});
150
+ await owner.authorTests({authorized:true});await owner.runRevisionTests({authorized:true});
151
+ assert.equal(owner.status().stage,'revision_prepared');
152
+ assert.equal(owner.status().revisionTestCheck.observations[0].exitCode,5);
153
+ assert.equal(owner.status().redTest.observation.exitCode,1);
154
+ await owner.repair({authorized:true});await owner.runRegression({authorized:true});
155
+ assert.equal(owner.status().stage,'revision_regression_blocked');
156
+ assert.equal(owner.status().revisionRegression.testExtension.observations[0].exitCode,5);
157
+ assert.equal(f.reopen().status().stage,'revision_regression_blocked');
158
+ });
159
+
160
+ test('F56 lost test-author result remains unknown and never dispatches again',async t=>{
161
+ const f=await fixture(t,'changes_requested',{author(cwd){fs.appendFileSync(path.join(cwd,'red.mjs'),'\n// interrupted edit');throw Error('lost');}});
162
+ const owner=f.owner();owner.publishReview();await owner.prepareRevision({authorized:true,tests:plan});
163
+ assert.equal((await owner.authorTests({authorized:true})).stage,'unknown');
164
+ const resumed=f.reopen();await resumed.authorTests({authorized:true});await resumed.runRevisionTests({authorized:true});
165
+ assert.equal(resumed.status().stage,'unknown');assert.equal(f.authors(),1);
166
+ });
167
+
168
+ test('F56 unauthorized edit after preparation is refused before registering author intent',async t=>{
169
+ const f=await fixture(t),owner=f.owner();owner.publishReview();await owner.prepareRevision({authorized:true,tests:plan});
170
+ const records=JSON.parse(fs.readFileSync(f.statePath)).records;
171
+ fs.appendFileSync(path.join(f.cwd,'value.mjs'),' // unauthorized');
172
+ await owner.authorTests({authorized:true});
173
+ assert.equal(f.authors(),0);
174
+ assert.deepEqual(JSON.parse(fs.readFileSync(f.statePath)).records,records);
175
+ assert.equal(f.reopen().status().stage,'revision_test_evidence_required');
176
+ });
177
+
178
+ test('F56 rejects missing findings, business scope, permissions, late edits and changed raw red',async t=>{
179
+ const f=await fixture(t),owner=f.owner();owner.publishReview();
180
+ await assert.rejects(owner.prepareRevision({authorized:true,tests:{...plan,findingIds:['absent']}}),{code:'fix_test_extension_finding_required'});
181
+ await assert.rejects(owner.prepareRevision({authorized:true,tests:{...plan,testFiles:['value.mjs']}}),{code:'fix_test_extension_scope'});
182
+ await assert.rejects(owner.prepareRevision({authorized:true,tests:{...plan,reason:''}}));
183
+ await owner.prepareRevision({authorized:true,tests:plan});
184
+ await assert.rejects(owner.authorTests(),{code:'test_author_authorization_required'});
185
+ await owner.authorTests({authorized:true});
186
+ await assert.rejects(owner.runRevisionTests(),{code:'regression_authorization_required'});
187
+ await owner.runRevisionTests({authorized:true});
188
+ const redFile=path.join(f.cwd,'docs/fixes',owner.status().redTest.output.path),red=fs.readFileSync(redFile);
189
+ const altered=JSON.parse(red);altered.stderrBase64=Buffer.from('BUG changed historical output').toString('base64');
190
+ fs.writeFileSync(redFile,JSON.stringify(altered));assert.equal(owner.status().stage,'red_test_evidence_required');fs.writeFileSync(redFile,red);
191
+ fs.appendFileSync(path.join(f.cwd,'red.mjs'),' // unregistered');
192
+ assert.equal(owner.status().stage,'revision_test_evidence_required');
193
+ });
194
+
195
+ test('F56 existing prepared revision can append a test plan without rewriting preparation',async t=>{
196
+ const f=await fixture(t),owner=f.owner();owner.publishReview();await owner.prepareRevision({authorized:true});
197
+ const before=JSON.parse(fs.readFileSync(f.statePath)).records;
198
+ await owner.prepareRevision({authorized:true,tests:plan});
199
+ assert.equal(owner.status().stage,'revision_test_author_required');
200
+ await owner.authorTests({authorized:true});await owner.runRevisionTests({authorized:true});await owner.repair({authorized:true});
201
+ assert.equal(owner.status().stage,'revision_regression_required');
202
+ assert.deepEqual(JSON.parse(fs.readFileSync(f.statePath)).records.slice(0,before.length),before);
203
+ assert.equal(f.reopen().status().stage,'revision_regression_required');
204
+ });
205
+
206
+ test('F56 M2 extension plan rejects an absent file reserved for business repair',()=>{
207
+ // A new file passes the existing-file restriction; only repair-scope exclusion
208
+ // prevents authoring it as a test before the business repair creates it.
209
+ const context={configuration:{redTest:{testFiles:['red.mjs']},baseline:{testFiles:['existing.mjs']},
210
+ repair:{scope:['new-business.mjs']}},feedback:{review:{verdict:'changes_requested',findings:[{id:'F1'}]}},files:[]};
211
+ assert.deepEqual(readTestExtensionPlan({...plan,testFiles:['new-boundary.mjs']},context).testFiles,['new-boundary.mjs']);
212
+ for(const file of ['new-business.mjs','NEW-BUSINESS.mjs'])
213
+ assert.throws(()=>readTestExtensionPlan({...plan,testFiles:[file]},context),{code:'fix_test_extension_scope'});
214
+ });
215
+
216
+ test('F56 M3 extension file verification rejects post-author edits before downstream evidence',t=>{
217
+ const cwd=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-extension-drift-')));
218
+ t.after(()=>fs.rmSync(cwd,{recursive:true,force:true}));
219
+ const file=path.join(cwd,'new-boundary.mjs'),authored='if(2+2!==4)throw Error("boundary");';
220
+ fs.writeFileSync(file,authored);
221
+ const extension={plan:{...plan,testFiles:['new-boundary.mjs']},files:inventory(readReviewSourceFiles(cwd,['new-boundary.mjs']))};
222
+ const registered=JSON.stringify(extension);
223
+ assert.doesNotThrow(()=>verifyExtensionFiles(cwd,extension));
224
+ fs.writeFileSync(file,'if(2+2!==4)throw Error("tampered");');
225
+ assert.throws(()=>verifyExtensionFiles(cwd,extension),{code:'fix_test_extension_drift'});
226
+ assert.equal(JSON.stringify(extension),registered);
227
+ fs.writeFileSync(file,authored);assert.doesNotThrow(()=>verifyExtensionFiles(cwd,extension));
228
+ });
229
+
230
+ test('F56 M4 review baseline promotion rejects changed overlapping test bytes',t=>{
231
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-extension-baseline-')));
232
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
233
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
234
+ fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
235
+ fs.writeFileSync(path.join(cwd,'existing.mjs'),'// original reviewed test');
236
+ const options={root:cwd,specsRoot,identity:{repositoryId:'fixture',runId:'baseline',taskId:'T-FIX-overlap',attempt:2},requirements:['value.mjs']};
237
+ const original=captureReviewBaseline({...options,scope:['value.mjs']}),bytes=JSON.stringify(original);
238
+ assert.equal(Object.hasOwn(original.files.find(file=>file.path==='existing.mjs'),'contentBase64'),false);
239
+ const author=captureReviewBaseline({...options,scope:['existing.mjs']});
240
+ const promoted=extendRevisionReviewBaseline(original,author);
241
+ assert.deepEqual(promoted.files.find(file=>file.path==='existing.mjs'),author.files.find(file=>file.path==='existing.mjs'));
242
+ fs.writeFileSync(path.join(cwd,'existing.mjs'),'// hidden edit before test author');
243
+ const drifted=captureReviewBaseline({...options,scope:['existing.mjs']});
244
+ assert.throws(()=>extendRevisionReviewBaseline(original,drifted),{code:'fix_revision_source_mismatch'});
245
+ assert.equal(JSON.stringify(original),bytes);
246
+ });
@@ -0,0 +1,66 @@
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 {verifyVisualCarrier} from '../runtime/js/cm-fix/visual.mjs';
8
+
9
+ // 纯视觉修复的证据载体可以是截图也可以是录屏——cm-fix-host 的帮助里写着
10
+ // kind:screenshot|video。但 video 那一半从来没有测试走过,现有用例只造过截图,
11
+ // 连一个文件头常量都没出现过(docs/untested-branches.md 的 A 类第二条)。
12
+ //
13
+ // 这里要钉的不是「字符串能不能通过校验」,而是真正值钱的那条:载体的**声明**必须
14
+ // 和文件的**实际字节**对上。声明成录屏却塞张图,或者反过来,都必须被拒——否则
15
+ // 「视觉证据」就只是一个可以随便填的字段。
16
+ const magic={
17
+ png:Buffer.from([137,80,78,71,13,10,26,10]),
18
+ jpeg:Buffer.from([255,216,255,224]),
19
+ gif:Buffer.from('GIF89a'),
20
+ // MP4/MOV:前 4 字节是长度,紧跟 'ftyp'
21
+ mp4:Buffer.concat([Buffer.from([0,0,0,24]),Buffer.from('ftypisom')]),
22
+ webm:Buffer.from([26,69,223,163]),
23
+ };
24
+ function carrier(t,head,kind,{corruptHash=false}={}){
25
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'visual-carrier-')));
26
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
27
+ const file=path.join(root,'evidence.bin');
28
+ // 补足尾巴,确保不是靠长度而是靠文件头判定。
29
+ const bytes=Buffer.concat([head,Buffer.alloc(64,7)]);
30
+ fs.writeFileSync(file,bytes);
31
+ const sha256=corruptHash?'0'.repeat(64):createHash('sha256').update(bytes).digest('hex');
32
+ return {path:file,sha256,kind,description:'Synthetic carrier for the fixture'};
33
+ }
34
+
35
+ test('a video carrier is accepted for the container formats the contract names',t=>{
36
+ for(const format of ['mp4','webm']){
37
+ const value=carrier(t,magic[format],'video');
38
+ assert.deepEqual(verifyVisualCarrier(value),value,format);
39
+ }
40
+ });
41
+
42
+ test('a screenshot carrier still accepts the image formats, unchanged',t=>{
43
+ for(const format of ['png','jpeg','gif']){
44
+ const value=carrier(t,magic[format],'screenshot');
45
+ assert.deepEqual(verifyVisualCarrier(value),value,format);
46
+ }
47
+ });
48
+
49
+ test('the declared kind must match the actual bytes, in both directions',t=>{
50
+ // 这条才是这段校验存在的理由:声明不能脱离字节。
51
+ for(const [head,kind] of [['png','video'],['jpeg','video'],['mp4','screenshot'],['webm','screenshot']])
52
+ assert.throws(()=>verifyVisualCarrier(carrier(t,magic[head],kind)),
53
+ {code:'fix_visual_carrier_invalid'},`${head} 不该被当成 ${kind}`);
54
+ });
55
+
56
+ test('bytes that are neither an image nor a video are refused whichever kind is claimed',t=>{
57
+ const text=Buffer.from('this is just a text file pretending to be evidence');
58
+ for(const kind of ['screenshot','video'])
59
+ assert.throws(()=>verifyVisualCarrier(carrier(t,text,kind)),{code:'fix_visual_carrier_invalid'},kind);
60
+ });
61
+
62
+ test('a video carrier whose file no longer matches its hash is refused as changed',t=>{
63
+ // 录屏和截图走同一条哈希绑定,但之前只在截图上验过。
64
+ assert.throws(()=>verifyVisualCarrier(carrier(t,magic.mp4,'video',{corruptHash:true})),
65
+ {code:'fix_visual_carrier_changed'});
66
+ });
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import os from 'node:os';
6
+ import {createHash} from 'node:crypto';
6
7
  import {captureReviewBaseline} from '../runtime/js/cm-ai/review-package.mjs';
7
8
  import {createHostHandoff} from '../runtime/js/cm-ai/host-handoff.mjs';
8
9
  import {loadHandoff,implementationSha256} from './cm-task-gate.mjs';
@@ -90,6 +91,42 @@ test('an unreviewed handoff from a dead run is archived so the retry can publish
90
91
  assert.deepEqual(fs.readFileSync(path.join(archive,archived[0])),stale);
91
92
  }));
92
93
 
94
+ test('stale handoff archival preserves exact bytes and tolerates an existing crash-after-link archive',()=>collisionFixture(f=>{
95
+ createHostHandoff(f.build('first attempt'));
96
+ const stale=fs.readFileSync(f.handoffPath);
97
+ const staleStat=fs.statSync(f.handoffPath);
98
+ const name=path.basename(f.handoffPath);
99
+ const stamp=createHash('sha256').update(stale).digest('hex').slice(0,16);
100
+ const archive=path.join(f.reviews,'.superseded');
101
+ const target=path.join(archive,`${name}.${stamp}`);
102
+ const unrelated=path.join(f.reviews,'unrelated-r1.md');
103
+ fs.writeFileSync(unrelated,Buffer.from([0,255,10,42]));
104
+ const unrelatedBytes=fs.readFileSync(unrelated),unrelatedStat=fs.statSync(unrelated);
105
+ assert.equal(fs.existsSync(archive),false);
106
+
107
+ const retry=f.build('second attempt');
108
+ assert.equal(createHostHandoff(retry).status,'ready_for_review');
109
+ assert.equal(fs.statSync(archive).mode&0o777,0o700);
110
+ assert.deepEqual(fs.readdirSync(archive),[`${name}.${stamp}`]);
111
+ assert.deepEqual(fs.readFileSync(target),stale);
112
+ assert.equal(fs.statSync(target).ino,staleStat.ino);
113
+ const published=fs.readFileSync(f.handoffPath);
114
+ assert.notDeepEqual(published,stale);
115
+ assert.equal(fs.statSync(f.handoffPath).nlink,1);
116
+ assert.notEqual(fs.statSync(f.handoffPath).ino,staleStat.ino);
117
+ assert.equal(loadHandoff(f.handoffPath).implementation_sha256,implementationSha256(retry.root,['a.mjs']));
118
+
119
+ fs.unlinkSync(f.handoffPath);
120
+ fs.linkSync(target,f.handoffPath); // Crash after archive link, before source unlink.
121
+ assert.equal(createHostHandoff(retry).status,'ready_for_review');
122
+ assert.deepEqual(fs.readFileSync(f.handoffPath),published);
123
+ assert.deepEqual(fs.readdirSync(archive),[`${name}.${stamp}`]);
124
+ assert.deepEqual(fs.readdirSync(f.reviews).sort(),['.superseded',name,'unrelated-r1.md'].sort());
125
+ assert.deepEqual(fs.readFileSync(unrelated),unrelatedBytes);
126
+ assert.equal(fs.statSync(unrelated).ino,unrelatedStat.ino);
127
+ assert.equal(fs.statSync(unrelated).mtimeMs,unrelatedStat.mtimeMs);
128
+ }));
129
+
93
130
  test('a handoff the matching receipt names is never replaced',()=>collisionFixture(f=>{
94
131
  createHostHandoff(f.build('first attempt'));
95
132
  const reviewed=fs.readFileSync(f.handoffPath);
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+ // cm-idea 请求表(cm-idea-host.mjs handle();host-session.mjs operationNames):
3
+ // start / advance -> idea_interview;host.mjs interviewing 分支,人工问题或 PRD 草稿。
4
+ // finish -> idea_confirm_save;host.mjs confirming_save 分支,人工当前用户决定;宿主自己
5
+ // 以 exclusive 写法保存并回读,无驾驶员命令 runner。
6
+ // status/cancel/prepare_save: 无 host_request;host.mjs handle()。
7
+ // resume: 重放 pending.request,故按原 operation 和 checkpoint.stage 推导;
8
+ // 未知调用只接受原 callId/requestDigest/evidence 绑定的真实回执。
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import {fileURLToPath} from 'node:url';
12
+ import {inspectCmIdeaAdmission} from './cm-idea-entry.mjs';
13
+ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
14
+
15
+ const HOST=fileURLToPath(new URL('./cm-idea-host.mjs',import.meta.url));
16
+ const KNOWN=new Set(['start','advance','status','cancel','prepare_save','finish','resume']);
17
+ const nonempty=x=>typeof x==='string'&&x.trim().length>0;
18
+ const obj=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
19
+ function valid(ok,label){if(!ok)stop(2,`答案格式错误:${label}`);}
20
+ function main(){
21
+ if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
22
+ process.stdout.write('用法: cm-idea-drive.mjs --plan PLAN.json <operation>\nPLAN: project, sessionFile, mode:create|resume, text/maturity, answers;finish 需 saveRoot、filename 和当前用户的确认答案。宿主负责真实保存与回读。\n');return;
23
+ }
24
+ const {plan,operation,base}=loadPlanFile({name:'cm-idea-drive.mjs',known:KNOWN});
25
+ requireFields(plan,['project','sessionFile','mode']);
26
+ valid(['create','resume'].includes(plan.mode),'PLAN.mode');
27
+ const project=path.resolve(base,plan.project),skillDir=fileURLToPath(new URL('../skills/cm-idea',import.meta.url));
28
+ let admission;try{admission=inspectCmIdeaAdmission({skillDir});}catch(error){stop(2,`cm-idea 定义无效: ${error.code??error.message}`);}
29
+ valid(admission.workflowRoot===path.dirname(path.dirname(skillDir)),'cm-idea 定义路径');
30
+ valid(fs.existsSync(project)&&fs.realpathSync(project)===project&&fs.statSync(project).isDirectory(),'PLAN.project');
31
+ const sessionFile=path.resolve(base,plan.sessionFile),state=readJson(sessionFile,'恢复存档');
32
+ if(!fs.existsSync(path.dirname(sessionFile))||fs.realpathSync(path.dirname(sessionFile))!==path.dirname(sessionFile))
33
+ stop(2,`sessionFile 父目录不存在或不是规范路径: ${path.dirname(sessionFile)}`);
34
+ if(plan.mode==='create'&&state!==undefined)stop(2,`新会话存档已存在: ${sessionFile}`);
35
+ if(plan.mode==='resume'&&state===undefined)stop(2,`恢复存档不存在: ${sessionFile}`);
36
+ if(plan.mode==='resume')valid(state.workflow==='cm-idea'&&state.binding?.cwd===project
37
+ &&obj(state.checkpoint),'resume 存档与 project 不匹配');
38
+ if(state?.pending&&operation!=='resume')stop(2,'恢复存档存在 pending;必须用 resume 和原调用回执,不能重派');
39
+ const stage=state?.checkpoint?.stage??'ready';
40
+ if(operation==='status'&&plan.mode!=='resume')stop(2,'status 需要已有会话');
41
+ if(operation==='resume'){
42
+ if(plan.mode!=='resume')stop(2,'resume 需要已有存档');
43
+ if(state.pending?.writing)stop(2,'保存结果未知,不能自动恢复');
44
+ const call=state.pending?.call,resolution=plan.resolution??null;
45
+ if(call&&!Object.hasOwn(call,'result'))valid(obj(resolution)&&resolution.callId===call.callId
46
+ &&resolution.requestDigest===call.requestDigest&&nonempty(resolution.evidence)
47
+ &&Object.hasOwn(resolution,'result'),'resume 缺少原调用的真实回执');
48
+ else valid(resolution===null,'resume 不应提供新回执');
49
+ }
50
+ const actualOp=operation==='resume'?(state.pending?.request?.operation??'status'):operation;
51
+ if(actualOp==='start')valid(stage==='ready'&&nonempty(plan.text),'start 缺少 text 或阶段错误');
52
+ if(actualOp==='advance')valid(['awaiting_user','draft_ready'].includes(stage)&&nonempty(plan.text)
53
+ &&['L1','L2','L3'].includes(plan.maturity)
54
+ &&(stage!=='awaiting_user'||state?.checkpoint?.draft!==null||plan.maturity==='L1'),
55
+ 'advance 缺少 text/maturity 或阶段错误');
56
+ const saveRoot=plan.saveRoot?path.resolve(base,plan.saveRoot):null;
57
+ if(saveRoot!==null)valid(fs.existsSync(saveRoot)&&fs.realpathSync(saveRoot)===saveRoot
58
+ &&fs.statSync(saveRoot).isDirectory(),'saveRoot');
59
+ if(actualOp==='prepare_save')valid(stage==='draft_ready'&&saveRoot!==null,'prepare_save 缺少 saveRoot 或草稿');
60
+ if(actualOp==='finish'){
61
+ valid(stage==='draft_ready'&&nonempty(plan.filename)&&/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/.test(plan.filename),
62
+ 'finish 缺少草稿或安全的 filename');
63
+ const root=saveRoot??state?.checkpoint?.saveRoot;
64
+ valid(nonempty(root),'finish 缺少 saveRoot');
65
+ valid(state?.checkpoint?.saveRoot===null||state?.checkpoint?.saveRoot===root,'finish saveRoot 与已绑定会话不符');
66
+ const directory=path.join(root,'prd'),target=path.join(directory,plan.filename);
67
+ valid(!fs.existsSync(directory)||fs.lstatSync(directory).isDirectory()&&!fs.lstatSync(directory).isSymbolicLink(),
68
+ 'finish 保存目录越界');
69
+ valid(!fs.existsSync(target),'finish 目标文件已存在');
70
+ }
71
+ const kind=['start','advance'].includes(actualOp)?'idea_interview':actualOp==='finish'?'idea_confirm_save':null;
72
+ const answers=plan.answers?path.resolve(base,plan.answers):null;
73
+ const answer=preflightAnswers(kind?[kind]:[],key=>{
74
+ const file=path.join(answers??base,key==='idea_interview'?'interview.json':'confirm-save.json');
75
+ const value=readJson(file,key);
76
+ if(value===undefined)stop(2,`步骤 ${operation} 会反问 ${key},但答案文件不存在: ${file}`);
77
+ valid(obj(value),'idea answer');
78
+ if(key==='idea_confirm_save')valid(Object.keys(value).join(',')==='decision'
79
+ &&['approved','rejected'].includes(value.decision),'confirm-save.json');
80
+ else if(value.status==='question')valid(Object.keys(value).sort().join(',')==='productType,question,status'
81
+ &&nonempty(value.question)&&(value.productType===null||['A','B','C','D','E'].includes(value.productType)),
82
+ 'interview.json question');
83
+ else if(value.status==='draft')valid(Object.keys(value).sort().join(',')==='content,followup,maturity,productType,status'
84
+ &&nonempty(value.content)&&nonempty(value.followup)&&['A','B','C','D','E'].includes(value.productType)
85
+ &&value.maturity===(actualOp==='start'?'L1':plan.maturity),'interview.json draft');
86
+ else valid(value.status==='blocked'&&Object.keys(value).sort().join(',')==='reason,status'
87
+ &&nonempty(value.reason),'interview.json blocked');
88
+ return value;
89
+ });
90
+ driveHost({host:HOST,args:['serve','--skill-dir',skillDir,'--session-file',sessionFile,
91
+ ...(saveRoot?['--save-root',saveRoot]:[])],cwd:project,operation,
92
+ request:{...(['start','advance'].includes(operation)?{text:plan.text}:{}),
93
+ ...(operation==='advance'?{maturity:plan.maturity}:{}),
94
+ ...(operation==='finish'?{filename:plan.filename}:{}),
95
+ ...(operation==='prepare_save'?{saveRoot}:{}),
96
+ ...(operation==='resume'?{resolution:plan.resolution??null}:{})},answers:answer,
97
+ answerFor:row=>answer[row.kind]??null});
98
+ }
99
+ main();
@@ -0,0 +1,50 @@
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 {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+
9
+ const root=fileURLToPath(new URL('..',import.meta.url));
10
+ function fixture(t){
11
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-idea-drive-'))),project=path.join(dir,'project');
12
+ fs.mkdirSync(project);const answers=path.join(dir,'answers');fs.mkdirSync(answers);
13
+ fs.writeFileSync(path.join(answers,'interview.json'),JSON.stringify({status:'draft',content:'# Fixture PRD',
14
+ maturity:'L1',productType:'B',followup:'What should change?'}));
15
+ fs.writeFileSync(path.join(answers,'confirm-save.json'),JSON.stringify({decision:'approved'}));
16
+ const sessionFile=path.join(dir,'session.json');t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
17
+ const plan=(over={})=>({project,sessionFile,mode:fs.existsSync(sessionFile)?'resume':'create',
18
+ answers,text:'Fixture idea',saveRoot:project,filename:'fixture.md',...over});
19
+ const drive=(value,operation='start')=>{const file=path.join(dir,'plan.json');fs.writeFileSync(file,JSON.stringify(value));
20
+ return spawnSync(process.execPath,[path.join(root,'scripts/cm-idea-drive.mjs'),'--plan',file,operation],{encoding:'utf8'});};
21
+ return {dir,project,answers,sessionFile,plan,drive};
22
+ }
23
+ test('real idea host: interview draft, status, resumed save with host write and readback',t=>{
24
+ const f=fixture(t);let run=f.drive(f.plan());assert.equal(run.status,0,run.stderr);
25
+ assert.equal(JSON.parse(run.stdout).result.stage,'draft_ready');
26
+ const before=fs.readFileSync(f.sessionFile);
27
+ run=f.drive(f.plan({answers:undefined}),'status');assert.equal(run.status,0,run.stderr);
28
+ assert.equal(JSON.parse(run.stdout).result.stage,'draft_ready');assert.deepEqual(fs.readFileSync(f.sessionFile),before);
29
+ run=f.drive(f.plan(),'finish');assert.equal(run.status,0,run.stderr);
30
+ assert.equal(JSON.parse(run.stdout).result.stage,'saved');
31
+ assert.equal(fs.readFileSync(path.join(f.project,'prd','fixture.md'),'utf8'),'# Fixture PRD');
32
+ });
33
+ test('missing or malformed answer and out-of-scope filename refuse before session creation',t=>{
34
+ const f=fixture(t),file=path.join(f.answers,'interview.json');
35
+ fs.rmSync(file);let run=f.drive(f.plan());assert.equal(run.status,2);assert.match(run.stderr,/interview\.json/);
36
+ fs.writeFileSync(file,'{"status":"draft"}');run=f.drive(f.plan());assert.equal(run.status,2);assert.match(run.stderr,/答案格式错误/);
37
+ run=f.drive(f.plan());assert.equal(run.status,2);assert.equal(fs.existsSync(f.sessionFile),false);
38
+ fs.writeFileSync(file,JSON.stringify({status:'draft',content:'# Fixture',maturity:'L1',productType:'B',followup:'Next?'}));
39
+ assert.equal(f.drive(f.plan()).status,0);
40
+ run=f.drive(f.plan({filename:'../outside.md'}),'finish');assert.equal(run.status,2);assert.match(run.stderr,/filename/);
41
+ assert.equal(fs.existsSync(path.join(f.project,'prd')),false);
42
+ });
43
+ test('missing save decision and resume session binding refuse before launch',t=>{
44
+ const f=fixture(t);assert.equal(f.drive(f.plan()).status,0);
45
+ const before=fs.readFileSync(f.sessionFile);
46
+ fs.rmSync(path.join(f.answers,'confirm-save.json'));
47
+ let run=f.drive(f.plan(),'finish');assert.equal(run.status,2);assert.match(run.stderr,/confirm-save\.json/);
48
+ run=f.drive(f.plan({sessionFile:undefined}),'finish');assert.equal(run.status,2);assert.match(run.stderr,/sessionFile/);
49
+ assert.deepEqual(fs.readFileSync(f.sessionFile),before);
50
+ });