@aibyzero/cm-workflow 0.16.3 → 0.16.5

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 (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +55 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/next-steps.md +14 -24
  9. package/docs/runtime-failover.md +1 -1
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  12. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
  15. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  16. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  17. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  18. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  19. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  21. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  22. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  24. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  25. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  27. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  28. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  29. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  30. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  31. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  32. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  34. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  38. package/runtime/js/cm-ai/host-session.mjs +20 -5
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  43. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  44. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  45. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  46. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  47. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  48. package/runtime/js/cm-ai/review-package.mjs +427 -31
  49. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  50. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  52. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  53. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  54. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  56. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  57. package/runtime/js/cm-fix/execution.mjs +109 -25
  58. package/runtime/js/cm-fix/host-review.mjs +7 -3
  59. package/runtime/js/cm-fix/host.mjs +3 -1
  60. package/runtime/js/cm-fix/progress.mjs +1 -0
  61. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  62. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  63. package/runtime/js/cm-prd/analysis.mjs +2 -1
  64. package/runtime/js/cm-prd/change.mjs +28 -10
  65. package/runtime/js/cm-prd/draft.mjs +5 -2
  66. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  67. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  68. package/runtime/js/cm-prd/self-check.mjs +6 -3
  69. package/runtime/js/cm-prd/summary.mjs +6 -2
  70. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  71. package/runtime/js/spec-task-line.mjs +117 -0
  72. package/runtime/js/specs-status.mjs +14 -3
  73. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  74. package/scripts/cm-ai-admission.mjs +19 -10
  75. package/scripts/cm-ai-admission.test.mjs +65 -1
  76. package/scripts/cm-ai-batch-drive.mjs +93 -21
  77. package/scripts/cm-ai-batch-drive.test.mjs +171 -3
  78. package/scripts/cm-ai-batch-host.mjs +37 -13
  79. package/scripts/cm-ai-batch-host.test.mjs +26 -0
  80. package/scripts/cm-ai-batch-run.mjs +33 -10
  81. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  82. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  84. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  85. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  86. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  87. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  88. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  89. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  90. package/scripts/cm-ai-drive.mjs +480 -47
  91. package/scripts/cm-ai-drive.test.mjs +247 -10
  92. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  93. package/scripts/cm-ai-host.mjs +89 -25
  94. package/scripts/cm-ai-host.test.mjs +274 -12
  95. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  96. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  97. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  98. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  99. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  100. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  101. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  102. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  103. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  104. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  105. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  106. package/scripts/cm-ai-run.mjs +160 -60
  107. package/scripts/cm-ai-run.test.mjs +4 -3
  108. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  109. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  110. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  111. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  112. package/scripts/cm-ai-supersede.test.mjs +571 -17
  113. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  114. package/scripts/cm-capability-gate.test.mjs +21 -2
  115. package/scripts/cm-check-drive.mjs +4 -3
  116. package/scripts/cm-check-drive.test.mjs +17 -1
  117. package/scripts/cm-check-entry.mjs +13 -2
  118. package/scripts/cm-check-host.mjs +2 -2
  119. package/scripts/cm-check-host.test.mjs +57 -1
  120. package/scripts/cm-check-runtime.sh +16 -7
  121. package/scripts/cm-claude-developer-worker.test.mjs +43 -2
  122. package/scripts/cm-claude-probe.test.mjs +9 -1
  123. package/scripts/cm-claude-review-stream.test.mjs +68 -0
  124. package/scripts/cm-claude-worker.test.mjs +11 -4
  125. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  126. package/scripts/cm-failover.mjs +8 -8
  127. package/scripts/cm-fix-abandon.test.mjs +123 -5
  128. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  129. package/scripts/cm-fix-drive.mjs +45 -13
  130. package/scripts/cm-fix-drive.test.mjs +36 -1
  131. package/scripts/cm-fix-host.mjs +9 -6
  132. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  133. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  134. package/scripts/cm-host-check.test.mjs +6 -3
  135. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  136. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  137. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  138. package/scripts/cm-log-event.mjs +17 -0
  139. package/scripts/cm-log-event.test.mjs +31 -0
  140. package/scripts/cm-prd-completion.test.mjs +105 -2
  141. package/scripts/cm-prd-draft.test.mjs +14 -0
  142. package/scripts/cm-prd-drive.mjs +13 -7
  143. package/scripts/cm-prd-drive.test.mjs +10 -0
  144. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  145. package/scripts/cm-prd-review-gate.mjs +126 -81
  146. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  147. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  148. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  149. package/scripts/cm-prd-self-check.test.mjs +6 -0
  150. package/scripts/cm-prd-summary.test.mjs +40 -0
  151. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  152. package/scripts/cm-review-inventory.test.mjs +253 -1
  153. package/scripts/cm-spec-manifest.mjs +28 -10
  154. package/scripts/cm-spec-manifest.test.mjs +8 -4
  155. package/scripts/cm-spec-task-line.test.mjs +138 -0
  156. package/scripts/cm-specs-status.test.mjs +31 -1
  157. package/scripts/cm-task-gate.mjs +18 -10
  158. package/scripts/cm-task-gate.py +1 -1
  159. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  160. package/scripts/fixtures/claude-review-process.mjs +1 -0
  161. package/scripts/fixtures/process-cleanup.mjs +99 -0
  162. package/scripts/test-cm-log-event.py +2 -0
  163. package/scripts/test-cm-prd-review-gate.py +2 -1
  164. package/scripts/test-npm-install.py +1 -1
  165. package/scripts/test-scan-public-safety.py +1 -1
  166. package/scripts/test-shell-compat.sh +67 -0
  167. package/scripts/test-spec-manifest.py +16 -8
  168. package/scripts/test-task-gate.py +2 -2
  169. package/scripts/test-workflow-config.py +1 -0
  170. package/scripts/validate-public-repo.py +1 -0
  171. package/skills/cm-ai/references/N1-init.md +1 -1
  172. package/skills/cm-ai/references/js-host.md +264 -40
  173. package/skills/cm-check/SKILL.md +6 -1
  174. package/skills/cm-check/references/js-host.md +3 -3
  175. package/skills/cm-fix/references/js-host.md +22 -1
  176. package/skills/cm-prd/references/js-change-recovery.md +30 -0
  177. package/skills/cm-prd/references/js-host.md +6 -0
@@ -10,9 +10,15 @@ import {preQaConfigurations,readQaAttachment} from '../runtime/js/cm-ai/qa-attac
10
10
  import {recordCmAiQaAttachment} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
11
11
  import {isSupportedExecutionPlatform} from '../runtime/js/cm-ai/execution-platform.mjs';
12
12
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
13
- import {previousQaMaterial,qaConfigurationSlice,qaInvariantDigest,qaRevisionChain,verifyQaRevisionMaterial} from '../runtime/js/cm-ai/qa-config-revision.mjs';
14
- import {inspectCmAiQaRevisionTarget,recordCmAiQaConfigurationRevision} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
15
- import {prepareReviewedEvidenceSupersession,archiveReviewedEvidence,recordEvidenceSupersession} from '../runtime/js/cm-ai/reviewed-evidence-supersede.mjs';
13
+ import {hasLegacyQaPlanFingerprint,previousQaMaterial,qaConfigurationSlice,qaExecutorMaterial,qaInvariantDigest,qaRevisionChain,verifyQaRevisionMaterial} from '../runtime/js/cm-ai/qa-config-revision.mjs';
14
+ import {hasCmAiQaRun,inspectCmAiQaRevisionTarget,recordCmAiQaConfigurationRevision} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
15
+ import {prepareReviewedEvidenceSupersession,archiveReviewedEvidence,recordEvidenceSupersession,assertNoUnrecordedPriorCode} from '../runtime/js/cm-ai/reviewed-evidence-supersede.mjs';
16
+ import {explainFingerprintMismatch} from '../runtime/js/cm-ai/launch-mismatch.mjs';
17
+ import {recordReviewAbandonment} from '../runtime/js/cm-ai/review-abandon-log.mjs';
18
+ import {recordEffectAbandonment} from '../runtime/js/cm-ai/effect-abandon-log.mjs';
19
+ import {reviewConsumedHandoff,reviewedHandoffConflict} from '../runtime/js/cm-ai/host-handoff.mjs';
20
+ import {RUN_ID_RULE,validRunId} from './cm-log-event.mjs';
21
+ import {JOURNAL_PAYLOAD_LIMIT,boundedReason} from '../runtime/js/cm-ai/effect-contract.mjs';
16
22
 
17
23
  const usage='cm-ai-run.mjs serve --config RUN_DEFINITION.json --mode create|resume (no provider dispatch)\nNew runs bind approved specification material from specsDir; requirements may be [] or supplemental code-project files. Manifest drift blocks as spec_drift; legacy journals retain their original format.';
18
24
  const fail=code=>{throw Object.assign(new Error(code),{code});};
@@ -128,16 +134,20 @@ export async function createCodexExecution(configuration,authority){
128
134
  return execution;
129
135
  }
130
136
 
137
+ // Also bounds every changed-file list a task handoff can carry (see the handoff
138
+ // size test): raising it means revisiting the 256 KiB handoff limit.
139
+ export const RUN_DEFINITION_LIMIT=64*1024;
131
140
  export function readRunDefinition(file){
132
141
  const info=fs.lstatSync(file);
133
142
  if(!info.isFile()||info.isSymbolicLink())fail('invalid_config: not a regular file');
134
- if(info.size>64*1024)fail('invalid_config: file exceeds 64KiB');
143
+ if(info.size>RUN_DEFINITION_LIMIT)fail('invalid_config: file exceeds 64KiB');
135
144
  return validateRunDefinition(JSON.parse(fs.readFileSync(file,'utf8')));
136
145
  }
137
146
  export function validateRunDefinition(input){
138
147
  const value=structuredClone(input);
139
148
  const keys=['version','specsDir','codeProject','feature','identity','scope','requirements'];
140
149
  if(value&&Object.hasOwn(value,'codeProjects'))keys.push('codeProjects');
150
+ if(value&&Object.hasOwn(value,'taskSelection'))keys.push('taskSelection');
141
151
  if(!value||typeof value!=='object')fail('invalid_config: expected an object');
142
152
  const unexpected=Object.keys(value).filter(key=>!keys.includes(key));
143
153
  const missing=keys.filter(key=>!Object.hasOwn(value,key));
@@ -157,6 +167,9 @@ export function validateRunDefinition(input){
157
167
  for(const key of ['repositoryId','runId','taskId']){
158
168
  if(typeof value.identity[key]!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value.identity[key]))fail('invalid_identity');
159
169
  }
170
+ if(Object.hasOwn(value,'taskSelection')&&(!value.taskSelection||value.taskSelection.version!==1
171
+ ||Object.keys(value.taskSelection).sort().join(',')!=='taskId,version'
172
+ ||value.taskSelection.taskId!==value.identity.taskId))fail('invalid_task_selection');
160
173
  for(const key of ['scope','requirements']){
161
174
  if(!Array.isArray(value[key])||(!value[key].length&&!(key==='requirements'))||value[key].length>256
162
175
  ||value[key].some(p=>typeof p!=='string'||!p||p.includes('\\')||p.includes('\0')
@@ -170,13 +183,46 @@ export function validateRunDefinition(input){
170
183
  }
171
184
  return value;
172
185
  }
186
+ // Create-time only: an existing journal keeps resuming (and can be abandoned)
187
+ // exactly as before, while a new run can no longer strand its first develop
188
+ // effect on a run ID the run log refuses.
189
+ export function assertCreatableRunId(identity){
190
+ if(!validRunId(identity?.runId))fail(`invalid_config: identity.runId must be ${RUN_ID_RULE} (run log requirement)`);
191
+ }
192
+
193
+ // Definition is data, never an import path, command, grant or executable callback.
194
+ // legacyQa rebuilds the historical QA executor form for stores created before
195
+ // the built-in plan left the fingerprint; it is never used to create a store.
196
+ export function runConfigMaterial(definition,execution,{parallelSelection=null,bootstrapConfig=null,legacyQa=false}={}){
197
+ if(execution===null)return parallelSelection===null?definition:{definition,parallelSelection};
198
+ return {definition,...(parallelSelection===null?{}:{parallelSelection}),execution:execution.configuration,
199
+ ...(bootstrapConfig?{bootstrap:bootstrapConfig}:{}),
200
+ ...(Object.hasOwn(execution,'developmentAttempt')?{developmentAuthorization:'per-attempt-v1'}:{}),
201
+ ...(execution.hostDecisionProvider?{hostDecisionProvider:{version:1,timeoutMs:execution.hostDecisionProvider.timeoutMs}}:{}),
202
+ ...(execution.qaDecisionProvider?{qaDecisionProvider:'host-v1',qaTimeoutMs:execution.qaDecisionProvider.timeoutMs}:{}),
203
+ ...(execution.qaExecutor?{qaExecutor:qaExecutorMaterial(execution.qaExecutor,legacyQa)}:{}),
204
+ ...(execution.applicableAgentFiles?{applicableAgentFiles:execution.applicableAgentFiles}:{}),
205
+ ...(execution.documentationProvider?{documentationProvider:{version:1,timeoutMs:execution.documentationProvider.timeoutMs}}:{}),
206
+ ...(execution.documentationResult?{documentationResult:execution.documentationResult}:{}),
207
+ ...(execution.documentationSync?{documentationSync:{version:1,paths:execution.documentationSync.paths}}:{})};
208
+ }
209
+ const LEGACY_QA_FINGERPRINT_REASON='运行指纹与当前配置不符。若此运行由之前的版本创建,它的指纹还含有当时生效的 CM 配置'
210
+ +'(项目 .cm-workflow.yml、~/.cm-workflow/runtimes.yml 与插件内置默认值):把这些配置恢复为创建时的内容即可恢复;'
211
+ +'现在新建的运行不再把这些可变配置写进指纹。否则请核对 run.json、--workflow-config、宿主身份及授权参数是否与创建时一致。';
173
212
 
174
- export async function openControlRun(definition,mode,execution=null,{rerunUnknownQa=false,rerunBlockedQa=false,parallelSelection=null,qaConfigRevision=null,supersedeReason=null}={}){
213
+ export async function openControlRun(definition,mode,execution=null,{rerunUnknownQa=false,rerunBlockedQa=false,qaEnvironmentFailure=null,parallelSelection=null,qaConfigRevision=null,supersedeReason=null,acceptSupersededCodeDrift=false,allowAbandonReview=false,allowAbandonEffect=false,holdRevision=false,specRebindReason=null}={}){
175
214
  // Check before importing node:sqlite: legacy Node users get a useful error.
176
215
  if(!isSupportedExecutionPlatform())fail('unsupported_runner_platform');
177
216
  const {conversationProtection}=await import('../runtime/js/cm-ai/host-conversation-execution.mjs');
178
217
  if(!['create','resume'].includes(mode))fail('invalid_mode');
218
+ if(mode==='create')assertCreatableRunId(definition?.identity);
179
219
  if(supersedeReason!==null&&mode!=='create')fail('supersede_unavailable');
220
+ if(allowAbandonEffect&&mode!=='resume')fail('effect_abandon_unavailable');
221
+ if(typeof holdRevision!=='boolean')fail('invalid_input');
222
+ if(specRebindReason!==null&&(mode!=='resume'||execution===null||typeof specRebindReason!=='string'||!specRebindReason.trim()
223
+ ||Buffer.byteLength(specRebindReason,'utf8')>500||/[\r\n\0]/.test(specRebindReason)))fail('spec_rebind_unavailable');
224
+ if(typeof acceptSupersededCodeDrift!=='boolean'||acceptSupersededCodeDrift&&supersedeReason===null)
225
+ fail('supersede_unavailable');
180
226
  if(qaConfigRevision!==null&&(mode!=='resume'||!execution?.qaExecutor||rerunUnknownQa||rerunBlockedQa
181
227
  ||typeof qaConfigRevision.reason!=='string'||!qaConfigRevision.reason.trim()||qaConfigRevision.reason.length>500
182
228
  ||/[\r\n\0]/.test(qaConfigRevision.reason)||!qaConfigRevision.previousWorkflow))fail('qa_revision_authorization_required');
@@ -184,7 +230,7 @@ export async function openControlRun(definition,mode,execution=null,{rerunUnknow
184
230
  ||(rerunUnknownQa||rerunBlockedQa)&&(mode!=='resume'||!execution?.qaExecutor))fail('qa_recovery_authorization_required');
185
231
  const {openTaskExecutionStore}=await import('../runtime/js/cm-ai/task-owner.mjs');
186
232
  const {createCmAiHost}=await import('../runtime/js/cm-ai/host.mjs');
187
- const {inspectCmAiAdmission,matchesCmAiTaskSelection}=await import('../runtime/js/cm-ai/cm-ai-admission.mjs');
233
+ const {inspectCmAiAdmission,matchesCmAiTaskSelection,explainCmAiTaskSelection}=await import('../runtime/js/cm-ai/cm-ai-admission.mjs');
188
234
  const {captureReviewBaseline}=await import('../runtime/js/cm-ai/review-package.mjs');
189
235
  if(execution!==null){
190
236
  const {shape,json,validCallTimeout}=await import('../runtime/js/cm-ai/effect-contract.mjs');
@@ -214,89 +260,120 @@ export async function openControlRun(definition,mode,execution=null,{rerunUnknow
214
260
  const featureSlug=feature.replace(/^\d+\./,'');
215
261
  const reviewsDir=path.join(specsDir,'.reviews');
216
262
  const supersession=mode==='create'&&supersedeReason!==null
217
- ?prepareReviewedEvidenceSupersession({specsDir,codeProject,feature,identity,reason:supersedeReason,tasksPath}):null;
263
+ ?prepareReviewedEvidenceSupersession({specsDir,codeProject,feature,identity,reason:supersedeReason,tasksPath,
264
+ acceptSupersededCodeDrift}):null;
218
265
  let bootstrapConfig=null;
219
266
  if(execution?.bootstrap){
220
267
  const {bootstrapConfiguration}=await import('../runtime/js/cm-ai/host-bootstrap.mjs');
221
268
  bootstrapConfig=bootstrapConfiguration(execution.bootstrap,{root:codeProject,identity,scope,feature});
222
269
  }
223
270
  if(parallelSelection!==null)parallelSelection=JSON.parse(JSON.stringify(parallelSelection));
271
+ if(parallelSelection!==null&&definition.taskSelection)fail('task_selection_mismatch');
272
+ const selection=parallelSelection??definition.taskSelection??null;
224
273
  const selectedRoots=definition.codeProjects?codeProjectPaths(codeProject,resolveCodeProjects(codeProject,definition.codeProjects)):null;
225
274
  if(selectedRoots){
226
275
  if(!execution||conversationProtection(execution)===null)fail('multi_root_protection_required');
227
276
  for(const root of definition.codeProjects){
228
277
  const selected=inspectCmAiAdmission({specsDir,codeProject:root});
229
- if(mode==='create'&&!matchesCmAiTaskSelection(selected,feature,identity.taskId,parallelSelection))
278
+ if(mode==='create'&&!matchesCmAiTaskSelection(selected,feature,identity.taskId,selection))
230
279
  return {blocked:selected,close:()=>{}};
231
280
  }
232
281
  }
233
282
  const developer=execution?.documentationSync
234
283
  ?(await import('../runtime/js/cm-ai/host-documentation.mjs')).withHostDocumentation({developer:execution.developer,
235
- documentationSync:execution.documentationSync,specsDir,codeProject,feature,scope,parallelSelection}):execution?.developer;
284
+ documentationSync:execution.documentationSync,specsDir,codeProject,feature,scope,parallelSelection:selection}):execution?.developer;
236
285
  const admission=inspectCmAiAdmission({specsDir,codeProject});
237
286
  if(mode==='create'&&admission.state!=='ready')return {blocked:admission,close:()=>{}};
238
- if(mode==='create'&&!matchesCmAiTaskSelection(admission,feature,identity.taskId,parallelSelection))fail('task_selection_mismatch');
287
+ if(mode==='create'&&!matchesCmAiTaskSelection(admission,feature,identity.taskId,selection))
288
+ throw Object.assign(new Error('task_selection_mismatch'),{code:'task_selection_mismatch',
289
+ reason:explainCmAiTaskSelection(admission,{feature,taskId:identity.taskId,selection})});
239
290
  const handoffs=[1,2].map(attempt=>path.join(reviewsDir,`${featureSlug}-${identity.taskId}-a${attempt}-handoff.json`));
291
+ if(mode==='create'&&supersession===null){
292
+ for(const [index,handoff] of handoffs.entries()){
293
+ if(fs.existsSync(handoff)&&reviewConsumedHandoff(reviewsDir,path.basename(handoff),index+1))reviewedHandoffConflict();
294
+ }
295
+ assertNoUnrecordedPriorCode({specsDir,codeProject,feature,identity,tasksPath});
296
+ }
240
297
  // Reuse the runner's real validator before creating durable state. A failed
241
298
  // baseline must not strand an otherwise unused run ID.
242
299
  const specification={specsRoot:specsDir,feature};
243
300
  const baselineOptions={root:codeProject,specsRoot:specsDir,identity,scope,requirements,specification,
244
301
  ...(bootstrapConfig?{bootstrapRequirements:bootstrapConfig.bootstrapRequirements}:{}),
245
302
  ...(selectedRoots?{codeProjectPaths:selectedRoots}:{})};
246
- if(mode==='create')captureReviewBaseline(baselineOptions);
247
- // Definition is data, never an import path, command, grant or executable callback.
248
- const configMaterial=execution===null?(parallelSelection===null?definition:{definition,parallelSelection}):{definition,...(parallelSelection===null?{}:{parallelSelection}),execution:execution.configuration,
249
- ...(bootstrapConfig?{bootstrap:bootstrapConfig}:{}),
250
- ...(Object.hasOwn(execution,'developmentAttempt')?{developmentAuthorization:'per-attempt-v1'}:{}),
251
- ...(execution.hostDecisionProvider?{hostDecisionProvider:{version:1,timeoutMs:execution.hostDecisionProvider.timeoutMs}}:{}),
252
- ...(execution.qaDecisionProvider?{qaDecisionProvider:'host-v1',qaTimeoutMs:execution.qaDecisionProvider.timeoutMs}:{}),
253
- ...(execution.qaExecutor?{qaExecutor:{version:1,mode:execution.qaExecutor.mode,
254
- caseCount:execution.qaExecutor.caseCount,timeoutMs:execution.qaExecutor.timeoutMs,
255
- ...(Object.hasOwn(execution.qaExecutor,'configuration')?{configuration:execution.qaExecutor.configuration}:{})}}:{}),
256
- ...(execution.applicableAgentFiles?{applicableAgentFiles:execution.applicableAgentFiles}:{}),
257
- ...(execution.documentationProvider?{documentationProvider:{version:1,timeoutMs:execution.documentationProvider.timeoutMs}}:{}),
258
- ...(execution.documentationResult?{documentationResult:execution.documentationResult}:{}),
259
- ...(execution.documentationSync?{documentationSync:{version:1,paths:execution.documentationSync.paths}}:{})};
260
- const fingerprints={workflow:sha(execution===null?'cm-ai-control-v1':'cm-ai-host-execution-v1'),
261
- config:sha(configMaterial),inputs:sha({feature,task:identity.taskId})};
262
- const storeOptions={tasksPath,feature:featureSlug,specsRoot:specsDir,
263
- identity:{repositoryId:identity.repositoryId,runId:identity.runId},fingerprints,create:mode==='create'};
264
- let store,attaching=false,priorMaterial=null;
265
- if(qaConfigRevision!==null)priorMaterial=previousQaMaterial(configMaterial,qaConfigRevision.previousWorkflow);
266
- try{store=openTaskExecutionStore(storeOptions);}
267
- catch(error){
268
- if(mode!=='resume'||error.code!=='fingerprint_mismatch')throw error;
269
- const snapshot=readExecutionSnapshot({specsRoot:specsDir,identity:storeOptions.identity});
270
- const last=qaRevisionChain(snapshot).revisions.at(-1);
271
- if(priorMaterial&&last?.toFingerprint===fingerprints.config&&last.fromFingerprint===sha(priorMaterial)
272
- &&last.reason===qaConfigRevision.reason)priorMaterial=null;
273
- if(priorMaterial||snapshot.records.some(row=>row.payload.type==='qa-config-revised')){
274
- verifyQaRevisionMaterial(snapshot,configMaterial,priorMaterial);
275
- store=openTaskExecutionStore({...storeOptions,fingerprints:{...fingerprints,config:snapshot.fingerprints.config}});
303
+ if(mode==='create'){
304
+ // The baseline is journaled as one record. One that cannot fit even on its own
305
+ // is refused here, before any store exists; the runner checks the exact record.
306
+ const preview=captureReviewBaseline(baselineOptions),bytes=Buffer.byteLength(JSON.stringify(preview));
307
+ if(bytes>JOURNAL_PAYLOAD_LIMIT){
308
+ const largest=preview.files.filter(file=>Object.hasOwn(file,'contentBase64')).sort((a,b)=>b.size-a.size).slice(0,3)
309
+ .map(file=>`${file.path} ${file.size} bytes`);
310
+ throw Object.assign(new Error(boundedReason(`limit_exceeded: the task baseline alone is ${bytes} bytes, above the journal record limit `
311
+ +`${JOURNAL_PAYLOAD_LIMIT}; largest baseline material: `,largest)),{code:'limit_exceeded'});
276
312
  }
277
- if(!store){
278
- for(const previous of preQaConfigurations(configMaterial)){
279
- try{store=openTaskExecutionStore({...storeOptions,fingerprints:{...fingerprints,config:sha(previous)}});break;}
280
- catch(cause){if(cause.code!=='fingerprint_mismatch')throw cause;}
313
+ }
314
+ const storeIdentity={repositoryId:identity.repositoryId,runId:identity.runId};
315
+ // Every fingerprint check below runs against one candidate material and
316
+ // closes its store before the next candidate is tried.
317
+ const openFor=material=>{
318
+ const fingerprints={workflow:sha(execution===null?'cm-ai-control-v1':'cm-ai-host-execution-v1'),
319
+ config:sha(material),inputs:sha({feature,task:identity.taskId})};
320
+ const storeOptions={tasksPath,feature:featureSlug,specsRoot:specsDir,identity:storeIdentity,fingerprints,create:mode==='create'};
321
+ let store,attaching=false,priorMaterial=null;
322
+ if(qaConfigRevision!==null)priorMaterial=previousQaMaterial(material,qaConfigRevision.previousWorkflow);
323
+ try{store=openTaskExecutionStore(storeOptions);}
324
+ catch(error){
325
+ if(mode!=='resume'||error.code!=='fingerprint_mismatch')throw error;
326
+ const snapshot=readExecutionSnapshot({specsRoot:specsDir,identity:storeIdentity});
327
+ const last=qaRevisionChain(snapshot).revisions.at(-1);
328
+ if(priorMaterial&&last?.toFingerprint===fingerprints.config&&last.fromFingerprint===sha(priorMaterial)
329
+ &&last.reason===qaConfigRevision.reason)priorMaterial=null;
330
+ if(priorMaterial||snapshot.records.some(row=>row.payload.type==='qa-config-revised')){
331
+ verifyQaRevisionMaterial(snapshot,material,priorMaterial);
332
+ store=openTaskExecutionStore({...storeOptions,fingerprints:{...fingerprints,config:snapshot.fingerprints.config}});
333
+ }
334
+ if(!store){
335
+ for(const previous of preQaConfigurations(material)){
336
+ try{store=openTaskExecutionStore({...storeOptions,fingerprints:{...fingerprints,config:sha(previous)}});break;}
337
+ catch(cause){if(cause.code!=='fingerprint_mismatch')throw cause;}
338
+ }
339
+ if(!store){error.reason=explainFingerprintMismatch({snapshot,definition,execution,fingerprints});throw error;}
340
+ attaching=true;
281
341
  }
282
- if(!store)throw error;
283
- attaching=true;
342
+ }
343
+ try{
344
+ const chain=qaRevisionChain(store.snapshot());
345
+ if(chain.revisions.length&&chain.fingerprint!==fingerprints.config&&!priorMaterial)
346
+ throw Object.assign(new Error('fingerprint_mismatch'),{code:'fingerprint_mismatch',
347
+ reason:'QA 配置与最后一次 --revise-qa-config 修订后的配置不同;请用修订后的 --workflow-config 恢复'});
348
+ if(chain.revisions.length||priorMaterial)verifyQaRevisionMaterial(store.snapshot(),material,priorMaterial);
349
+ const attachments=store.snapshot().records.filter(row=>row.payload.type==='qa-attached');
350
+ if(attachments.length>1)fail('qa_attachment_duplicate');
351
+ const attached=attachments.length?readQaAttachment(attachments[0].payload.record):null;
352
+ if(attached&&!chain.revisions.length&&!priorMaterial&&attached.qaFingerprint!==fingerprints.config)
353
+ throw Object.assign(new Error('fingerprint_mismatch'),{code:'fingerprint_mismatch',
354
+ reason:'启动配置与事后附加 QA 时绑定的配置不同;请用附加 QA 时的 --workflow-config 与参数恢复'});
355
+ if(attaching&&store.snapshot().records.length===0)fail('qa_attach_not_completed');
356
+ return {material,fingerprints,store,attaching,priorMaterial,chain,attached};
357
+ }catch(error){store.close();throw error;}
358
+ };
359
+ let opened;
360
+ try{opened=openFor(runConfigMaterial(definition,execution,{parallelSelection,bootstrapConfig}));}
361
+ catch(error){
362
+ // Only resume may fall back, and only to the exact historical QA form.
363
+ if(mode!=='resume'||error.code!=='fingerprint_mismatch'||!hasLegacyQaPlanFingerprint(execution?.qaExecutor))throw error;
364
+ try{opened=openFor(runConfigMaterial(definition,execution,{parallelSelection,bootstrapConfig,legacyQa:true}));}
365
+ catch(cause){
366
+ if(cause.code!=='fingerprint_mismatch')throw cause;
367
+ throw Object.assign(error,{reason:error.reason?`${error.reason}。${LEGACY_QA_FINGERPRINT_REASON}`:LEGACY_QA_FINGERPRINT_REASON});
284
368
  }
285
369
  }
370
+ const {material:configMaterial,fingerprints,store,attaching,priorMaterial,chain,attached}=opened;
286
371
  try{
287
- const chain=qaRevisionChain(store.snapshot());
288
- if(chain.revisions.length&&chain.fingerprint!==fingerprints.config&&!priorMaterial)fail('fingerprint_mismatch');
289
- if(chain.revisions.length||priorMaterial)verifyQaRevisionMaterial(store.snapshot(),configMaterial,priorMaterial);
290
- const attachments=store.snapshot().records.filter(row=>row.payload.type==='qa-attached');
291
- if(attachments.length>1)fail('qa_attachment_duplicate');
292
- const attached=attachments.length?readQaAttachment(attachments[0].payload.record):null;
293
- if(attached&&!chain.revisions.length&&!priorMaterial&&attached.qaFingerprint!==fingerprints.config)fail('fingerprint_mismatch');
294
- if(attaching&&store.snapshot().records.length===0)fail('qa_attach_not_completed');
295
372
  let runnerMode=mode;
296
373
  if(mode==='resume'&&store.snapshot().records.length===0){
297
374
  // Only the genuine, fingerprint-matching empty initializer can be finished.
298
375
  // Never reset/recreate a journal that contains any event.
299
- if(!matchesCmAiTaskSelection(admission,feature,identity.taskId,parallelSelection))
376
+ if(!matchesCmAiTaskSelection(admission,feature,identity.taskId,selection))
300
377
  fail('initialization_admission_required');
301
378
  captureReviewBaseline(baselineOptions);
302
379
  runnerMode='create';
@@ -307,15 +384,29 @@ export async function openControlRun(definition,mode,execution=null,{rerunUnknow
307
384
  developer:{provider:'codex',requestedModel:'unconfigured',contextId:'control-developer',run:unavailable},
308
385
  reviewers:[],check:unavailable,taskCompletion:{reviewsDir,handoffs},taskLearning:{feature},
309
386
  persistence:{store,mode:runnerMode,version:execution===null?2:3},
387
+ ...(execution===null?{}:{providerDevelopment:protectedExecutions.has(execution)
388
+ ||Boolean(execution.configuration.providerDevelopment)}),
310
389
  ...(execution===null?{}:{developer,reviewers:execution.reviewers,
311
390
  ...(execution.bootstrap?{bootstrap:execution.bootstrap}:{}),
312
391
  reviewInvocation:execution.reviewInvocation,check:execution.check,
313
392
  excludedContexts:execution.excludedContexts,timeoutMs:execution.timeoutMs,
314
393
  ...(Object.hasOwn(execution,'verificationGate')?{verificationGate:execution.verificationGate}:{}),
315
394
  taskLearning:{feature,hostHandoff:true}})},
316
- entry:{specsDir,codeProject,feature,identity,rerunUnknownQa,rerunBlockedQa,...(parallelSelection===null?{}:{parallelSelection}),...(execution===null?{}:{hostDecision:execution.hostDecision,
395
+ // The entry validates the declaration (single line, with --rerun-blocked-qa) before any durable write.
396
+ entry:{specsDir,codeProject,feature,identity,rerunUnknownQa,rerunBlockedQa,...(qaEnvironmentFailure===null?{}:{qaEnvironmentFailure}),allowAbandonReview,allowAbandonEffect,...(holdRevision?{holdRevision}:{}),...(selection===null?{}:{parallelSelection:selection}),...(execution===null?{}:{hostDecision:execution.hostDecision,
317
397
  ...Object.fromEntries(['developmentAttempt','hostDecisionProvider','qaDecisionProvider','qaLogHome','qaExecutor','applicableAgentFiles','documentationProvider','documentationResult'].filter(key=>Object.hasOwn(execution,key)).map(key=>[key,execution[key]]))})},
318
398
  });
399
+ const logAbandonments=()=>{
400
+ for(const record of store.snapshot().records.filter(row=>row.payload.type==='review-invocation-abandoned'))
401
+ recordReviewAbandonment({specsDir,codeProject,feature,identity,record,
402
+ runtime:execution?.reviewers?.[0]?.provider??'codex',
403
+ ...(execution?.qaLogHome?{logHome:execution.qaLogHome}:{})});
404
+ for(const record of store.snapshot().records.filter(row=>row.payload.type==='effect-abandoned'))
405
+ recordEffectAbandonment({specsDir,codeProject,feature,identity,record,
406
+ runtime:execution?.developer?.provider??'codex',
407
+ ...(execution?.qaLogHome?{logHome:execution.qaLogHome}:{})});
408
+ };
409
+ if(mode==='resume')logAbandonments();
319
410
  const recorded=store.snapshot().records.find(row=>row.payload.type==='evidence-superseded')?.payload.record??null;
320
411
  if(supersession!==null||recorded!==null){
321
412
  const record=host.supersedeEvidence(supersession??recorded);
@@ -335,16 +426,23 @@ export async function openControlRun(definition,mode,execution=null,{rerunUnknow
335
426
  ...(execution?.qaLogHome?{logHome:execution.qaLogHome}:{})};
336
427
  // Repair a crash after the journal append, before the log supersession.
337
428
  for(const record of chain.revisions)recordCmAiQaConfigurationRevision({...qaBinding,identity:{...identity,attempt:record.taskAttempt},packageDigest:record.packageDigest},record);
429
+ if(specRebindReason!==null){
430
+ // Consumed once on this launch; the journal record is the audit trail.
431
+ host.rebindSpecification({version:1,reason:specRebindReason,at:new Date().toISOString()});
432
+ }
338
433
  if(priorMaterial){
339
434
  if(sha(priorMaterial)===fingerprints.config)fail('qa_revision_unchanged');
340
435
  const current=await host.handle({version:1,operation:'status',requestId:'qa-revision-status',identity});
341
- if(current.state!=='fixture_completed'||current.code!==null)fail('qa_revision_not_completed');
436
+ // No QA round of this run has started: record a round-0 revision that
437
+ // supersedes nothing and consumes no round. The runner re-checks state.
438
+ const beforeQa=!hasCmAiQaRun({specsDir,feature,identity:current.identity});
439
+ if(!beforeQa&&(current.state!=='fixture_completed'||current.code!==null))fail('qa_revision_not_completed');
342
440
  const binding={...qaBinding,identity:current.identity,packageDigest:current.packageDigest};
343
- const target=inspectCmAiQaRevisionTarget(binding);
441
+ const target=beforeQa?{testRunId:null,qaRound:0}:inspectCmAiQaRevisionTarget(binding);
344
442
  const record=host.reviseQa({version:1,fromFingerprint:sha(priorMaterial),toFingerprint:fingerprints.config,
345
443
  invariantDigest:qaInvariantDigest(configMaterial),previousQaDigest:sha(qaConfigurationSlice(priorMaterial)),qaDigest:sha(qaConfigurationSlice(configMaterial)),
346
444
  reason:qaConfigRevision.reason,hostContextId:execution.configuration.hostContextId,
347
- revisedAt:new Date().toISOString().replace(/\.\d{3}Z$/,'Z'),packageDigest:current.packageDigest,
445
+ revisedAt:new Date().toISOString().replace(/\.\d{3}Z$/,'Z'),packageDigest:current.packageDigest??null,
348
446
  testRunId:target.testRunId,qaRound:target.qaRound,taskAttempt:current.identity.attempt});
349
447
  recordCmAiQaConfigurationRevision(binding,record);
350
448
  }
@@ -353,7 +451,9 @@ export async function openControlRun(definition,mode,execution=null,{rerunUnknow
353
451
  // Do not imply an unavailable execution adapter was dispatched.
354
452
  return {outcome:'blocked',code:'execution_adapter_required',providerCalls:0};
355
453
  }
356
- return host.handle(request);
454
+ const result=await host.handle(request);
455
+ if(['abandon_review','abandon_effect'].includes(request.operation)&&result.outcome==='abandoned')logAbandonments();
456
+ return result;
357
457
  }},inspectFixAssociation:host.inspectFixAssociation,acceptCompletedFix:host.acceptCompletedFix,
358
458
  checkpoint:()=>store.snapshot().revision,close:()=>store.close()};
359
459
  }catch(error){store.close();throw error;}
@@ -78,8 +78,9 @@ test(`trusted host execution uses the same entry and sole gate: ${mode} nested=$
78
78
  fs.writeFileSync(path.join(f.codeProject,'.git'),'gitdir: /nonexistent/cm-synthetic-worktree-metadata\n');
79
79
  let stdout='',stderr='',calls=0,reviews=0;output.on('data',x=>stdout+=x);error.on('data',x=>stderr+=x);
80
80
  const execution={configuration:{kind:'synthetic-host-v1'},timeoutMs:2000,excludedContexts:['main'],
81
- developer:{provider:'codex',requestedModel:'fixture',contextId:'dev',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async()=>{
82
- calls++;fs.writeFileSync(path.join(f.codeProject,'a.js'),'new\n');
81
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'dev',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async({prompt})=>{
82
+ // Attempt 2 must change the rejected bytes (develop_unchanged_after_review).
83
+ calls++;fs.writeFileSync(path.join(f.codeProject,'a.js'),JSON.parse(prompt.split('<cm-developer-data-json>\n')[1]).identity.attempt===1?'new\n':'new 2\n');
83
84
  return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
84
85
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
85
86
  }})},
@@ -114,7 +115,7 @@ test(`trusted host execution uses the same entry and sole gate: ${mode} nested=$
114
115
  }},
115
116
  hostDecision:mode==='awaiting'?null:['approved','blocked','repair','review_limit','spec_drift'].includes(mode)?{status:'approved'}:{status:'denied',code:'permission_denied'},
116
117
  check:createHostCheck({cwd:f.codeProject,commands:[{id:'content',command:[process.execPath,'-e',
117
- "require('node:assert/strict').equal(require('node:fs').readFileSync('a.js','utf8'),'new\\n')"]}]})};
118
+ "require('node:assert/strict').match(require('node:fs').readFileSync('a.js','utf8'),/^new( 2)?\\n$/)"]}]})};
118
119
  let qaCalls=0,qaRuns=0,docInspections=0,docWrites=0,reviewDecisions=0;
119
120
  const dynamicQa=mode==='approved'&&!nested;
120
121
  const dynamicReview=dynamicQa||mode==='repair';
@@ -4,6 +4,13 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {createTaskRunner} from '../runtime/js/cm-ai/task-runner.mjs';
7
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
8
+ import {withHandoffDiagnostic} from './cm-ai-host.mjs';
9
+ import {controlledState,stageAllowed,completedEffectCount,runnerStatus,readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
10
+ import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
11
+ import {digest,requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+ import {reviewPaths,reviewReceipt} from '../runtime/js/cm-ai/review-runner.mjs';
13
+ import {createReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
7
14
 
8
15
  test('adapter exception code getter cannot escape the runner failure boundary',async t=>{
9
16
  const root=fs.mkdtempSync(path.join(os.tmpdir(),'cm-runner-error-code-'));
@@ -27,3 +34,215 @@ test('adapter exception code getter cannot escape the runner failure boundary',a
27
34
  assert.equal(result.code,'execution_error');
28
35
  assert.equal(getterReads,0);
29
36
  });
37
+
38
+ test('check-created untracked output blocks with paths and retries in the same run',async t=>{
39
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-output-')));
40
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
41
+ fs.writeFileSync(path.join(root,'code.js'),'old');
42
+ fs.writeFileSync(path.join(root,'requirements.md'),'fixture');
43
+ const identity={repositoryId:'fixture',runId:'check-output',taskId:'T-001',attempt:1};
44
+ let checks=0;
45
+ const hostCheck=createHostCheck({cwd:root,commands:[{id:'build',command:[process.execPath,'-e',
46
+ "require('node:fs').mkdirSync('build',{recursive:true});require('node:fs').writeFileSync('build/product','x')"]}]});
47
+ const runner=createTaskRunner({root,identity,scope:['code.js'],requirements:['requirements.md'],
48
+ excludedContexts:['main'],timeoutMs:5000,
49
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:request=>{
50
+ fs.writeFileSync(path.join(root,'code.js'),'new');
51
+ return {version:1,invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
52
+ effectiveModel:'fixture',status:'succeeded',accepted:true,result:{outcome:'implemented'}};
53
+ }},
54
+ reviewers:[{id:'reviewer',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
55
+ contexts:['review-one','review-two'],run:()=>{throw new Error('must not review');}}],
56
+ check:async(...args)=>{checks++;return checks===1?hostCheck(...args):
57
+ [{id:'build',command:['fixture'],outcome:'passed',exitCode:0,evidence:'fixture'}];},
58
+ commit:()=>{throw new Error('must not commit');}});
59
+ const first=await runner.executeEffect({version:1,id:'develop-1',identity,kind:'develop'});
60
+ assert.equal(first.state,'blocked');assert.equal(first.code,'check_output_out_of_scope');
61
+ assert.equal(runner.verificationBlocks(),1);
62
+ assert.match(first.reason,/build\/product/);assert(!first.reason.includes(root));
63
+ fs.rmSync(path.join(root,'build'),{recursive:true});
64
+ const second=await runner.executeEffect({version:1,id:'develop-2',identity,kind:'develop'});
65
+ assert.equal(second.state,'awaiting_review');assert.equal(second.code,null);
66
+ assert.equal(checks,2);
67
+ });
68
+
69
+ test('developer-created out of scope file remains unknown with a path diagnostic',async t=>{
70
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-developer-outscope-')));
71
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
72
+ fs.writeFileSync(path.join(root,'code.js'),'old');fs.writeFileSync(path.join(root,'requirements.md'),'fixture');
73
+ const identity={repositoryId:'fixture',runId:'developer-outscope',taskId:'T-001',attempt:1};
74
+ const runner=createTaskRunner({root,identity,scope:['code.js'],requirements:['requirements.md'],
75
+ excludedContexts:['main'],timeoutMs:5000,
76
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:request=>{
77
+ fs.writeFileSync(path.join(root,'code.js'),'new');fs.writeFileSync(path.join(root,'unexpected.js'),'developer');
78
+ return {version:1,invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
79
+ effectiveModel:'fixture',status:'succeeded',accepted:true,result:{outcome:'implemented'}};
80
+ }},
81
+ reviewers:[{id:'reviewer',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
82
+ contexts:['review-one','review-two'],run:()=>{throw new Error('must not review');}}],
83
+ check:async()=>[{id:'unit',command:['fixture'],outcome:'passed',exitCode:0,evidence:'fixture'}],
84
+ commit:()=>{throw new Error('must not commit');}});
85
+ const result=await runner.executeEffect({version:1,id:'develop-1',identity,kind:'develop'});
86
+ assert.equal(result.state,'unknown');assert.equal(result.code,'out_of_scope');
87
+ assert.match(result.reason,/unexpected\.js/);assert(!result.reason.includes(root));
88
+ });
89
+
90
+ test('host stderr repeats the bounded relative scope diagnostic',async()=>{
91
+ let stderr='';
92
+ const host=withHandoffDiagnostic({handle:async()=>({state:'blocked',code:'check_output_out_of_scope',
93
+ reason:'out_of_scope: build/product'})},{write:text=>{stderr+=text;}});
94
+ const result=await host.handle({operation:'status'});
95
+ assert.equal(result.reason,'out_of_scope: build/product');
96
+ assert.match(stderr,/build\/product/);
97
+ });
98
+
99
+ test('a later control error clears stale scope paths from status',()=>{
100
+ const next=controlledState({state:'blocked',code:'check_output_out_of_scope',
101
+ reason:'out_of_scope: build/product',workflowError:null},'workflow-error',false);
102
+ assert.equal(next.code,'workflow_error');
103
+ assert.equal(next.reason,null);
104
+ });
105
+
106
+ test('legacy state without a reason remains readable and check-output retry does not consume the effect cap',()=>{
107
+ const state={state:'blocked',code:'out_of_scope',attempt:1,reviewPackage:null,receipt:null,receipts:[],calls:[],
108
+ cancelAfterCommit:false,workflowError:null,cancellationRequested:false};
109
+ const status=runnerStatus(state,{identity:{repositoryId:'fixture',runId:'legacy',taskId:'T-001',attempt:1}});
110
+ assert.equal(Object.hasOwn(status,'reason'),false);
111
+ assert.equal(stageAllowed('develop','blocked','check_output_out_of_scope'),true);
112
+ assert.equal(completedEffectCount([{effect:{kind:'develop'},result:{state:'blocked',code:'check_output_out_of_scope'}}]),0);
113
+ assert.equal(stageAllowed('develop','blocked','develop_checks_not_passed'),true);
114
+ assert.equal(stageAllowed('develop','blocked','checks_not_passed'),false);
115
+ // Completion holds no effect slot (an approved run can always complete); the
116
+ // legacy completion-gate checks_not_passed stays terminal through its stage.
117
+ assert.equal(completedEffectCount([{effect:{kind:'complete'},result:{state:'blocked',code:'checks_not_passed'}}]),0);
118
+ assert.equal(stageAllowed('complete','blocked','checks_not_passed'),false);
119
+ assert.equal(completedEffectCount([{effect:{kind:'develop'},result:{state:'blocked',code:'develop_checks_not_passed'}}]),1);
120
+ });
121
+
122
+ test('check-output block and reason replay from the stored run before retry',async t=>{
123
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-replay-')));
124
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
125
+ const code=path.join(root,'code'),specs=path.join(root,'specs');
126
+ fs.mkdirSync(code);fs.mkdirSync(path.join(specs,'.reviews'),{recursive:true});
127
+ fs.writeFileSync(path.join(code,'code.js'),'old');fs.writeFileSync(path.join(code,'requirements.md'),'fixture');
128
+ const tasksPath=path.join(specs,'tasks.md');fs.writeFileSync(tasksPath,'- [ ] T-001: fixture\n');
129
+ const identity={repositoryId:'fixture',runId:'check-replay',taskId:'T-001',attempt:1};
130
+ const owner={tasksPath,feature:'feature',specsRoot:specs,identity:{repositoryId:identity.repositoryId,runId:identity.runId},
131
+ fingerprints:{workflow:digest('fixture'),config:digest('fixture-config'),inputs:digest('fixture-input')},create:true};
132
+ let store=openTaskExecutionStore(owner);
133
+ t.after(()=>store.close());
134
+ let checks=0;
135
+ const options={root:code,identity,scope:['code.js'],requirements:['requirements.md'],excludedContexts:['main'],timeoutMs:5000,
136
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:request=>{
137
+ fs.writeFileSync(path.join(code,'code.js'),'new');
138
+ return {version:1,invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
139
+ effectiveModel:'fixture',status:'succeeded',accepted:true,result:{outcome:'implemented'}};
140
+ }},
141
+ reviewers:[{id:'reviewer',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
142
+ contexts:['review-one','review-two'],run:()=>{throw new Error('must not review');}}],
143
+ check:async()=>{
144
+ checks++;
145
+ if(checks===1){fs.mkdirSync(path.join(code,'build'));fs.writeFileSync(path.join(code,'build/product'),'x');}
146
+ return [{id:'unit',command:['fixture'],outcome:'passed',exitCode:0,evidence:'fixture'}];
147
+ },commit:()=>{throw new Error('must not commit');}};
148
+ const first=createTaskRunner({...options,persistence:{store,mode:'create'}});
149
+ const blocked=await first.executeEffect({version:1,id:'develop-1',identity,kind:'develop'});
150
+ assert.equal(blocked.code,'check_output_out_of_scope');
151
+ assert.equal(first.verificationBlocks(),1);
152
+ store.close();store=openTaskExecutionStore({...owner,create:false});
153
+ const resumed=createTaskRunner({...options,persistence:{store,mode:'resume'}});
154
+ assert.equal(resumed.status().reason,blocked.reason);
155
+ assert.equal(resumed.verificationBlocks(),1);
156
+ fs.rmSync(path.join(code,'build'),{recursive:true});
157
+ const next=await resumed.executeEffect({version:1,id:'develop-2',identity,kind:'develop'});
158
+ assert.equal(next.state,'awaiting_review');
159
+ });
160
+
161
+ test('legacy completion checks_not_passed never reopens develop live or after replay',async t=>{
162
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-legacy-complete-')));
163
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
164
+ const code=path.join(root,'code'),specs=path.join(root,'specs');
165
+ fs.mkdirSync(code);fs.mkdirSync(path.join(specs,'.reviews'),{recursive:true});
166
+ fs.writeFileSync(path.join(code,'code.js'),'old');
167
+ fs.writeFileSync(path.join(code,'requirements.md'),'fixture');
168
+ const tasksPath=path.join(specs,'tasks.md');fs.writeFileSync(tasksPath,'- [ ] T-001: fixture\n');
169
+ const identity={repositoryId:'fixture',runId:'legacy-complete',taskId:'T-001',attempt:1};
170
+ const owner={tasksPath,feature:'feature',specsRoot:specs,identity:{repositoryId:identity.repositoryId,runId:identity.runId},
171
+ fingerprints:{workflow:digest('legacy-complete'),config:digest('fixture'),inputs:digest('fixture')},create:true};
172
+ let store=openTaskExecutionStore(owner);
173
+ t.after(()=>store.close());
174
+ let checks=0,developCalls=0;
175
+ const terminal=(request,result)=>({version:1,invocationId:request.invocationId,contextId:request.contextId,
176
+ provider:request.provider,effectiveModel:'fixture',status:'succeeded',accepted:true,result});
177
+ const options={root:code,identity,scope:['code.js'],requirements:['requirements.md'],excludedContexts:['main'],timeoutMs:5000,
178
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:request=>{
179
+ developCalls++;fs.writeFileSync(path.join(code,'code.js'),'new');
180
+ return terminal(request,{outcome:'implemented'});
181
+ }},
182
+ reviewers:[{id:'reviewer',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
183
+ contexts:['review-one','review-two'],run:request=>terminal(request,{verdict:'approved',
184
+ packageDigest:request.payload.reviewPackage.packageDigest,
185
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'fixture review'})}],
186
+ check:()=>{checks++;return [{id:'unit',command:['fixture'],outcome:checks===1?'passed':'failed',
187
+ exitCode:checks===1?0:1,evidence:'fixture'}];},
188
+ commit:()=>{throw new Error('must not commit');}};
189
+ const effect=(kind,id=kind)=>({version:1,id,identity,kind});
190
+ const first=createTaskRunner({...options,persistence:{store,mode:'create'}});
191
+ assert.equal((await first.executeEffect(effect('develop'))).state,'awaiting_review');
192
+ assert.equal((await first.executeEffect(effect('review'))).state,'approved');
193
+ store.close();
194
+
195
+ // A pre-D1 journal could approve a failed-check review package. Rebind its
196
+ // package, request and receipt so replay validates the actual legacy path.
197
+ const statePath=path.join(specs,'.reviews','.execution',identity.runId,'state.json');
198
+ const saved=JSON.parse(fs.readFileSync(statePath,'utf8'));
199
+ const failed=[{id:'unit',command:['fixture'],outcome:'failed',exitCode:1,evidence:'fixture'}];
200
+ const legacyPackage=createReviewPackage({root:code,baseline:saved.records[0].payload.baseline,checks:failed});
201
+ const dev=saved.records.find(record=>record.payload.type==='effect-checkpoint'
202
+ &&record.payload.checkpoint.state==='awaiting_review').payload.checkpoint;
203
+ const approved=saved.records.at(-1).payload.checkpoint;
204
+ dev.reviewPackage=legacyPackage;dev.currentChecks=failed;
205
+ dev.cache.at(-1).result.packageDigest=legacyPackage.packageDigest;
206
+ const reviewCall=approved.calls.at(-1);
207
+ const reviewRequest=requestFor({invocationId:reviewCall.invocationId,identity,role:'reviewer',
208
+ provider:'codex',requestedModel:'fixture',contextId:'review-one',
209
+ payload:{reviewPackage:legacyPackage,priorReview:null}});
210
+ const reviewResult={verdict:'approved',packageDigest:legacyPackage.packageDigest,
211
+ examinedPaths:reviewPaths(legacyPackage),findings:[],summary:'fixture review'};
212
+ reviewCall.requestDigest=reviewRequest.requestDigest;reviewCall.resultDigest=digest(reviewResult);
213
+ const receipt=reviewReceipt({request:reviewRequest,call:reviewCall,result:reviewResult,
214
+ reviewPackage:legacyPackage,developerProvider:'codex',fallbackReasons:[]});
215
+ approved.reviewPackage=legacyPackage;approved.currentChecks=failed;
216
+ approved.receipt=receipt;approved.receipts=[receipt];approved.priorReview=reviewResult;
217
+ approved.cache[0]=structuredClone(dev.cache[0]);
218
+ const reviewed=approved.cache.at(-1).result;
219
+ reviewed.packageDigest=legacyPackage.packageDigest;
220
+ reviewed.receipt=receipt;reviewed.receipts=[receipt];reviewed.calls=approved.calls;
221
+ for(let i=0;i<saved.records.length;i++){
222
+ const {digest:ignored,...record}=saved.records[i];
223
+ record.previousDigest=i?saved.records[i-1].digest:null;
224
+ saved.records[i]={...record,digest:digest(record)};
225
+ }
226
+ const {revision:ignored,...body}=saved;
227
+ fs.writeFileSync(statePath,JSON.stringify({...body,revision:digest(body)})+'\n');
228
+ assert.equal(readRunnerHistory(saved.records,saved.records[0].payload.config).state.state,'approved');
229
+ const reopen=()=>{
230
+ store.close();store=openTaskExecutionStore({...owner,create:false});
231
+ return createTaskRunner({...options,persistence:{store,mode:'resume'}});
232
+ };
233
+ const live=reopen();
234
+ assert.equal(live.status().state,'approved');
235
+ assert.equal(live.status().receipt.checksDigest,digest(failed));
236
+ const blocked=await live.executeEffect(effect('complete'));
237
+ assert.equal(blocked.state,'blocked');assert.equal(blocked.code,'checks_not_passed');
238
+ assert.equal(live.status().code,'checks_not_passed');
239
+ assert.equal(live.verificationBlocks(),0);
240
+ assert.deepEqual(await live.executeEffect(effect('develop','develop-after-complete')),
241
+ {outcome:'rejected',code:'stage_mismatch'});
242
+ assert.equal(developCalls,1);
243
+ const replay=reopen();
244
+ assert.equal(replay.status().code,'checks_not_passed');
245
+ assert.deepEqual(await replay.executeEffect(effect('develop','develop-after-replay')),
246
+ {outcome:'rejected',code:'stage_mismatch'});
247
+ assert.equal(developCalls,1);
248
+ });