@aibyzero/cm-workflow 0.16.2 → 0.16.4

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 (155) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +147 -0
  4. package/README.md +44 -3
  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 +100 -0
  9. package/docs/untested-branches.md +24 -18
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/claude-review-stream.mjs +18 -0
  12. package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +7 -1
  14. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
  15. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
  16. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
  17. package/runtime/js/cm-ai/drive-core.mjs +68 -0
  18. package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
  19. package/runtime/js/cm-ai/effect-contract.mjs +4 -3
  20. package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
  22. package/runtime/js/cm-ai/host-handoff.mjs +9 -14
  23. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
  24. package/runtime/js/cm-ai/host-session.mjs +10 -3
  25. package/runtime/js/cm-ai/host.mjs +1 -1
  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-ai/worker-claude-developer.mjs +16 -7
  32. package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
  33. package/runtime/js/cm-fix/cause-package.mjs +21 -0
  34. package/runtime/js/cm-fix/dossier.mjs +40 -1
  35. package/runtime/js/cm-fix/execution.mjs +360 -83
  36. package/runtime/js/cm-fix/host.mjs +7 -3
  37. package/runtime/js/cm-fix/layout.mjs +14 -6
  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-prd/accepted-design.mjs +28 -9
  47. package/runtime/js/cm-prd/analysis.mjs +68 -16
  48. package/runtime/js/cm-prd/change.mjs +21 -1
  49. package/runtime/js/cm-prd/draft-save.mjs +96 -2
  50. package/runtime/js/cm-prd/failed-correction.mjs +51 -0
  51. package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
  52. package/runtime/js/cm-prd/review-correction.mjs +3 -0
  53. package/runtime/js/cm-prd/review-disposition.mjs +33 -15
  54. package/runtime/js/cm-prd/review-findings.mjs +2 -2
  55. package/runtime/js/cm-prd/review-host.mjs +2 -0
  56. package/runtime/js/cm-prd/review-preparation.mjs +28 -1
  57. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  58. package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
  59. package/runtime/js/cm-prd/session.mjs +5 -5
  60. package/runtime/js/cm-prd/split-design.mjs +67 -0
  61. package/runtime/js/cm-prd/summary.mjs +57 -10
  62. package/runtime/js/cm-refactor/workflow.mjs +100 -19
  63. package/runtime/js/specs-status.mjs +6 -2
  64. package/scripts/cm-ai-admission.mjs +2 -0
  65. package/scripts/cm-ai-batch-drive.mjs +251 -0
  66. package/scripts/cm-ai-batch-drive.test.mjs +159 -0
  67. package/scripts/cm-ai-batch-host.mjs +13 -5
  68. package/scripts/cm-ai-batch-host.test.mjs +25 -0
  69. package/scripts/cm-ai-contracts.test.mjs +30 -0
  70. package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
  71. package/scripts/cm-ai-drive.mjs +335 -0
  72. package/scripts/cm-ai-drive.test.mjs +258 -0
  73. package/scripts/cm-ai-fix-integration.test.mjs +1 -1
  74. package/scripts/cm-ai-host.mjs +48 -20
  75. package/scripts/cm-ai-host.test.mjs +79 -0
  76. package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
  77. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
  78. package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
  79. package/scripts/cm-ai-review-timeout.test.mjs +30 -0
  80. package/scripts/cm-ai-run.mjs +59 -11
  81. package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
  82. package/scripts/cm-ai-session-chain.test.mjs +261 -0
  83. package/scripts/cm-ai-supersede.test.mjs +320 -0
  84. package/scripts/cm-check-drive.mjs +94 -0
  85. package/scripts/cm-check-drive.test.mjs +78 -0
  86. package/scripts/cm-check-entry.mjs +13 -2
  87. package/scripts/cm-check-host.mjs +2 -2
  88. package/scripts/cm-check-host.test.mjs +103 -0
  89. package/scripts/cm-check-runtime.sh +15 -6
  90. package/scripts/cm-claude-developer-worker.test.mjs +40 -1
  91. package/scripts/cm-claude-probe.test.mjs +117 -2
  92. package/scripts/cm-claude-review-stream.test.mjs +43 -0
  93. package/scripts/cm-fix-abandon.test.mjs +383 -0
  94. package/scripts/cm-fix-cause-package.test.mjs +31 -1
  95. package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
  96. package/scripts/cm-fix-drive.mjs +168 -0
  97. package/scripts/cm-fix-drive.test.mjs +117 -0
  98. package/scripts/cm-fix-escalation.test.mjs +214 -0
  99. package/scripts/cm-fix-execution.test.mjs +26 -0
  100. package/scripts/cm-fix-host.mjs +4 -2
  101. package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
  102. package/scripts/cm-fix-qa-source.test.mjs +3 -3
  103. package/scripts/cm-fix-session-chain.test.mjs +244 -0
  104. package/scripts/cm-fix-test-extension.test.mjs +246 -0
  105. package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
  106. package/scripts/cm-host-handoff.test.mjs +37 -0
  107. package/scripts/cm-idea-drive.mjs +99 -0
  108. package/scripts/cm-idea-drive.test.mjs +50 -0
  109. package/scripts/cm-init-drive.mjs +191 -0
  110. package/scripts/cm-init-drive.test.mjs +59 -0
  111. package/scripts/cm-log-event.mjs +9 -0
  112. package/scripts/cm-prd-completion.test.mjs +30 -2
  113. package/scripts/cm-prd-design-phase.test.mjs +355 -15
  114. package/scripts/cm-prd-drive.mjs +314 -0
  115. package/scripts/cm-prd-drive.test.mjs +164 -0
  116. package/scripts/cm-prd-host.mjs +46 -17
  117. package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
  118. package/scripts/cm-prd-review-disposition.test.mjs +133 -7
  119. package/scripts/cm-prd-review-gate.mjs +23 -4
  120. package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
  121. package/scripts/cm-prd-summary.test.mjs +79 -4
  122. package/scripts/cm-refactor-drive.mjs +237 -0
  123. package/scripts/cm-refactor-drive.test.mjs +77 -0
  124. package/scripts/cm-refactor-gaps.test.mjs +276 -0
  125. package/scripts/cm-refactor-host.test.mjs +1 -48
  126. package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
  127. package/scripts/cm-specs-status.test.mjs +19 -0
  128. package/scripts/cm-test-drive.mjs +132 -0
  129. package/scripts/cm-test-drive.test.mjs +91 -0
  130. package/scripts/cm-test-session.test.mjs +117 -0
  131. package/scripts/correction-check.test.mjs +38 -0
  132. package/scripts/fixtures/claude-model-marker.mjs +6 -0
  133. package/scripts/fixtures/claude-review-process.mjs +7 -0
  134. package/scripts/fixtures/cm-refactor.mjs +56 -0
  135. package/scripts/test-shell-compat.sh +67 -0
  136. package/skills/cm-ai/SKILL.md +1 -1
  137. package/skills/cm-ai/references/N4-review.md +2 -0
  138. package/skills/cm-ai/references/N8-finish.md +1 -0
  139. package/skills/cm-ai/references/js-host.md +85 -3
  140. package/skills/cm-check/SKILL.md +6 -1
  141. package/skills/cm-check/references/js-host.md +4 -2
  142. package/skills/cm-fix/SKILL.md +11 -4
  143. package/skills/cm-fix/references/js-host.md +67 -2
  144. package/skills/cm-fix/references/test-extension.md +57 -0
  145. package/skills/cm-idea/references/js-host.md +2 -0
  146. package/skills/cm-init/references/js-host.md +2 -0
  147. package/skills/cm-prd/SKILL.md +8 -8
  148. package/skills/cm-prd/references/js-change-recovery.md +71 -0
  149. package/skills/cm-prd/references/js-host.md +64 -2
  150. package/skills/cm-prd/references/spec-self-check.md +14 -2
  151. package/skills/cm-refactor/SKILL.md +5 -0
  152. package/skills/cm-refactor/references/js-batch.md +3 -1
  153. package/skills/cm-refactor/references/js-host.md +49 -0
  154. package/skills/cm-test/references/js-host.md +5 -0
  155. package/skills/cm-test/references/unit-coverage.md +2 -2
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env node
2
+ // cm-fix 的驾驶员:替你开宿主、发一条指令、代答宿主的反问、把结果打出来、关进程。
3
+ //
4
+ // 为什么需要它:cm-fix-host.mjs 是个服务端,靠标准输入一行一行喂 JSON。而 AI 助手每次
5
+ // 只能执行一条命令,抱不住一个长活进程,于是每个用它的人——包括模型自己——都得先
6
+ // 临时手搓一个中间人。一次真实实跑里就是这么干的,两次配错(走查模块对不上、任务编号
7
+ // 重名)根源都在这儿:没有现成的护栏。
8
+ //
9
+ // 它只是方便,不是放权:能做什么仍由宿主的 --allow-* 开关说了算;它绝不替你编诊断、
10
+ // 测试或修复内容,缺哪份答案就停在发指令之前。
11
+ //
12
+ // node scripts/cm-fix-drive.mjs --plan PLAN.json <operation>
13
+ //
14
+ // PLAN.json(路径都相对于 PLAN.json 所在目录):
15
+ // {
16
+ // "config": "fix-config.json", 宿主配置,格式见 cm-fix-host.mjs --help
17
+ // "cwd": "/abs/project", 代码根,须等于 config.reproduction.cwd
18
+ // "mode": "create" | "resume",
19
+ // "hostContext": "<当前真实会话 ID>",
20
+ // "originalHostContext": "<旧会话 ID>", 只在换会话恢复时填
21
+ // "runtime": "codex" | "claude", 缺省 codex
22
+ // "reviewConfig": "review.json", 可选
23
+ // "permissions": ["--allow-red-test", ...], 原样传给宿主,不另造一套词
24
+ // "answers": "answers", 答案目录;abandon_step 可省略
25
+ // "reason": "旧本地步骤结果丢失" abandon_step 必填,并需 --allow-abandon
26
+ // }
27
+ //
28
+ // answers/ 里按反问种类放文件,一种一个:
29
+ // learning.json {status, summary} 恢复时若存档里已有记录会自动复用
30
+ // diagnosis.json 诊断结论对象
31
+ // retrospective.json {status, candidates, reason}
32
+ // test-edits.json {"仓库内路径": "本目录下的内容文件"}
33
+ // repair-edits.json 同上
34
+ import fs from 'node:fs';
35
+ import path from 'node:path';
36
+ import {fileURLToPath} from 'node:url';
37
+ import {fixEvidenceNames} from '../runtime/js/cm-fix/layout.mjs';
38
+ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
39
+
40
+ const here=path.dirname(fileURLToPath(import.meta.url));
41
+ const HOST=path.join(here,'cm-fix-host.mjs');
42
+
43
+ // 每个步骤会反问什么。unknown 默认不重派;仅显式授权的本地 abandon_step 可重做。
44
+ // 答案必须在发原步骤前查齐,缺一个都不发——这是驾驶员最要紧的一条护栏。
45
+ // design_change_required uses red_test (or test_author_required/author_tests).
46
+ // escalation_required uses publish_dossier/finish: neither requests answers.
47
+ const ASKS={
48
+ advance:['learning','diagnosis'],
49
+ author_tests:['learning','test-edits'],
50
+ repair:['learning','repair-edits'],
51
+ retrospective:['learning','retrospective'],
52
+ red_test:['learning'],baseline:['learning'],regression:['learning'],
53
+ post_review_regression:['learning'],prepare_revision:['learning'],
54
+ };
55
+ const READ_ONLY=new Set(['status','final_review_package','completion_evidence','cause_review_package']);
56
+ const KNOWN=new Set([...Object.keys(ASKS),...READ_ONLY,'cancel','handoff','publish_review','check_n5',
57
+ 'publish_dossier','learning_writeback','walkthrough','finish','final_review','cause_review',
58
+ 'recover_final_review','abandon_step','resume','revision_test_check']);
59
+
60
+ function loadPlan(){
61
+ const {operation,plan,base}=loadPlanFile({name:'cm-fix-drive.mjs',known:KNOWN});
62
+ requireFields(plan,['config','cwd','mode','hostContext','permissions',...(operation==='abandon_step'?[]:['answers'])]);
63
+ if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
64
+ if(!Array.isArray(plan.permissions)||plan.permissions.some(p=>!/^--allow-[a-z-]+$/.test(p)))
65
+ stop(2,'permissions 必须是 --allow-xxx 形式的数组,原样传给宿主');
66
+ if(operation==='abandon_step'&&(!plan.permissions.includes('--allow-abandon')||typeof plan.reason!=='string'
67
+ ||!plan.reason.trim().length||Buffer.byteLength(plan.reason,'utf8')>1000||/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))
68
+ stop(2,'abandon_step 需要 PLAN.reason(单行,最多 1000 字节)和 --allow-abandon');
69
+ if(plan.originalHostContext&&plan.mode!=='resume')stop(2,'originalHostContext 只在 resume 时有意义');
70
+ const resolve=p=>path.resolve(base,p);
71
+ return {operation,plan,paths:{config:resolve(plan.config),answers:plan.answers?resolve(plan.answers):null,
72
+ review:plan.reviewConfig?resolve(plan.reviewConfig):null}};
73
+ }
74
+
75
+ // 恢复时宿主要求学习记录和上次一字不差;从存档里读上次记的那份,省掉一个必踩的坑。
76
+ // 只读,且宿主仍会自己校验摘要——读错了也只是被宿主拒绝,不会放行。
77
+ function recordedLearning(config,cwd){
78
+ const archive=config.specsRoot??path.join(cwd,'docs','fixes');
79
+ const state=path.join(archive,'.reviews','.execution',config.identity.runId,'state.json');
80
+ const stored=readJson(state,'存档');
81
+ const record=stored?.records?.find(row=>row.kind==='result'&&/^fix-learning-/.test(row.id));
82
+ return record?.payload?.application??null;
83
+ }
84
+
85
+ function preflight({operation,plan,paths}){
86
+ const config=readJson(paths.config,'宿主配置');
87
+ if(config===undefined)stop(2,`宿主配置不存在: ${paths.config}`);
88
+ if(path.resolve(plan.cwd)!==path.resolve(config.reproduction?.cwd??''))
89
+ stop(2,`PLAN.cwd 与 config.reproduction.cwd 不一致`);
90
+ const need=(kind,file)=>{const value=readJson(path.join(paths.answers,file),kind);
91
+ if(value===undefined)stop(2,`步骤 ${operation} 会反问「${kind}」,但答案文件不存在: ${path.join(paths.answers,file)}\n 先把它写好,再来调驾驱员。缺答案而硬发指令,会把这次运行做死。`);
92
+ return value;};
93
+ const answers=preflightAnswers(ASKS[operation]??[],kind=>{
94
+ if(kind==='learning'){
95
+ const recorded=plan.mode==='resume'?recordedLearning(config,plan.cwd):null;
96
+ if(recorded){stderr(`恢复:复用存档里已记的学习记录(${recorded.status})`);return recorded;}
97
+ return need('学习记录','learning.json');
98
+ }
99
+ if(kind==='diagnosis')return need('诊断','diagnosis.json');
100
+ if(kind==='retrospective')return need('复盘','retrospective.json');
101
+ const map=need(kind==='test-edits'?'测试内容':'修复内容',`${kind}.json`);
102
+ for(const [target,local] of Object.entries(map)){
103
+ const file=path.join(paths.answers,local);
104
+ if(!fs.existsSync(file))stop(2,`${kind}.json 把 ${target} 指向 ${file},但那个文件不存在`);
105
+ }
106
+ return map;
107
+ });
108
+ if(plan.mode==='create'){
109
+ // 建运行前的体检:宿主也会查,但这里把「是哪个文件」提前说清。
110
+ const cwd=path.resolve(plan.cwd);
111
+ for(const file of [...(config.testAuthor?.requirements??[]),...(config.repair?.requirements??[]),
112
+ ...(config.redTest?.testFiles??[]),...(config.baseline?.testFiles??[])])
113
+ if(!fs.existsSync(path.join(cwd,file)))stderr(`注意:配置引用的文件不存在 ${file}`);
114
+ const archive=config.specsRoot??path.join(cwd,'docs','fixes');
115
+ for(const name of fixEvidenceNames(config.identity,config)){
116
+ if(!fs.existsSync(path.join(archive,'.reviews',name)))continue;
117
+ if(/-(?:cause-)?r\d+\.md$/.test(name))stderr(`会被拦:${name} 是审查结论,这个任务编号已占住,换一个`);
118
+ else stderr(`注意:${name} 已存在,宿主会把它归档到 .superseded/ 再继续`);
119
+ }
120
+ if(config.protectSpecs){
121
+ const commands=[config.reproduction?.command,config.redTest?.command,...(config.baseline?.commands??[]).map(c=>c.command),
122
+ ...(config.walkthrough?.flows??[]).map(f=>f.command)].filter(Array.isArray);
123
+ for(const command of commands)
124
+ if(command.some(arg=>/(^|\/)(tsx|vitest)$/.test(String(arg))||/\btsx\b|\bvitest\b/.test(String(arg))))
125
+ stderr(`注意:受保护模式的沙箱跑不了 tsx / vitest 这类要开本地 socket 的命令:${command.join(' ')}\n 见 skills/cm-fix/references/js-host.md「同仓 specs 的受保护修复」`);
126
+ }
127
+ }
128
+ return {config,answers};
129
+ }
130
+
131
+ function hostArgs({plan,paths}){
132
+ return [HOST,'serve','--config',paths.config,'--mode',plan.mode,'--host-context',plan.hostContext,'--allow-reproduction',
133
+ ...(plan.originalHostContext?['--original-host-context',plan.originalHostContext]:[]),
134
+ '--runtime',plan.runtime??'codex',
135
+ ...(paths.review?['--review-config',paths.review]:[]),
136
+ ...plan.permissions];
137
+ }
138
+
139
+ function answerFor(row,answers,paths){
140
+ const {kind,payload}=row;
141
+ if(kind==='fix_learning')return {contextDigest:payload.contextDigest,status:answers.learning.status,summary:answers.learning.summary};
142
+ if(kind==='fix_diagnose')return answers.diagnosis;
143
+ if(kind==='fix_retrospective')return answers.retrospective;
144
+ if(kind==='fix_test_author'||kind==='fix_repair'){
145
+ const map=answers[kind==='fix_repair'?'repair-edits':'test-edits'],expected=payload.expected??{};
146
+ const edits=[];
147
+ for(const [target,local] of Object.entries(map)){
148
+ // 路径不在宿主给的范围里:不能硬塞,也不能断线(断线会把运行做死)。
149
+ // 回一个合法的 blocked,运行停在可续的状态,把原因打出来。
150
+ if(!Object.hasOwn(expected,target)){stderr(`${target} 不在宿主本次允许的范围内,回 blocked`);return {outcome:'blocked',edits:[]};}
151
+ edits.push({path:target,beforeSha256:expected[target],content:fs.readFileSync(path.join(paths.answers,local),'utf8')});
152
+ }
153
+ return {outcome:kind==='fix_repair'?'repaired':'authored',edits};
154
+ }
155
+ return null;
156
+ }
157
+
158
+ function main(){
159
+ const loaded=loadPlan();
160
+ const {answers}=preflight(loaded);
161
+ const {operation,plan,paths}=loaded;
162
+ driveHost({host:HOST,args:hostArgs(loaded).slice(1),cwd:path.resolve(plan.cwd),operation,
163
+ request:{...(operation==='abandon_step'?{reason:plan.reason}:{}),
164
+ ...(operation==='prepare_revision'&&Object.hasOwn(plan,'revisionTests')?{tests:plan.revisionTests}:{})},
165
+ answers,paths,answerFor});
166
+ }
167
+
168
+ main();
@@ -0,0 +1,117 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {spawnSync} from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {isSupportedExecutionPlatform} from '../runtime/js/cm-ai/execution-platform.mjs';
9
+ import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
10
+ import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
11
+ import {startFixRun} from '../runtime/js/cm-fix/start.mjs';
12
+
13
+ // 驾驭员是宿主的中间人:开进程、发一条指令、代答反问、打结果。它的价值有两条要
14
+ // 拿真宿主验:确实能把一轮开起来并走下去;答案没备齐时停在发指令之前,不把运行做死。
15
+ const DRIVER=fileURLToPath(new URL('./cm-fix-drive.mjs',import.meta.url));
16
+ const skip=!isSupportedExecutionPlatform();
17
+
18
+ function fixture(t){
19
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-drive-')));
20
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
21
+ const cwd=path.join(root,'code');fs.mkdirSync(cwd);
22
+ fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
23
+ fs.writeFileSync(path.join(cwd,'red.mjs'),"import {value} from './value.mjs';if(value!==2){console.error('BUG');process.exit(1)}");
24
+ fs.writeFileSync(path.join(cwd,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1)");
25
+ const check=[process.execPath,'red.mjs'],failure={exitCode:1,outputIncludes:'BUG'};
26
+ // 裸项目:不给 specsRoot,档案落在 code/docs/fixes,不需要 codex 沙箱。
27
+ const config={identity:{repositoryId:'fixture',runId:'drive-demo',taskId:'T-FIX-drive',attempt:1},
28
+ defect:'Synthetic wrong constant',
29
+ reproduction:{cwd,command:check,expectedFailure:failure,timeoutMs:2000},
30
+ redTest:{cwd,testFiles:['red.mjs'],command:check,expectedFailure:failure,timeoutMs:2000},
31
+ baseline:{cwd,testFiles:['existing.mjs'],commands:[{id:'existing',command:[process.execPath,'existing.mjs']}],timeoutMs:2000}};
32
+ fs.writeFileSync(path.join(root,'fix-config.json'),JSON.stringify(config));
33
+ const answers=path.join(root,'answers');fs.mkdirSync(answers);
34
+ const plan=(overrides={})=>{
35
+ const file=path.join(root,`plan-${Object.keys(overrides).join('-')||'create'}.json`);
36
+ fs.writeFileSync(file,JSON.stringify({config:'fix-config.json',cwd,mode:'create',hostContext:'drive-fixture-host',
37
+ permissions:[],answers:'answers',...overrides}));
38
+ return file;
39
+ };
40
+ return {root,cwd,answers,plan,archive:path.join(cwd,'docs','fixes')};
41
+ }
42
+ const learning={status:'applied',summary:'Reproduce before repairing; keep the existing constant test as the red gate.'};
43
+ const diagnosis={status:'diagnosed',rootCause:'Constant is 1 where the contract expects 2',affectedPaths:['value.mjs'],
44
+ plan:'Set the constant to 2 after the red test',crossLayer:false,affectedModules:['value'],
45
+ investigation:{discardedAlternatives:[],boundaryAnalysis:null}};
46
+
47
+ // 不管成功失败都要同时拿到两路输出:结果在 stdout,「应答了什么 / 为什么停」在 stderr。
48
+ function drive(planFile,operation){
49
+ const run=spawnSync(process.execPath,[DRIVER,'--plan',planFile,operation],{encoding:'utf8',stdio:['ignore','pipe','pipe']});
50
+ return {status:run.status,stdout:run.stdout??'',stderr:run.stderr??''};
51
+ }
52
+
53
+ test('the driver opens a real host, answers its questions from files and reports the stage',{skip},t=>{
54
+ const f=fixture(t);
55
+ fs.writeFileSync(path.join(f.answers,'learning.json'),JSON.stringify(learning));
56
+ fs.writeFileSync(path.join(f.answers,'diagnosis.json'),JSON.stringify(diagnosis));
57
+ const run=drive(f.plan(),'advance');
58
+ assert.equal(run.status,0,run.stderr);
59
+ const reply=JSON.parse(run.stdout);
60
+ assert.equal(reply.result.stage,'red_test_required');
61
+ assert.equal(reply.result.diagnosis.rootCause,diagnosis.rootCause);
62
+ assert.match(run.stderr,/应答 fix_learning/);
63
+ assert.match(run.stderr,/应答 fix_diagnose/);
64
+ });
65
+
66
+ test('a missing answer stops the driver before any instruction is sent, so no run is created',{skip},t=>{
67
+ const f=fixture(t);
68
+ fs.writeFileSync(path.join(f.answers,'learning.json'),JSON.stringify(learning));
69
+ // 故意不写 diagnosis.json:advance 会问诊断,宿主一步做半就永久 unknown,所以必须在这儿就停。
70
+ const run=drive(f.plan(),'advance');
71
+ assert.equal(run.status,2);
72
+ assert.match(run.stderr,/diagnosis\.json/);
73
+ assert.equal(fs.existsSync(path.join(f.archive,'.reviews','.execution')),false,'不该留下半个运行');
74
+ });
75
+
76
+ test('on resume the driver reuses the recorded learning instead of demanding the file again',{skip},t=>{
77
+ const f=fixture(t);
78
+ fs.writeFileSync(path.join(f.answers,'learning.json'),JSON.stringify(learning));
79
+ fs.writeFileSync(path.join(f.answers,'diagnosis.json'),JSON.stringify(diagnosis));
80
+ assert.equal(drive(f.plan(),'advance').status,0);
81
+ // 换一个空的答案目录模拟新会话:没有 learning.json,靠存档里那份。
82
+ const empty=path.join(f.root,'answers-empty');fs.mkdirSync(empty);
83
+ const resumed=f.plan({mode:'resume',permissions:['--allow-red-test'],answers:'answers-empty'});
84
+ const run=drive(resumed,'red_test');
85
+ assert.equal(run.status,0,run.stderr);
86
+ assert.match(run.stderr,/复用存档里已记的学习记录/);
87
+ assert.equal(JSON.parse(run.stdout).result.stage,'baseline_required');
88
+ });
89
+
90
+ test('the driver refuses unknown operations and malformed plans without touching the host',{skip},t=>{
91
+ const f=fixture(t);
92
+ assert.equal(drive(f.plan(),'make_it_pass').status,2);
93
+ fs.writeFileSync(path.join(f.root,'bad.json'),JSON.stringify({config:'fix-config.json',cwd:f.cwd,mode:'resume',
94
+ hostContext:'h',permissions:['--allow-everything!'],answers:'answers'}));
95
+ const bad=drive(path.join(f.root,'bad.json'),'status');
96
+ assert.equal(bad.status,2);
97
+ assert.match(bad.stderr,/permissions/);
98
+ assert.equal(fs.existsSync(path.join(f.archive,'.reviews')),false);
99
+ });
100
+
101
+ test('the driver abandons a local unknown step using only plan reason and flag',{skip},t=>{
102
+ const f=fixture(t),config=JSON.parse(fs.readFileSync(path.join(f.root,'fix-config.json')));
103
+ const {identity,...definition}=config;
104
+ const owner=openFixExecution({specsRoot:null,identity:config.identity,
105
+ configuration:{...definition,hostContextId:'drive-fixture-host'},create:true});
106
+ owner.close();
107
+ startFixRun({specsRoot:f.archive,identity,configuration:{...definition,hostContextId:'drive-fixture-host',archiveMode:'bare'}});
108
+ const statePath=path.join(f.archive,'.reviews','.execution',config.identity.runId,'state.json');
109
+ const state=JSON.parse(fs.readFileSync(statePath));
110
+ const store=openExecutionStore({specsRoot:f.archive,identity:state.identity,fingerprints:state.fingerprints,create:false});
111
+ store.append({id:'fix-reproduce-intent',kind:'intent',payload:{stage:'reproduce'},expectedRevision:store.snapshot().revision});store.close();
112
+ const plan=f.plan({mode:'resume',permissions:['--allow-abandon'],reason:'Lost local reproduction result',answers:undefined});
113
+ const result=drive(plan,'abandon_step');
114
+ assert.equal(result.status,0,JSON.stringify(result));
115
+ assert.equal(JSON.parse(result.stdout).result.stage,'reproduce');
116
+ assert(JSON.parse(fs.readFileSync(statePath)).records.some(row=>row.id==='fix-abandoned-1'));
117
+ });
@@ -0,0 +1,214 @@
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 {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
8
+ import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
9
+ import {fixMetricsRow} from '../runtime/js/cm-fix/metrics.mjs';
10
+ import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
11
+ import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
12
+ import {createFixHost} from '../runtime/js/cm-fix/host.mjs';
13
+ import {startFixRun,logFixEvent} from '../runtime/js/cm-fix/start.mjs';
14
+ import {eventsAt} from '../runtime/js/cm-fix/finish.mjs';
15
+ import {fixProgress} from '../runtime/js/cm-fix/progress.mjs';
16
+ import {createQaFixOwnerHost} from '../runtime/js/cm-ai/host-qa-fix-owner.mjs';
17
+ import {recordCmAiQaDecision,recordCmAiQaRun} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
18
+ import {readHostQaFixHandoff} from '../runtime/js/cm-ai/host-qa-fix.mjs';
19
+ import {qaFixIdentity} from '../runtime/js/cm-fix/qa-source.mjs';
20
+
21
+ const control={authorized:true};
22
+ async function fixture(fn,{red=true,author=false,passing=false,normal=false,qa=false,visual=false,observing=false}={}){
23
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-escalation-')));
24
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
25
+ fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
26
+ const testBody="import {value} from './value.mjs';if(value!==2){console.error('EXPECTED VALUE 2');process.exit(1)}";
27
+ if(!author)fs.writeFileSync(path.join(cwd,'red.mjs'),testBody);
28
+ const reviewer={reviewerId:'cause-reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',contextId:'independent-review',excludedThreadIds:[]};
29
+ const configuration={hostContextId:'fixture-host',defect:'Value model needs redesign',causeReview:reviewer,
30
+ reproduction:{cwd,command:[process.execPath,'-e',"console.error('BUG');process.exit(1)"],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000}};
31
+ if(red)configuration.redTest={cwd,testFiles:['red.mjs'],command:passing?[process.execPath,'-e','process.exit(0)']:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'EXPECTED VALUE 2'},timeoutMs:2000};
32
+ if(visual){
33
+ const bytes=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a7l8AAAAASUVORK5CYII=','base64');
34
+ const file=path.join(root,'before.png');fs.writeFileSync(file,bytes);
35
+ configuration.reproduction={kind:'visual',cwd,timeoutMs:2000,before:{path:file,sha256:createHash('sha256').update(bytes).digest('hex'),kind:'screenshot',description:'Synthetic visual carrier'},
36
+ reason:'视觉判断无法写自动断言',environment:{scope:'local',kind:'web',carrier:'browser',target:'fixture'},steps:['Inspect value'],expected:['Value is represented correctly']};
37
+ if(red)configuration.redTest={...configuration.reproduction,testFiles:[]};
38
+ }
39
+ if(observing)configuration.reproduction.command=[process.execPath,'-e',"if(require('node:fs').existsSync('trigger')){console.error('BUG');process.exit(1)}"];
40
+ if(author)configuration.testAuthor={requirements:['value.mjs']};
41
+ if(red){configuration.baseline={cwd,testFiles:[],commands:[],noExistingTests:'Fixture has no existing tests',timeoutMs:2000};configuration.repair={scope:['value.mjs'],requirements:['value.mjs']};}
42
+ let identity={repositoryId:'fixture',runId:'escalation-run',taskId:'T-FIX-escalation',attempt:1},parentRequest;
43
+ if(qa){
44
+ fs.mkdirSync(path.join(specsRoot,'.reviews'));
45
+ const parent={repositoryId:'fixture',runId:'parent-run',taskId:'T-001',attempt:1};
46
+ const binding={specsDir:specsRoot,codeProject:cwd,feature:'1.work',identity:parent,packageDigest:'a'.repeat(64),logHome:path.join(root,'logs')};
47
+ const report=path.join(specsRoot,'.reviews','qa-failure.md');fs.writeFileSync(report,'Synthetic FAIL');
48
+ recordCmAiQaDecision({...binding,decision:{decisionId:'qa-decision',identity:parent,packageDigest:binding.packageDigest,status:'triggered',reason:'fixture',score:null,at:'2026-09-08T01:00:00Z'}});
49
+ const run={...binding,mode:'commands',caseCount:1,testRunId:'qa-round-1'};
50
+ recordCmAiQaRun({...run,phase:'start'});recordCmAiQaRun({...run,phase:'complete',result:{result:'FAIL',passed:0,failed:1,blocked:0,report}});
51
+ const {logHome,...handoffBinding}=binding;
52
+ const handoff=readHostQaFixHandoff({...handoffBinding,testRunId:run.testRunId});
53
+ configuration.qaSource={feature:binding.feature,identity:parent,packageDigest:binding.packageDigest,testRunId:run.testRunId,handoffDigest:handoff.handoffDigest};
54
+ identity=qaFixIdentity(configuration.qaSource);
55
+ parentRequest={version:1,requestId:'fix',identity:parent,packageDigest:binding.packageDigest,testRunId:run.testRunId};
56
+ }
57
+ const options={specsRoot,identity,configuration,create:true};
58
+ const authority=createHostReviewAuthority({hostContextId:configuration.hostContextId,reviewerId:reviewer.reviewerId,adapterId:reviewer.adapterId,decide:async()=>({status:'approved'})});
59
+ let owner,calls=0;
60
+ const dependencies={...(observing?{prepare:async()=>({files:[],contextDigest:digest([]),application:{contextDigest:digest([]),status:'no_relevant_lesson',summary:'Fixture'}})}:{}),assertReviewReady(){},bridge:{async call(kind){
61
+ if(kind==='fix_test_author'){calls++;fs.writeFileSync(path.join(cwd,'red.mjs'),testBody);return {outcome:'authored'};}
62
+ assert.equal(kind,'fix_diagnose');return {status:normal?'diagnosed':'design_change',rootCause:'Shared model cannot represent value',affectedPaths:['value.mjs'],affectedModules:['model'],crossLayer:false,plan:'Redesign the model with retained red acceptance'};
63
+ }},causeReview:{authorize:authority.authorize,run:async(request,{onEvent})=>{
64
+ for(const event of [{event:'thread.started',provider_thread:'synthetic-cause-thread'},{event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])assert.equal(onEvent(event),true);
65
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,examinedPaths:['value.mjs'],findings:[],summary:'Design change confirmed'}};
66
+ }}};
67
+ const stateFile=path.join(specsRoot,'.reviews','.execution',identity.runId,'state.json');
68
+ const f={root,cwd,specsRoot,options,dependencies,authority,parentRequest,stateFile,get owner(){return owner;},get calls(){return calls;},
69
+ reopen(){owner.close();owner=openFixExecution({...options,create:false},dependencies);return owner;},
70
+ async approve(){assert.equal((await owner.advance(control)).stage,'cause_review_required');const pkg=owner.causeReviewPackage();await authority.hostDecisionProvider.decide({identity,packageDigest:pkg.packageDigest},new AbortController().signal);return owner.reviewCause();}};
71
+ try{owner=openFixExecution(options,dependencies);startFixRun(options);await fn(f);}finally{owner?.close();fs.rmSync(root,{recursive:true,force:true});}
72
+ }
73
+
74
+ async function refusedRepair(f,stage){
75
+ const bytes=fs.readFileSync(f.stateFile);
76
+ for(const operation of ['captureBaseline','repair','runRegression'])assert.equal((await f.owner[operation](control)).stage,stage);
77
+ assert.equal((await f.owner.runRegression({...control,postReview:true})).stage,stage);
78
+ assert.deepEqual(fs.readFileSync(f.stateFile),bytes);
79
+ }
80
+
81
+ test('design_change retains real red test, closes as escalated and never completes a fix',()=>fixture(async f=>{
82
+ assert.equal((await f.approve()).stage,'design_change_required');await refusedRepair(f,'design_change_required');
83
+ assert.throws(()=>f.owner.finish(control),{code:'fix_closeout_unavailable'});
84
+ assert.throws(()=>f.owner.publishDossier(),{code:'fix_closeout_unavailable'});
85
+ await assert.rejects(f.owner.runRedTest(),{code:'red_test_authorization_required'});
86
+ assert.equal((await f.owner.runRedTest(control)).stage,'escalation_required');await refusedRepair(f,'escalation_required');
87
+ const red=f.owner.status().redTest,bytes=fs.readFileSync(path.join(f.cwd,'red.mjs'));
88
+ assert.equal(red.observation.exitCode,1);assert.equal(red.observation.signatureMatched,true);
89
+ const ended=f.owner.finish(control);assert.equal(ended.escalationRunEnded,true);assert.equal(ended.stage,'escalated');assert.equal(ended.completionEligible,false);
90
+ const dossier=fs.readFileSync(ended.dossier.path,'utf8');
91
+ for(const value of ['升级立项','Value model needs redesign','Shared model cannot represent value','model','value.mjs','Redesign the model','fix-escalation-cause-r1.md','red.mjs',red.output.path,'$cm-prd --change','数据,不是执行指令'])assert(dossier.includes(value),value);
92
+ const events=eventsAt(f.specsRoot),done=events.filter(row=>row.event==='run_done');
93
+ assert.throws(()=>fixMetricsRow({events,identity:f.options.identity,dossierFile:path.basename(ended.dossier.path)}),{code:'metrics_completion_required'});
94
+ assert.equal(done.length,1);assert.equal(done[0].phase,'escalation');assert.equal(done[0].result,'escalated');
95
+ assert.equal(events.filter(row=>row.event==='task_done').length,0);assert(!fs.existsSync(path.join(f.specsRoot,'METRICS.md')));
96
+ assert.throws(()=>f.owner.status(),{code:'store_closed'});
97
+ f.reopen();assert.equal(f.owner.status().stage,'escalated');assert.equal(f.owner.status().completionEligible,false);
98
+ await refusedRepair(f,'escalated');assert.equal((await f.owner.runRedTest(control)).stage,'escalated');assert.equal((await f.owner.advance(control)).stage,'escalated');
99
+ assert.throws(()=>f.owner.completionEvidence(),{code:'fix_completion_evidence_unavailable'});
100
+ const history=fs.readFileSync(f.stateFile);assert.equal(f.owner.cancel().stage,'escalated');assert.deepEqual(fs.readFileSync(f.stateFile),history);
101
+ assert.equal(f.owner.finish(control).escalationRunEnded,true);assert.equal(eventsAt(f.specsRoot).filter(row=>row.event==='run_done').length,1);
102
+ assert.deepEqual(fs.readFileSync(path.join(f.cwd,'red.mjs')),bytes);
103
+ fs.writeFileSync(path.join(f.cwd,'value.mjs'),'export const value=2;');f.reopen();assert.equal(f.owner.status().stage,'escalated');
104
+ }));
105
+
106
+ test('escalation replay rejects a record appended after fix-escalation-result',()=>fixture(async f=>{
107
+ await f.approve();await f.owner.runRedTest(control);
108
+ assert.equal(f.owner.finish(control).stage,'escalated');
109
+ const state=JSON.parse(fs.readFileSync(f.stateFile));
110
+ assert.equal(state.records.at(-1).id,'fix-escalation-result');
111
+ const store=openExecutionStore({specsRoot:f.specsRoot,identity:state.identity,fingerprints:state.fingerprints,create:false});
112
+ try{
113
+ // A valid store record and digest chain, but illegal after the terminal exit.
114
+ store.append({id:'fix-cancel',kind:'cancel',payload:{reason:'user_cancelled'},expectedRevision:store.snapshot().revision});
115
+ }finally{store.close();}
116
+ assert.throws(()=>f.reopen(),{code:'fix_history_invalid'});
117
+ }));
118
+
119
+ test('design_change author path writes once, resumes and then requires real red evidence',()=>fixture(async f=>{
120
+ assert.equal((await f.approve()).stage,'test_author_required');
121
+ assert.equal((await f.owner.runRedTest(control)).stage,'test_author_required');
122
+ assert.throws(()=>f.owner.finish(control),{code:'fix_closeout_unavailable'});
123
+ await assert.rejects(f.owner.authorTests(),{code:'test_author_authorization_required'});
124
+ assert.equal((await f.owner.authorTests(control)).stage,'design_change_required');f.reopen();
125
+ assert.equal((await f.owner.authorTests(control)).stage,'design_change_required');assert.equal(f.calls,1);
126
+ assert.equal((await f.owner.runRedTest(control)).stage,'escalation_required');
127
+ const output=path.join(f.specsRoot,f.owner.status().redTest.output.path),bytes=fs.readFileSync(output);
128
+ fs.writeFileSync(output,'tampered');assert.equal(f.owner.status().stage,'red_test_evidence_required');
129
+ assert.throws(()=>f.owner.finish(control),{code:'fix_closeout_unavailable'});fs.writeFileSync(output,bytes);
130
+ assert.equal(f.owner.finish(control).stage,'escalated');assert(fs.existsSync(path.join(f.cwd,'red.mjs')));
131
+ },{author:true}));
132
+
133
+ test('design_change unexpectedly green blocks escalation',()=>fixture(async f=>{
134
+ await f.approve();assert.equal((await f.owner.runRedTest(control)).stage,'red_test_not_confirmed');
135
+ assert.throws(()=>f.owner.finish(control),{code:'fix_closeout_unavailable'});assert.throws(()=>f.owner.publishDossier(),{code:'fix_closeout_unavailable'});
136
+ assert.equal(eventsAt(f.specsRoot).filter(row=>row.event==='run_done').length,0);f.reopen();assert.equal(f.owner.status().stage,'red_test_not_confirmed');
137
+ },{passing:true}));
138
+
139
+ test('design_change without configured red test escalates with an explicit absence reason',()=>fixture(async f=>{
140
+ const approved=await f.approve();assert.equal(approved.stage,'escalation_required');assert.equal(approved.completionEligible,false);
141
+ const archived=f.owner.publishDossier();assert.match(fs.readFileSync(archived.dossier.path,'utf8'),/没有失败测试.*未配置 redTest/);
142
+ assert.equal(eventsAt(f.specsRoot).filter(row=>row.event==='run_done').length,0);
143
+ assert.equal(f.owner.finish(control).stage,'escalated');
144
+ },{red:false}));
145
+
146
+ for(const crash of ['dossier','run_done'])test(`escalation resumes after ${crash} without duplicate run_done`,()=>fixture(async f=>{
147
+ await f.approve();await f.owner.runRedTest(control);
148
+ const archived=f.owner.publishDossier(),bytes=fs.readFileSync(archived.dossier.path);
149
+ assert.equal(JSON.parse(fs.readFileSync(f.stateFile)).records.filter(r=>r.id==='fix-escalation-dossier-intent').length,1);
150
+ if(crash==='run_done')logFixEvent({...f.options,event:'run_done',phase:'escalation',detail:'Synthetic crash after original log',data:{result:'escalated',dossier_file:`fixes/${path.basename(archived.dossier.path)}`,dossier_sha256:archived.dossier.sha256}});
151
+ f.reopen();assert.equal(f.owner.finish(control).escalationRunEnded,true);f.reopen();assert.equal(f.owner.finish(control).stage,'escalated');
152
+ assert.deepEqual(fs.readFileSync(archived.dossier.path),bytes);assert.equal(eventsAt(f.specsRoot).filter(row=>row.event==='run_done').length,1);
153
+ }));
154
+
155
+ test('escalation rejects a conflicting prior run_done',()=>fixture(async f=>{
156
+ await f.approve();await f.owner.runRedTest(control);f.owner.publishDossier();
157
+ logFixEvent({...f.options,event:'run_done',phase:'observation',detail:'Conflicting exit',data:{result:'observing'}});
158
+ assert.throws(()=>f.owner.finish(control),{code:'fix_escalation_exit_conflict'});
159
+ assert.equal(eventsAt(f.specsRoot).filter(row=>row.event==='run_done').length,1);
160
+ }));
161
+
162
+ test('diagnosed record bytes and digests are untouched on reopen and ordinary red still reaches baseline',()=>fixture(async f=>{
163
+ assert.equal((await f.owner.advance(control)).stage,'red_test_required');
164
+ const bytes=fs.readFileSync(f.stateFile),status=f.owner.status();f.reopen();
165
+ assert.deepEqual(f.owner.status(),status);assert.deepEqual(fs.readFileSync(f.stateFile),bytes);
166
+ assert.equal((await f.owner.runRedTest(control)).stage,'baseline_required');
167
+ const redBytes=fs.readFileSync(f.stateFile);f.reopen();assert.equal(f.owner.status().stage,'baseline_required');assert.deepEqual(fs.readFileSync(f.stateFile),redBytes);
168
+ assert.equal(JSON.parse(redBytes).records.some(r=>r.id.includes('escalation')),false);
169
+ },{normal:true}));
170
+
171
+ test('host sequence returns escalation exit without reading the closed owner',()=>fixture(async f=>{
172
+ const host=createFixHost({owner:f.owner,config:{...f.options.configuration,specsRoot:f.specsRoot,identity:f.options.identity},authority:f.authority,permissions:['--allow-reproduction','--allow-red-test','--allow-finish']});
173
+ const result=await host.run('escalate');assert.equal(result.stage,'escalated');assert.equal(result.escalationRunEnded,true);
174
+ }));
175
+
176
+ for(const operation of ['finish','run'])test(`QA child escalation via ${operation} reports qa_fix_incomplete and restores parent`,()=>fixture(async f=>{
177
+ await f.approve();if(operation==='finish')await f.owner.runRedTest(control);f.owner.close();let reopens=0;
178
+ const parent=()=>({host:{handle:async()=>({state:'fixture_completed',identity:f.parentRequest.identity,packageDigest:f.parentRequest.packageDigest})},close(){}});
179
+ const serial=createQaFixOwnerHost({parent:parent(),reopenParent:()=>{reopens++;return parent();},hostContextId:'fixture-host',parentHostContextId:'fixture-host',fix:{specsRoot:f.specsRoot,identity:f.options.identity,configuration:f.options.configuration},allowStart:true,fixExecution:f.dependencies,fixPermissions:['--allow-red-test','--allow-finish']});
180
+ try{
181
+ const result=await serial.handle({...f.parentRequest,operation:operation==='finish'?'fix_action':'fix_run',...(operation==='finish'?{fixOperation:'finish'}:{})});
182
+ assert.equal(result.code,'qa_fix_incomplete');assert.equal(result.fixStage,'escalated');assert.equal(result.actionResult.escalationRunEnded,true);assert.equal(result.evidence,undefined);assert.equal(reopens,1);
183
+ }finally{serial.close();}
184
+ },{qa:true}));
185
+
186
+ test('progress shows only escalation operations and never claims fixed completion',()=>{
187
+ assert.equal(fixProgress({stage:'design_change_required',diagnosis:{status:'design_change'},executionActive:true}).current,'当前操作正在执行');
188
+ for(const [stage,next] of [['design_change_required','red_test'],['test_author_required','author_tests'],['escalation_required','finish'],['escalated',null]]){
189
+ const progress=fixProgress({stage,diagnosis:{status:'design_change'},completionEligible:false},{redTest:{},testAuthor:{}});
190
+ assert.equal(progress.nextAction,next);assert.equal(progress.finished,false);assert(!JSON.stringify(progress.remaining).includes('修复代码'));
191
+ }
192
+ });
193
+
194
+ test('visual escalation redTest configured=true states no automatic failing test',()=>fixture(async f=>{
195
+ assert.equal((await f.approve()).stage,'design_change_required');
196
+ assert.equal((await f.owner.runRedTest(control)).stage,'escalation_required');
197
+ const ended=f.owner.finish(control),text=fs.readFileSync(ended.dossier.path,'utf8');
198
+ assert.match(text,/没有失败测试/);assert.match(text,/视觉判断无法写自动断言/);assert.equal(ended.completionEligible,false);
199
+ },{visual:true}));
200
+
201
+ test('visual escalation redTest configured=false is refused at open',()=>assert.rejects(
202
+ fixture(()=>assert.fail('visual configuration without redTest was opened'),{visual:true,red:false}),
203
+ {code:'fix_visual_configuration_required'}));
204
+
205
+ test('observing run can resume into escalation while retaining its original dossier and exit',()=>fixture(async f=>{
206
+ assert.equal((await f.owner.advance(control)).stage,'observation');const observed=f.owner.finish(control),prefix=fs.readFileSync(observed.dossier.path);
207
+ fs.writeFileSync(path.join(f.specsRoot,'failure.txt'),'New reproduction evidence');fs.writeFileSync(path.join(f.cwd,'trigger'),'ready');
208
+ f.reopen();f.owner.resume({...control,evidenceFiles:['failure.txt']});await f.approve();
209
+ assert.equal((await f.owner.runRedTest(control)).stage,'escalation_required');
210
+ const ended=f.owner.finish(control);assert.equal(ended.stage,'escalated');assert.equal(ended.dossier.path,observed.dossier.path);
211
+ assert(fs.readFileSync(ended.dossier.path).subarray(0,prefix.length).equals(prefix));
212
+ assert.deepEqual(eventsAt(f.specsRoot).filter(row=>row.event==='run_done').map(row=>row.result),['observing','escalated']);
213
+ f.reopen();assert.equal(f.owner.finish(control).stage,'escalated');
214
+ },{observing:true}));
@@ -166,3 +166,29 @@ test('a walkthrough that does not line up with the diagnosis stops right after d
166
166
  }finally{owner.close();bridge.close();}
167
167
  });
168
168
  });
169
+
170
+ // 「重名当场拦下」(建运行时检查)原本一刀切:名字被占就永久不能再用,而且没有
171
+ // 释放的办法——cancel 只标记状态,证据文件照样留着。这跟 host-handoff 早就定下的
172
+ // 规则不一致:那边是「被审查消费过的证据绝不动,其余归档让路」。照同一条规则来。
173
+ test('a dead run releases its name by archiving, but a reviewed one keeps it',()=>fixture(async(options)=>{
174
+ const reviews=path.join(options.specsRoot,'.reviews');
175
+ fs.mkdirSync(reviews,{recursive:true,mode:0o700});
176
+
177
+ // 半路死掉的运行只留下红灯输出,没有任何审查结论 —— 让路
178
+ const redOutput=path.join(reviews,'fix-demo-a1-red-output.md');
179
+ const leftover='{"stdoutBase64":"","stderrBase64":"ZGVhZCBydW4="}';
180
+ fs.writeFileSync(redOutput,leftover);
181
+ const configuration={...options.configuration,
182
+ redTest:{cwd:options.configuration.reproduction.cwd,testFiles:['red.mjs'],
183
+ command:[process.execPath,'-e','process.stderr.write("BUG");process.exit(1)'],
184
+ expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000}};
185
+ openFixExecution({...options,configuration}).close();
186
+ assert.equal(fs.existsSync(redOutput),false,'占位的红灯输出该让开');
187
+ const archived=fs.readdirSync(path.join(reviews,'.superseded'));
188
+ assert.equal(archived.length,1,'让开不等于删掉');
189
+ assert.equal(fs.readFileSync(path.join(reviews,'.superseded',archived[0]),'utf8'),leftover,'原字节要留着');
190
+
191
+ // 真做过审查的名字仍然占住:那份结论不许被挪开
192
+ fs.writeFileSync(path.join(reviews,`fix-demo-${identity.taskId}-r1.md`),'verdict: approved');
193
+ assert.throws(()=>openFixExecution({...options,configuration,create:true}),{code:'fix_evidence_name_taken'});
194
+ }));
@@ -11,13 +11,15 @@ import {id,json,need,shape,digest} from '../runtime/js/cm-ai/effect-contract.mjs
11
11
  import {readConversationReviewConfiguration} from './cm-ai-host.mjs';
12
12
  import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
13
13
 
14
- const usage='cm-fix-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-reproduction [--original-host-context ID] [--runtime codex|claude] [--review-config PATH] [--allow-cause-review] [--allow-final-review] [--allow-test-author] [--allow-red-test] [--allow-baseline] [--allow-repair] [--allow-regression] [--allow-learning-writeback]\nCodex or Claude current-host operations: advance, cause_review_package, cause_review, author_tests, red_test, baseline, repair, regression, retrospective, learning_writeback, handoff, final_review_package, final_review, publish_review, check_n5, post_review_regression, status, cancel. Runtime defaults to codex; claude uses its own matching diagnostic receipt and cannot reuse Codex preflight or disabledSkills settings. Runtime selection is bound to recovery; switching providers requires a separate run. This selects existing adapters, not permission to call them. Each write/check needs its respective launch flag and configuration. Test authoring, repair, cause and final review dispatch require matching existing stdin diagnostics; diagnostic alone is not authorization. Passing regression stops at handoff_required. The read-only retrospective operation yields handoff_ready or learning_writeback_required. learning_writeback requires its own flag, preserves project instructions and includes AGENTS.md in the review scope; it does not authorize provider calls. handoff publishes the fixed specs-local handoff with Learning evidence and moves to final_review_required; no provider is called and no task is completed. final_review_package is read-only and returns the final content-bound review package. final_review requires its own flag and matching diagnostics; observations do not complete the task. publish_review projects the registered result into the existing review file; it does not dispatch or complete tasks. check_n5 runs the original Learning-aware gate; post_review_regression requires --allow-regression and reaches closeout_required, not completion.';
14
+ const usage='cm-fix-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-reproduction [--original-host-context ID] [--runtime codex|claude] [--review-config PATH] [--allow-cause-review] [--allow-final-review] [--allow-test-author] [--allow-red-test] [--allow-baseline] [--allow-repair] [--allow-regression] [--allow-learning-writeback]\nCodex or Claude current-host operations: prepare_revision, revision_test_check, advance, cause_review_package, cause_review, author_tests, red_test, baseline, repair, regression, retrospective, learning_writeback, handoff, final_review_package, final_review, publish_review, check_n5, post_review_regression, status, cancel. Runtime defaults to codex; claude uses its own matching diagnostic receipt and cannot reuse Codex preflight or disabledSkills settings. Runtime selection is bound to recovery; switching providers requires a separate run. This selects existing adapters, not permission to call them. Each write/check needs its respective launch flag and configuration. Test authoring, repair, cause and final review dispatch require matching existing stdin diagnostics; diagnostic alone is not authorization. Passing regression stops at handoff_required. The read-only retrospective operation yields handoff_ready or learning_writeback_required. learning_writeback requires its own flag, preserves project instructions and includes AGENTS.md in the review scope; it does not authorize provider calls. handoff publishes the fixed specs-local handoff with Learning evidence and moves to final_review_required; no provider is called and no task is completed. final_review_package is read-only and returns the final content-bound review package. final_review requires its own flag and matching diagnostics; observations do not complete the task. publish_review projects the registered result into the existing review file; it does not dispatch or complete tasks. check_n5 runs the original Learning-aware gate; post_review_regression requires --allow-regression and reaches closeout_required, not completion.';
15
15
 
16
16
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr,reviewWorkerFactory=null}={}){
17
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Design-change escalation: approved cause_review reaches design_change_required when redTest is configured (test_author_required first if needed); author_tests/red_test keep their original flags and evidence checks. Confirmed red reaches escalation_required, never baseline/repair/regression. Non-visual runs without redTest reach escalation_required directly after approval and record why no failing test exists. Visual runs require a matching visual redTest with testFiles:[] and must complete the visual red step before escalation; opening without it fails with fix_visual_configuration_required. publish_dossier saves an 升级立项 dossier; finish requires --allow-finish, records run_done phase escalation/result escalated and closes the owner with escalationRunEnded:true. Retained tests become acceptance checks for the suggested $cm-prd --change. Resume the same run after a crash; conflicting exits fail with fix_escalation_exit_conflict. Terminal escalated is not completed: no task_done, metrics, repair or parent QA completion.\n');
17
18
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Omit specsRoot or use null for a bare project: the same owner stores archives in docs/fixes and reviews in docs/fixes/.reviews, uses the original no-specs log mode, and skips METRICS. No specs skeleton is created. Visual-only reproduction/redTest may use kind:visual with cwd, timeoutMs, before:{path,sha256,kind:screenshot|video,description}, reason explaining why automated red cannot be written, environment, steps and expected; redTest also has testFiles:[]. No testAuthor or fake red/green command. Repair/regression/review/finish permissions remain mandatory. qa_browser returns actual after carrier metadata; missing evidence blocks.\n');
18
19
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Optional startup configuration protectSpecs:true uses the existing Codex native sandbox for reproduction, red/baseline/regression/walkthrough commands and fixed text edits, without a model call. Requires the local sandbox executable; it does not change the current Codex/Claude host or reviewer identity. Original action permissions remain required. fix_test_author/fix_repair with editMode=protected-text-v1 require {outcome,edits:[{path,beforeSha256,content}]} using the supplied scope/expected hashes; never write directly. Content is full UTF-8 text or null for deletion, blocked requires edits:[]. Original 64KiB response limit applies. Drift or failed writes retain the original unknown boundary; no automatic retry/rollback or protection-mode switching on resume.\n');
19
20
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('completion_evidence is read-only and available only after the original finish has completed and current evidence still validates. It returns the selected attempt, original reviewed package, handoff/review digests, completion event IDs and optional qaSource from the original owner. It does not complete or resume a parent task; JSON evidence alone is not authority.\n');
20
21
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('recover_final_review requires --allow-final-review-recovery and exact latest invocationId/packageDigest, previousInvocationStopped:true, and a nonempty reason. The legacy first continuation remains once-only. A further continuation additionally requires a fresh startup --final-review-recovery-invocation ID matching the latest unknown invocation, authorizing exactly one new call. Confirm the previous process stopped; this is a trusted host acknowledgment, not an automatic liveness check. Preparation dispatches nothing. Later final_review requires recovery permission and --allow-final-review; additional cycles require the same invocation binding after restart. Old records, task attempt, reviewed package and the original Review/N5/finish remain unchanged. No automatic retry, cancelled/complete-verdict recovery, missing-thread recovery, business-revision recovery or source-drift bypass. status adds a read-only progress projection, not authorization or current-source verification.\n');
22
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_step requires --allow-abandon, stage unknown, an eligible local pending kind, and a nonempty single-line reason up to 1000 UTF-8 bytes. It records the abandoned intent and returns to the required stage; a later separate action redoes the step. At most eight abandonments per run. Review, Learning writeback and handoff remain unavailable.\n');
21
23
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('N6 child configuration may include qaSource {feature, identity, packageDigest, testRunId, handoffDigest}; derive the separate fixed child identity with qaFixIdentity. It requires --allow-qa-fix in addition to existing action flags. Close the parent host first: the original specs-wide owner lock is shared. Creation/resume rechecks the current failed round, project, report and policy; the source is bound to the original fix configuration. This does not resume the parent or automatically rerun QA, and does not authorize provider calls, installation or Git.\n');
22
24
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Second-round retrospective uses the cumulative original baseline, including previously authored tests and Learning scope. It persists the current round reflection and reaches revision_handoff_ready or revision_learning_writeback_required; neither state completes the task or publishes a new handoff. From revision_handoff_ready, handoff publishes a separate a2 handoff containing cumulative changes, current reflection, original red evidence and prior review/Learning history; final_review_package then reads that bound package. Pending Learning blocks publication. final_review requires --allow-final-review, uses fresh-thread exclusions and carries prior findings; publish_review writes the original r2 evidence and review log, and check_n5 runs the original Learning-aware gate. Approval reaches revision_post_review_regression_required, not completion.\n');
23
25
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('prepare_revision requires --allow-repair and either a published first-round changes_requested review or an approved first-round review followed by a package-bound walkthrough result of failed. The latter preserves the approved verdict and carries separate walkthrough failure evidence; passed, blocked, unknown, or drifted evidence cannot authorize this repair. An approved first-round review followed by package-bound post-review regression defect_remaining or regressed can also prepare the second repair when all baseline commands produced complete results. The regression commands must match the first reviewed handoff; passed, inconclusive, unavailable or partial evidence is refused. Regression and walkthrough failure feedback are mutually exclusive and neither replaces the next independent review. It rereads project Learning and persists the second-round preparation in the original store, preserving first-round evidence. repair then uses the original business scope and findings with separate second-round records. regression requires --allow-regression and reruns the original test commands against the second repair, preserving the original red evidence. Success reaches revision_handoff_required, not completion; handoff and final_review use the second-round package; review evidence publication and N5 are connected; post_review_regression requires --allow-regression and reaches revision_closeout_required after the original checks; walkthrough requires --allow-walkthrough and binds the second-round package and identity; finish reuses the original closeout with --allow-finish, preserving first-round history and recording completion for attempt 2. Second-round learning_writeback requires --allow-learning-writeback, includes the resulting AGENTS.md in the cumulative review package and preserves prior Learning history; pending or unknown writeback cannot advance to handoff. A lost repair or regression result stays unknown and is not redispatched.\n');
@@ -29,7 +31,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
29
31
  need(['create','resume'].includes(argv[4]),'invalid_arguments');id(argv[6]);
30
32
  const extra=new Map();
31
33
  for(let index=8;index<argv.length;index++){
32
- const flag=argv[index];need(!extra.has(flag)&&['--runtime','--review-config','--original-host-context','--final-review-recovery-invocation','--allow-qa-fix','--allow-cause-review','--allow-final-review','--allow-final-review-recovery','--allow-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
34
+ const flag=argv[index];need(!extra.has(flag)&&['--runtime','--review-config','--original-host-context','--final-review-recovery-invocation','--allow-qa-fix','--allow-cause-review','--allow-final-review','--allow-final-review-recovery','--allow-abandon','--allow-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
33
35
  if(flag.startsWith('--allow-'))extra.set(flag,true);
34
36
  else{need(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments');extra.set(flag,argv[++index]);}
35
37
  }