@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,191 @@
1
+ #!/usr/bin/env node
2
+ // cm-init 请求表(cm-init-host.mjs handle()/generateCmInitRules(),host-session.mjs operationNames):
3
+ // start -> init_analyze (host.mjs ready 分支)。
4
+ // advance @ ready/analysis_ready -> init_generate (host.mjs generating -> cm-init/draft-generation.mjs)。
5
+ // advance @ draft_generated -> init_verify (host.mjs verifying)。
6
+ // advance @ confirmation_required -> init_confirm (host.mjs confirming;只接受当前用户决定)。
7
+ // advance @ review_required -> init_review (host.mjs reviewing;人工独立审查结论)。
8
+ // advance @ reviewed_draft -> init_write (host.mjs writing;本驾驶员按审查过的 documents 真写磁盘并回报)。
9
+ // status/cancel/final_review_package/prepare_revision: 无 host_request;resume 重放原操作,
10
+ // 其请求种类由 pending.request.operation 与 checkpoint.stage 决定。host.mjs handle()。
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import {createHash} from 'node:crypto';
14
+ import {fileURLToPath} from 'node:url';
15
+ import {inspectCmInitAdmission} from './cm-init-entry.mjs';
16
+ import {validateCmInitSelection,cmInitRuleTargets} from '../runtime/js/cm-init/draft-generation.mjs';
17
+ import {inspectCmInitDraft,readCmInitSource} from '../runtime/js/cm-init/draft-inspection.mjs';
18
+ import {reviewResultForPaths} from '../runtime/js/cm-ai/review-runner.mjs';
19
+ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
20
+
21
+ const HOST=fileURLToPath(new URL('./cm-init-host.mjs',import.meta.url));
22
+ const KNOWN=new Set(['start','advance','status','cancel','final_review_package','prepare_revision','resume']);
23
+ const names={init_analyze:'analyze.json',init_generate:'generate.json',init_verify:'verify.json',
24
+ init_confirm:'confirm.json',init_review:'review.json'};
25
+ const categories=['commands','globs','file_references','constraint_preservation','rule_applicability'];
26
+ const obj=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
27
+ const nonempty=x=>typeof x==='string'&&x.trim().length>0;
28
+ function valid(ok,label){if(!ok)stop(2,`答案格式错误:${label}`);}
29
+ function sha(bytes){return createHash('sha256').update(bytes).digest('hex');}
30
+ function contentFile(root,local,label){
31
+ valid(nonempty(local)&&!path.isAbsolute(local)&&!local.split(/[\\/]/).includes('..'),label);
32
+ const target=path.join(root,local);
33
+ valid(fs.existsSync(target)&&fs.lstatSync(target).isFile()&&!fs.lstatSync(target).isSymbolicLink()
34
+ &&fs.realpathSync(target).startsWith(fs.realpathSync(root)+path.sep),`${label} 缺少安全的内容文件 ${target}`);
35
+ return fs.readFileSync(target,'utf8');
36
+ }
37
+ function stageKind(stage,operation){
38
+ if(operation==='start')return 'init_analyze';
39
+ if(operation!=='advance')return null;
40
+ return {ready:'init_generate',analysis_ready:'init_generate',draft_generated:'init_verify',
41
+ confirmation_required:'init_confirm',review_required:'init_review',reviewed_draft:'init_write'}[stage]??null;
42
+ }
43
+ function validate(kind,value,{project,selection,checkpoint,answers,hostContext}){
44
+ if(kind==='init_analyze'){
45
+ valid(obj(value)&&['analyzed','blocked'].includes(value.status),'analyze.json');
46
+ if(value.status==='blocked'){valid(Object.keys(value).sort().join(',')==='reason,status'&&nonempty(value.reason),'analyze.json');return value;}
47
+ valid(Object.keys(value).sort().join(',')==='evidence,noGitDecision,selection,status'&&nonempty(value.evidence),'analyze.json');
48
+ try{validateCmInitSelection(value.selection);}catch{valid(false,'analyze.json.selection');}
49
+ valid(value.selection.versionControl==='none'?value.noGitDecision==='explicit_user_refusal':value.noGitDecision===null,'analyze.json.noGitDecision');
50
+ return value;
51
+ }
52
+ if(kind==='init_generate'){
53
+ valid(obj(value)&&['generated','blocked'].includes(value.status),'generate.json');
54
+ if(value.status==='blocked'){valid(Object.keys(value).sort().join(',')==='reason,status'&&nonempty(value.reason),'generate.json');return {status:'blocked'};}
55
+ valid(Object.keys(value).sort().join(',')==='documents,status'&&Array.isArray(value.documents),'generate.json');
56
+ const targets=cmInitRuleTargets(selection,project);
57
+ valid(value.documents.length===targets.length&&new Set(value.documents.map(x=>x.path)).size===targets.length,'generate.json.documents');
58
+ const docs=value.documents.map(row=>{
59
+ valid(obj(row)&&Object.keys(row).sort().join(',')==='contentFile,path'&&targets.includes(row.path),`generate.json.documents ${row.path}`);
60
+ return {path:row.path,content:contentFile(answers,row.contentFile,`generate.json ${row.path}`)};
61
+ });
62
+ let inspection;try{inspection=inspectCmInitDraft({project,documents:docs,selection});}
63
+ catch(error){stop(2,`generate.json.documents 无效: ${error.code??error.message}`);}
64
+ valid(inspection.status==='structurally_checked',`generate.json.documents ${inspection.issues.map(x=>x.path+':'+x.code).join(', ')}`);
65
+ return {status:'generated',documents:docs};
66
+ }
67
+ if(kind==='init_verify'){
68
+ valid(obj(value)&&Object.keys(value).sort().join(',')==='checks,constraintChanges'
69
+ &&obj(value.checks)&&Object.keys(value.checks).sort().join(',')===categories.slice().sort().join(',')
70
+ &&Array.isArray(value.constraintChanges)&&new Set(value.constraintChanges).size===value.constraintChanges.length
71
+ &&value.constraintChanges.every(x=>checkpoint.result.inspection.existingChangeReviewRequired.includes(x)),'verify.json');
72
+ for(const item of Object.values(value.checks))valid(obj(item)&&Object.keys(item).sort().join(',')==='evidence,status'
73
+ &&['verified','not_applicable','unverified','failed'].includes(item.status)&&nonempty(item.evidence),'verify.json.checks');
74
+ return value;
75
+ }
76
+ if(kind==='init_confirm'){
77
+ valid(obj(value)&&Object.keys(value).join(',')==='decision'&&['approved','rejected'].includes(value.decision),'confirm.json');return value;
78
+ }
79
+ if(kind==='init_review'){
80
+ valid(obj(value)&&Object.keys(value).sort().join(',')==='at,contextId,independent,result,reviewer'
81
+ &&['codex-subagent','codex-cli','claude-cli'].includes(value.reviewer)
82
+ &&nonempty(value.contextId)&&value.contextId!==hostContext
83
+ &&!checkpoint.authorContexts.includes(value.contextId)&&value.independent===true
84
+ &&nonempty(value.at)&&new Date(value.at).toISOString()===value.at,'review.json');
85
+ const result=value.result,paths=checkpoint.result.documents.map(x=>x.path).sort();
86
+ valid(obj(result)&&Object.keys(result).sort().join(',')==='findings,summary,verdict','review.json.result');
87
+ try{reviewResultForPaths({...result,packageDigest:'0'.repeat(64),examinedPaths:paths},
88
+ {packageDigest:'0'.repeat(64)},paths);}catch(error){valid(false,`review.json.result ${error.code??error.message}`);}
89
+ return value;
90
+ }
91
+ return value;
92
+ }
93
+ function main(){
94
+ if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
95
+ process.stdout.write('用法: cm-init-drive.mjs --plan PLAN.json <operation>\nPLAN: project, sessionFile, mode:create|resume, hostContext, resume 时 originalHostContext;advance 首轮填 selection;answers 存人工分析、草稿、核验、决定和审查。allowWrite:true 时按审查草稿实际写文件。\n');return;
96
+ }
97
+ const {plan,operation,base}=loadPlanFile({name:'cm-init-drive.mjs',known:KNOWN});
98
+ requireFields(plan,['project','sessionFile','mode','hostContext']);
99
+ valid(['create','resume'].includes(plan.mode)&&nonempty(plan.hostContext),'PLAN.mode/hostContext');
100
+ const project=path.resolve(base,plan.project),skillDir=path.join(path.dirname(HOST),'..','skills','cm-init');
101
+ let admission;try{admission=inspectCmInitAdmission({project,skillDir});}catch(error){stop(2,`cm-init 项目或定义无效: ${error.code??error.message}`);}
102
+ if(admission.status!=='ready')stop(2,'cm-init 项目缺少已有内容');
103
+ const sessionFile=path.resolve(base,plan.sessionFile),state=readJson(sessionFile,'恢复存档');
104
+ if(!fs.existsSync(path.dirname(sessionFile))||fs.realpathSync(path.dirname(sessionFile))!==path.dirname(sessionFile))
105
+ stop(2,`sessionFile 父目录不存在或不是规范路径: ${path.dirname(sessionFile)}`);
106
+ if(plan.mode==='create'&&state!==undefined)stop(2,`新会话存档已存在: ${sessionFile}`);
107
+ if(plan.mode==='resume'&&state===undefined)stop(2,`恢复存档不存在: ${sessionFile}`);
108
+ if(plan.mode==='resume'){
109
+ valid(nonempty(plan.originalHostContext),'resume 缺少 originalHostContext');
110
+ valid(state.workflow==='cm-init'&&obj(state.checkpoint)&&state.checkpoint.authorContextId===plan.originalHostContext,
111
+ 'resume 存档与 originalHostContext 不匹配');
112
+ }
113
+ const checkpoint=state?.checkpoint??{stage:'ready',authorContexts:[plan.hostContext]},stage=checkpoint.stage;
114
+ if(operation==='start'&&stage!=='ready')stop(2,`start 只能从 ready 开始,当前 ${stage}`);
115
+ if(operation==='advance'&&!['ready','analysis_ready','draft_generated','confirmation_required','review_required','reviewed_draft'].includes(stage))
116
+ stop(2,`advance 当前阶段不能继续: ${stage}`);
117
+ if(['status','final_review_package'].includes(operation)&&plan.mode!=='resume')stop(2,`${operation} 需要已有会话`);
118
+ if(state?.pending&&operation!=='resume')stop(2,'恢复存档存在 pending;必须用 resume 和原调用回执,不能重派');
119
+ if(operation==='resume'){
120
+ if(plan.mode!=='resume')stop(2,'resume 需要已有存档');
121
+ if(state.pending?.writing)stop(2,'写入结果未知,不能自动恢复');
122
+ const call=state.pending?.call,resolution=plan.resolution??null;
123
+ if(call&&!Object.hasOwn(call,'result')){
124
+ valid(obj(resolution)&&resolution.callId===call.callId&&resolution.requestDigest===call.requestDigest
125
+ &&nonempty(resolution.evidence)&&Object.hasOwn(resolution,'result'),'resume 缺少原调用的真实回执');
126
+ }else valid(resolution===null,'resume 不应提供新回执');
127
+ }
128
+ let selection=checkpoint.selection;
129
+ if(stage==='ready'&&operation==='advance'){
130
+ try{selection=validateCmInitSelection(plan.selection);}catch{stop(2,'advance 缺少有效 PLAN.selection');}
131
+ }
132
+ const actualOp=operation==='resume'?(state.pending?.request?.operation??'status'):operation;
133
+ const kind=stageKind(stage,actualOp);
134
+ if(operation==='prepare_revision'){
135
+ valid(['verification_blocked','review_changes_requested','review_blocked'].includes(stage),'prepare_revision 阶段');
136
+ valid(Array.isArray(plan.documents)&&plan.documents.length===checkpoint.result?.documents?.length
137
+ &&new Set(plan.documents.map(x=>x?.path)).size===plan.documents.length
138
+ &&plan.documents.every(x=>checkpoint.result.documents.some(y=>y.path===x?.path)),
139
+ 'prepare_revision 文档范围越界');
140
+ let inspected;try{inspected=inspectCmInitDraft({project,documents:plan.documents,selection});}
141
+ catch(error){stop(2,`prepare_revision 文档格式错误: ${error.code??error.message}`);}
142
+ valid(inspected.status==='structurally_checked','prepare_revision 草稿无效');
143
+ }
144
+ if(kind==='init_write'){
145
+ if(plan.allowWrite!==true)stop(2,'步骤 advance 会反问 init_write,但 PLAN.allowWrite 缺少真实写入授权与 runner');
146
+ valid(checkpoint.result?.inspection?.status==='structurally_checked','init_write 审查草稿缺失');
147
+ for(const change of checkpoint.result.inspection.changes){
148
+ const before=readCmInitSource(project,change.path);
149
+ valid((before===null?null:sha(before))===change.beforeSha256,`init_write 原文件已变化: ${change.path}`);
150
+ }
151
+ }
152
+ const answers=plan.answers?path.resolve(base,plan.answers):null;
153
+ const answer=preflightAnswers(kind&&names[kind]?[kind]:[],key=>{
154
+ const file=path.join(answers??base,names[key]),value=readJson(file,key);
155
+ if(value===undefined)stop(2,`步骤 ${operation} 会反问 ${key},但答案文件不存在: ${file}`);
156
+ return validate(key,value,{project,selection,checkpoint,answers,hostContext:plan.hostContext});
157
+ });
158
+ driveHost({host:HOST,args:['serve','--skill-dir',skillDir,'--project',project,'--host-context',plan.hostContext,
159
+ ...(plan.allowWrite===true?['--allow-write']:[]),'--session-file',sessionFile],cwd:project,operation,
160
+ request:{...(operation==='advance'&&stage==='ready'?{selection}:{}),
161
+ ...(operation==='prepare_revision'?{documents:plan.documents}:{}),
162
+ ...(operation==='resume'?{resolution:plan.resolution??null}:{})},answers:answer,
163
+ answerFor:row=>{
164
+ if(row.kind==='init_review'){
165
+ const value=answer.init_review,pkg=row.payload.package;
166
+ return {...value,result:{...value.result,packageDigest:pkg.packageDigest,examinedPaths:pkg.examinedPaths}};
167
+ }
168
+ if(row.kind==='init_write'){
169
+ if(kind!=='init_write')return null;
170
+ const expected=checkpoint.result.inspection.changes.filter(x=>x.action!=='unchanged');
171
+ if(JSON.stringify(row.payload.expected)!==JSON.stringify(expected))return null;
172
+ const docs=checkpoint.result.documents.filter(x=>expected.some(y=>y.path===x.path));
173
+ if(JSON.stringify(row.payload.documents)!==JSON.stringify(docs))return null;
174
+ for(const change of expected){
175
+ const before=readCmInitSource(project,change.path);
176
+ if((before===null?null:sha(before))!==change.beforeSha256)return {status:'blocked'};
177
+ const document=docs.find(x=>x.path===change.path),target=path.join(project,change.path);
178
+ fs.mkdirSync(path.dirname(target),{recursive:true});
179
+ if(fs.realpathSync(path.dirname(target))!==path.dirname(target))return {status:'blocked'};
180
+ const flags=before===null?fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|fs.constants.O_NOFOLLOW
181
+ :fs.constants.O_WRONLY|fs.constants.O_TRUNC|fs.constants.O_NOFOLLOW;
182
+ const fd=fs.openSync(target,flags,0o600);
183
+ try{fs.writeFileSync(fd,document.content);}finally{fs.closeSync(fd);}
184
+ stderr(`实际写入 ${change.path}`);
185
+ }
186
+ return {status:'written'};
187
+ }
188
+ return answer[row.kind]??null;
189
+ }});
190
+ }
191
+ main();
@@ -0,0 +1,59 @@
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
+ const selection={versionControl:'none',modules:[],analysis:'Fixture project'};
11
+ const targets=['AGENTS.md','.claude/CLAUDE.md','.claude/rules/coding-style.md',
12
+ '.claude/rules/testing.md','.claude/rules/security.md'];
13
+ function fixture(t){
14
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-init-drive-'))),project=path.join(dir,'project');
15
+ fs.mkdirSync(project);fs.writeFileSync(path.join(project,'AGENTS.md'),'Original rule\n');
16
+ const answers=path.join(dir,'answers');fs.mkdirSync(answers);
17
+ const documents=targets.map((file,i)=>{const contentFile=`draft-${i}.md`;
18
+ fs.writeFileSync(path.join(answers,contentFile),'# Fixture\nPreserve original rule\n');return {path:file,contentFile};});
19
+ fs.writeFileSync(path.join(answers,'generate.json'),JSON.stringify({status:'generated',documents}));
20
+ fs.writeFileSync(path.join(answers,'verify.json'),JSON.stringify({checks:Object.fromEntries(
21
+ ['commands','globs','file_references','constraint_preservation','rule_applicability'].map(x=>[x,{status:'verified',evidence:'Fixture review'}])),constraintChanges:[]}));
22
+ fs.writeFileSync(path.join(answers,'review.json'),JSON.stringify({reviewer:'codex-subagent',contextId:'independent-fixture',
23
+ independent:true,at:new Date().toISOString(),result:{verdict:'approved',findings:[],summary:'Fixture verdict'}}));
24
+ const sessionFile=path.join(dir,'session.json');t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
25
+ const plan=(over={})=>({project,sessionFile,mode:fs.existsSync(sessionFile)?'resume':'create',
26
+ hostContext:'fixture-author',originalHostContext:fs.existsSync(sessionFile)?'fixture-author':undefined,
27
+ answers,selection,...over});
28
+ const drive=(value,operation='advance')=>{const file=path.join(dir,'plan.json');fs.writeFileSync(file,JSON.stringify(value));
29
+ return spawnSync(process.execPath,[path.join(root,'scripts/cm-init-drive.mjs'),'--plan',file,operation],{encoding:'utf8'});};
30
+ return {dir,project,answers,sessionFile,documents,plan,drive};
31
+ }
32
+ test('real init host: generated draft, resumed verification, review and actual scoped write',t=>{
33
+ const f=fixture(t);let run=f.drive(f.plan());assert.equal(run.status,0,run.stderr);
34
+ assert.equal(JSON.parse(run.stdout).result.status,'draft_generated');
35
+ run=f.drive(f.plan());assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.stage,'review_required');
36
+ const status=f.drive(f.plan({answers:undefined}),'status');assert.equal(status.status,0,status.stderr);
37
+ assert.equal(JSON.parse(status.stdout).result.stage,'review_required');
38
+ run=f.drive(f.plan());assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.stage,'reviewed_draft');
39
+ run=f.drive(f.plan({allowWrite:true}));assert.equal(run.status,0,run.stderr);
40
+ assert.equal(JSON.parse(run.stdout).result.stage,'rules_written');
41
+ assert.equal(fs.readFileSync(path.join(f.project,'AGENTS.md'),'utf8'),'# Fixture\nPreserve original rule\n');
42
+ });
43
+ test('missing or malformed generated answer and out-of-scope edit refuse before session creation',t=>{
44
+ const f=fixture(t),file=path.join(f.answers,'generate.json'),original=fs.readFileSync(file);
45
+ fs.rmSync(file);let run=f.drive(f.plan());assert.equal(run.status,2);assert.match(run.stderr,/generate\.json/);
46
+ fs.writeFileSync(file,'{}');run=f.drive(f.plan());assert.equal(run.status,2);assert.match(run.stderr,/答案格式错误/);
47
+ const altered=JSON.parse(original);altered.documents[0].path='outside.md';fs.writeFileSync(file,JSON.stringify(altered));
48
+ run=f.drive(f.plan());assert.equal(run.status,2);assert.match(run.stderr,/generate\.json/);
49
+ assert.equal(fs.existsSync(f.sessionFile),false);
50
+ });
51
+ test('resume binding and missing write runner refuse before host launch',t=>{
52
+ const f=fixture(t);assert.equal(f.drive(f.plan()).status,0);
53
+ let run=f.drive(f.plan({originalHostContext:undefined}));assert.equal(run.status,2);assert.match(run.stderr,/originalHostContext/);
54
+ assert.equal(f.drive(f.plan()).status,0);assert.equal(f.drive(f.plan()).status,0);
55
+ const before=fs.readFileSync(f.sessionFile);
56
+ fs.writeFileSync(path.join(f.answers,'init-write.json'),JSON.stringify({status:'written'}));
57
+ run=f.drive(f.plan());assert.equal(run.status,2);assert.match(run.stderr,/init_write/);
58
+ assert.deepEqual(fs.readFileSync(f.sessionFile),before);
59
+ });
@@ -336,6 +336,15 @@ function validateQaAbandonment(state,event){
336
336
 
337
337
  function validateQaSupersession(state,event){
338
338
  const {start,complete}=state;
339
+ if(event.reason==='qa_configuration_revision'){
340
+ if(state.active||state.superseded||!start||!complete||start.attempt>=3
341
+ ||event.workflow!=='cm-ai'||event.node!=='N6'||event.previous_test_run_id!==start.operation_id
342
+ ||!['PASS','FAIL','BLOCKED'].includes(complete.result)||!/^[a-f0-9]{64}$/.test(event.qa_revision_digest??'')
343
+ ||!['repository_id','run_id','feature','task','package_digest','qa_decision_id','operation_id','attempt','mode','case_count']
344
+ .every(key=>event[key]!==undefined&&event[key]===start[key]&&event[key]===complete[key]))
345
+ throw new UsageError('QA configuration supersession requires the matching completed invocation and revision digest');
346
+ return;
347
+ }
339
348
  if(state.active||state.superseded||!start||!complete||complete.result!=='BLOCKED'||complete.failed!==0
340
349
  ||complete.blocked<=0||start.attempt>=3||event.workflow!=='cm-ai'||event.node!=='N6'
341
350
  ||event.reason!=='host_evidence_problem'||event.previous_test_run_id!==start.operation_id