@aibyzero/cm-workflow 0.16.4 → 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 (167) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +50 -0
  4. package/README.md +12 -1
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/runtime-failover.md +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  11. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  14. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  16. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  17. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  19. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  20. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  21. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  22. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  24. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  26. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  27. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  28. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  29. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  30. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  31. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  33. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  34. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  35. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  36. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  37. package/runtime/js/cm-ai/host-session.mjs +12 -4
  38. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  42. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  45. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  46. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  47. package/runtime/js/cm-ai/review-package.mjs +427 -31
  48. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  49. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  50. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  51. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  52. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  53. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  54. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  55. package/runtime/js/cm-fix/execution.mjs +109 -25
  56. package/runtime/js/cm-fix/host-review.mjs +7 -3
  57. package/runtime/js/cm-fix/host.mjs +3 -1
  58. package/runtime/js/cm-fix/progress.mjs +1 -0
  59. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  60. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  61. package/runtime/js/cm-prd/analysis.mjs +2 -1
  62. package/runtime/js/cm-prd/change.mjs +28 -10
  63. package/runtime/js/cm-prd/draft.mjs +5 -2
  64. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  65. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  66. package/runtime/js/cm-prd/self-check.mjs +6 -3
  67. package/runtime/js/cm-prd/summary.mjs +3 -1
  68. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  69. package/runtime/js/spec-task-line.mjs +117 -0
  70. package/runtime/js/specs-status.mjs +10 -3
  71. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  72. package/scripts/cm-ai-admission.mjs +18 -11
  73. package/scripts/cm-ai-admission.test.mjs +65 -1
  74. package/scripts/cm-ai-batch-drive.mjs +92 -20
  75. package/scripts/cm-ai-batch-drive.test.mjs +164 -3
  76. package/scripts/cm-ai-batch-host.mjs +27 -11
  77. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  78. package/scripts/cm-ai-batch-run.mjs +33 -10
  79. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  80. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  81. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  82. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  84. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  85. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  86. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  87. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  88. package/scripts/cm-ai-drive.mjs +479 -47
  89. package/scripts/cm-ai-drive.test.mjs +240 -10
  90. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  91. package/scripts/cm-ai-host.mjs +84 -25
  92. package/scripts/cm-ai-host.test.mjs +232 -12
  93. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  94. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  95. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  96. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  97. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  98. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  99. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  100. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  101. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  102. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  103. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  104. package/scripts/cm-ai-run.mjs +160 -60
  105. package/scripts/cm-ai-run.test.mjs +4 -3
  106. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  107. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  108. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  109. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  110. package/scripts/cm-ai-supersede.test.mjs +571 -17
  111. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  112. package/scripts/cm-capability-gate.test.mjs +21 -2
  113. package/scripts/cm-check-drive.test.mjs +1 -1
  114. package/scripts/cm-check-host.test.mjs +1 -1
  115. package/scripts/cm-check-runtime.sh +1 -1
  116. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  117. package/scripts/cm-claude-probe.test.mjs +9 -1
  118. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  119. package/scripts/cm-claude-worker.test.mjs +11 -4
  120. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  121. package/scripts/cm-failover.mjs +8 -8
  122. package/scripts/cm-fix-abandon.test.mjs +123 -5
  123. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  124. package/scripts/cm-fix-drive.mjs +45 -13
  125. package/scripts/cm-fix-drive.test.mjs +36 -1
  126. package/scripts/cm-fix-host.mjs +9 -6
  127. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  128. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  129. package/scripts/cm-host-check.test.mjs +6 -3
  130. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  131. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  132. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  133. package/scripts/cm-log-event.mjs +17 -0
  134. package/scripts/cm-log-event.test.mjs +31 -0
  135. package/scripts/cm-prd-completion.test.mjs +75 -0
  136. package/scripts/cm-prd-draft.test.mjs +14 -0
  137. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  138. package/scripts/cm-prd-review-gate.mjs +126 -81
  139. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  140. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  141. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  142. package/scripts/cm-prd-self-check.test.mjs +6 -0
  143. package/scripts/cm-prd-summary.test.mjs +9 -0
  144. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  145. package/scripts/cm-review-inventory.test.mjs +253 -1
  146. package/scripts/cm-spec-manifest.mjs +28 -10
  147. package/scripts/cm-spec-manifest.test.mjs +8 -4
  148. package/scripts/cm-spec-task-line.test.mjs +138 -0
  149. package/scripts/cm-specs-status.test.mjs +12 -1
  150. package/scripts/cm-task-gate.mjs +18 -10
  151. package/scripts/cm-task-gate.py +1 -1
  152. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  153. package/scripts/fixtures/claude-review-process.mjs +1 -0
  154. package/scripts/fixtures/process-cleanup.mjs +99 -0
  155. package/scripts/test-cm-log-event.py +2 -0
  156. package/scripts/test-cm-prd-review-gate.py +2 -1
  157. package/scripts/test-npm-install.py +1 -1
  158. package/scripts/test-scan-public-safety.py +1 -1
  159. package/scripts/test-spec-manifest.py +16 -8
  160. package/scripts/test-task-gate.py +2 -2
  161. package/scripts/test-workflow-config.py +1 -0
  162. package/scripts/validate-public-repo.py +1 -0
  163. package/skills/cm-ai/references/N1-init.md +1 -1
  164. package/skills/cm-ai/references/js-host.md +261 -42
  165. package/skills/cm-fix/references/js-host.md +22 -1
  166. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  167. package/skills/cm-prd/references/js-host.md +6 -0
@@ -60,6 +60,18 @@ function stepRecord(id){
60
60
  }
61
61
  const retryBase=id=>id.replace(/-retry-[1-8]-(intent|result)$/,'-$1');
62
62
  const latestStepRecord=(records,id)=>[...records].reverse().find(row=>retryBase(row.id)===id);
63
+ // A cause or second-round final review that produced no review result may be
64
+ // abandoned once, audited, and dispatched again under its own record prefix.
65
+ const REVIEW_ABANDON={cause_review:'fix-cause',revision_final_review:'fix-revision-final'};
66
+ const reviewCycleRecord=(records,prefix,suffix)=>records.some(row=>row.id===`${prefix}-abandoned`)
67
+ ?records.find(row=>row.id===`${prefix}-retry-${suffix}`):records.find(row=>row.id===`${prefix}-${suffix}`);
68
+ // Reviews wait for their own budget (host review configuration), never for the
69
+ // reproduction command's. Embedders that supply none keep the historical budget.
70
+ function reviewTimeout(adapter,fallback){
71
+ if(adapter?.timeoutMs===undefined)return fallback;
72
+ need(Number.isInteger(adapter.timeoutMs)&&adapter.timeoutMs>=1&&adapter.timeoutMs<=3600000,'invalid_review_config');
73
+ return adapter.timeoutMs;
74
+ }
63
75
 
64
76
  function diagnosis(raw){
65
77
  const value=json(raw,32*1024);
@@ -192,14 +204,14 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
192
204
  const publishCause=(inspectOnly=false)=>{
193
205
  const records=store.snapshot().records;
194
206
  return publishCauseEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,
195
- registration:records.find(record=>record.id==='fix-cause-registered')?.payload,
196
- started:records.find(record=>record.id==='fix-cause-started')?.payload.providerThreadId??null,
197
- result:records.find(record=>record.id==='fix-cause-result')?.payload});
207
+ registration:reviewCycleRecord(records,'fix-cause','registered')?.payload,
208
+ started:reviewCycleRecord(records,'fix-cause','started')?.payload.providerThreadId??null,
209
+ result:reviewCycleRecord(records,'fix-cause','result')?.payload});
198
210
  };
199
211
  const publishFinal=(inspectOnly=false)=>{
200
212
  const records=store.snapshot().records;
201
213
  return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,
202
- causeThread:records.find(record=>record.id==='fix-cause-started')?.payload.providerThreadId??null,
214
+ causeThread:reviewCycleRecord(records,'fix-cause','started')?.payload.providerThreadId??null,
203
215
  registration:finalRecord(records,'registered')?.payload,
204
216
  started:finalRecord(records,'started')?.payload.providerThreadId??null,
205
217
  result:finalRecord(records,'result')?.payload});
@@ -208,7 +220,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
208
220
  const records=store.snapshot().records;
209
221
  const failed=latestStepRecord(records,'fix-walkthrough-result')?.payload;
210
222
  const regression=latestStepRecord(records,'fix-post-regression-result')?.payload;
211
- return {configuration:fixFinalReviewConfiguration(reviewConfiguration,records.find(row=>row.id==='fix-cause-started')?.payload.providerThreadId??null),
223
+ return {configuration:fixFinalReviewConfiguration(reviewConfiguration,reviewCycleRecord(records,'fix-cause','started')?.payload.providerThreadId??null),
212
224
  registration:finalRecord(records,'registered')?.payload,
213
225
  started:finalRecord(records,'started')?.payload.providerThreadId??null,
214
226
  result:finalRecord(records,'result')?.payload,
@@ -222,9 +234,9 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
222
234
  const publishRevisionFinal=(inspectOnly=false)=>{
223
235
  const records=store.snapshot().records;
224
236
  return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,reviewFeedback:revisionFeedback(),
225
- registration:records.find(row=>row.id==='fix-revision-final-registered')?.payload,
226
- started:records.find(row=>row.id==='fix-revision-final-started')?.payload.providerThreadId??null,
227
- result:records.find(row=>row.id==='fix-revision-final-result')?.payload});
237
+ registration:reviewCycleRecord(records,'fix-revision-final','registered')?.payload,
238
+ started:reviewCycleRecord(records,'fix-revision-final','started')?.payload.providerThreadId??null,
239
+ result:reviewCycleRecord(records,'fix-revision-final','result')?.payload});
228
240
  };
229
241
  const reviewBaseline=()=>{
230
242
  const records=store.snapshot().records;
@@ -359,6 +371,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
359
371
  let repairBaseline=null,repaired=null;
360
372
  let regression=null,retrospective=null,retrospectivePackage=null,writeback=null,learningPackage=null,handoff=null;
361
373
  let finalRegistration=null,finalStarted=null,finalResult=null,finalRecovery=null,finalRecoveryCount=0;
374
+ let causeOrigin=null,causeResultPayload=null,causeAbandonment=null,revisionFinalResultPayload=null,revisionAbandonment=null;
362
375
  const finalInvocations=new Set(),finalThreads=new Set();
363
376
  let joinedCount=0;const seenJoined=new Set();
364
377
  let n5=null,postReviewRegression=null,walkthrough=null,revision=null,revisionBaseline=null,revisionRepair=null,revisionRegression=null;
@@ -428,6 +441,13 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
428
441
  need(finalRecovery&&record.id===`${recoveryPrefix(finalRecoveryCount)}-${suffix}`,'fix_history_invalid');
429
442
  record={...record,id:`fix-final-${suffix}`};
430
443
  }else if(/^fix-final-(registered|started|result)$/.test(record.id))need(!finalRecovery,'fix_history_invalid');
444
+ // After a one-time abandonment only the retry cycle's records are valid.
445
+ const reviewRetry=/^(fix-cause|fix-revision-final)-retry-(registered|started|result)$/.exec(record.id);
446
+ if(reviewRetry){
447
+ need((reviewRetry[1]==='fix-cause'?causeAbandonment:revisionAbandonment)!==null,'fix_history_invalid');
448
+ record={...record,id:`${reviewRetry[1]}-${reviewRetry[2]}`};
449
+ }else if(/^fix-cause-(registered|started|result)$/.test(record.id))need(causeAbandonment===null,'fix_history_invalid');
450
+ else if(/^fix-revision-final-(registered|started|result)$/.test(record.id))need(revisionAbandonment===null,'fix_history_invalid');
431
451
  const observed=/^fix-observation-(?:(\d+)-)?(resume-prepared|reproduce-intent|reproduce-result|diagnose-intent|diagnose-result)$/.exec(record.id);
432
452
  if(observed){
433
453
  const cycle=observed[2]==='resume-prepared'?observationCycle+1:observationCycle;
@@ -639,6 +659,27 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
639
659
  need(record.payload.outcome==='created'&&record.payload.status==='ready_for_review'&&/^[a-f0-9]{64}$/.test(record.payload.handoffSha256),'invalid_handoff_result');
640
660
  revisionHandoff=record.payload;pending=null;stage='revision_final_review_required';continue;
641
661
  }
662
+ if(record.id==='fix-cause-abandoned'||record.id==='fix-revision-final-abandoned'){
663
+ const causeKind=record.id==='fix-cause-abandoned';
664
+ const registration=causeKind?cause:revisionFinalRegistration,result=causeKind?causeResult:revisionFinalResult;
665
+ need(record.kind==='result'&&(causeKind?causeAbandonment:revisionAbandonment)===null&&registration&&stage==='unknown'
666
+ &&(pending===(causeKind?'cause_review':'revision_final_review')&&!result
667
+ ||pending===null&&result&&result.observationStatus!=='completed'),'fix_history_invalid');
668
+ const value=record.payload,resultPayload=causeKind?causeResultPayload:revisionFinalResultPayload;
669
+ shape(value,['invocationId','registrationDigest','providerThreadId','resultDigest','reason','abandonedAt']);
670
+ need(value.invocationId===registration.request.invocationId&&value.registrationDigest===digest(registration)
671
+ &&value.providerThreadId===(causeKind?started:revisionFinalStarted)
672
+ &&value.resultDigest===(resultPayload===null?null:digest(resultPayload)),'fix_review_abandon_mismatch');
673
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=1000
674
+ &&!/[\r\n\0\u0085\u2028\u2029]/.test(value.reason)&&Number.isSafeInteger(value.abandonedAt)&&value.abandonedAt>0,'fix_history_invalid');
675
+ if(causeKind){
676
+ causeAbandonment=value;stage=causeOrigin;cause=null;started=null;causeResult=null;causeResultPayload=null;causeResumeStage=null;
677
+ }else{
678
+ revisionAbandonment=value;stage='revision_final_review_required';
679
+ revisionFinalRegistration=null;revisionFinalStarted=null;revisionFinalResult=null;revisionFinalResultPayload=null;
680
+ }
681
+ pending=null;continue;
682
+ }
642
683
  if(record.id==='fix-revision-final-registered'){
643
684
  need(revision&&stage==='revision_final_review_required'&&record.kind==='intent','fix_history_invalid');
644
685
  revisionFinalRegistration=inspectFixFinalRegistration(record.payload,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds));
@@ -651,6 +692,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
651
692
  need(revision&&pending==='revision_final_review'&&revisionFinalStarted===null&&record.kind==='result','fix_history_invalid');
652
693
  need(record.payload.providerThreadId!==finalRecovery?.providerThreadId,'final_context_mismatch');
653
694
  shape(record.payload,['providerThreadId']);id(record.payload.providerThreadId);
695
+ need(record.payload.providerThreadId!==revisionAbandonment?.providerThreadId,'final_context_mismatch');
654
696
  const config=fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds);
655
697
  need(![...fixHostContexts(config),config.reviewer.contextId,...config.reviewer.excludedThreadIds].includes(record.payload.providerThreadId),'final_context_mismatch');
656
698
  revisionFinalStarted=record.payload.providerThreadId;continue;
@@ -658,7 +700,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
658
700
  if(record.id==='fix-revision-final-result'){
659
701
  need(revision&&pending==='revision_final_review'&&record.kind==='result','fix_history_invalid');
660
702
  revisionFinalResult=inspectFixFinalResult(record.payload,revisionFinalRegistration,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds),revisionFinalStarted);
661
- pending=null;stage=revisionFinalResult.observationStatus==='completed'
703
+ revisionFinalResultPayload=record.payload;pending=null;stage=revisionFinalResult.observationStatus==='completed'
662
704
  ?revisionFinalResult.review.verdict==='approved'?'revision_final_review_evidence_required':revisionFinalResult.review.verdict==='changes_requested'?'revision_review_limit_reached':'revision_final_review_blocked':'unknown';continue;
663
705
  }
664
706
  if(record.id==='fix-revision-n5-result'){
@@ -908,16 +950,17 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
908
950
  need(digest(pkg.identity)===digest(identity)&&pkg.defect===configuration.defect
909
951
  &&digest(pkg.reproduction)===digest(reproduction)&&digest(pkg.diagnosis)===digest(diagnosed)
910
952
  &&digest(pkg.learning)===digest(learning),'cause_registration_mismatch');
911
- stage='unknown';pending='cause_review';continue;
953
+ causeOrigin=stage;stage='unknown';pending='cause_review';continue;
912
954
  }
913
955
  if(record.id==='fix-cause-started'){
914
956
  need(pending==='cause_review'&&started===null&&record.kind==='result','fix_history_invalid');
915
957
  shape(record.payload,['providerThreadId']);id(record.payload.providerThreadId);started=record.payload.providerThreadId;
916
- need(![...hostContextIds,configuration.causeReview.contextId,finalStarted,...configuration.causeReview.excludedThreadIds].includes(started),'cause_registration_mismatch');continue;
958
+ need(![...hostContextIds,configuration.causeReview.contextId,finalStarted,...configuration.causeReview.excludedThreadIds,
959
+ causeAbandonment?.providerThreadId].includes(started),'cause_registration_mismatch');continue;
917
960
  }
918
961
  if(record.id==='fix-cause-result'){
919
962
  need(pending==='cause_review'&&record.kind==='result','fix_history_invalid');
920
- causeResult=inspectCauseResult(record.payload,cause,reviewConfiguration,started);pending=null;
963
+ causeResult=inspectCauseResult(record.payload,cause,reviewConfiguration,started);causeResultPayload=record.payload;pending=null;
921
964
  stage=causeResult.observationStatus!=='completed'?'unknown':causeResult.review.verdict==='approved'
922
965
  ?(causeResumeStage??(diagnosed.status==='design_change'?'design_change_required':'red_test_required'))
923
966
  :causeResult.review.verdict==='changes_requested'?'rediagnosis_required':'cause_review_blocked';continue;
@@ -1086,7 +1129,18 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1086
1129
  catch{stage='visual_evidence_required';}
1087
1130
  }
1088
1131
  if(stage==='design_change_required'&&!runRed)stage='escalation_required';
1132
+ // Registered review with no review result: nothing arrived, or only a timeout,
1133
+ // disconnect or cancellation observation. Each kind may be abandoned once.
1134
+ const noReviewResult=(registration,result,kind)=>stage==='unknown'&&registration!==null
1135
+ &&(pending===kind&&!result||pending===null&&result!==null&&result.observationStatus!=='completed');
1136
+ const causeNoResult=noReviewResult(cause,causeResult,'cause_review');
1137
+ const revisionNoResult=noReviewResult(revisionFinalRegistration,revisionFinalResult,'revision_final_review');
1138
+ const reviewAbandonable=causeNoResult&&!causeAbandonment?'cause_review':revisionNoResult&&!revisionAbandonment?'revision_final_review':null;
1089
1139
  const status=json({identity,stage,pending,abandoned,executionActive:active!==null,reproduction,diagnosis:diagnosed,learning,causeReview:causeResult,
1140
+ ...(reviewAbandonable?{reviewAbandonable}:{}),
1141
+ ...(causeNoResult&&causeAbandonment||revisionNoResult&&revisionAbandonment?{reviewAbandonBudgetExhausted:true}:{}),
1142
+ ...(causeAbandonment?{causeReviewAbandonment:causeAbandonment}:{}),
1143
+ ...(revisionAbandonment?{revisionFinalReviewAbandonment:revisionAbandonment}:{}),
1090
1144
  ...(causeReviewCorrection?{causeReviewCorrection}:{}),
1091
1145
  ...(observationResume?{observationResume,observationCycle}:{}),
1092
1146
  ...(observationReproduction?{observationReproduction}:{}),
@@ -1148,6 +1202,26 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1148
1202
  detail:`显式放弃 unknown 步骤:${current.pending}`,data:{pending:current.pending,reason}});
1149
1203
  return project();
1150
1204
  },
1205
+ // One audited abandonment per review kind, mirroring cm-ai abandon_review. The
1206
+ // host confirms the old reviewer process stopped; the record binds the exact
1207
+ // registration, thread and any no-result observation. The retry needs the
1208
+ // original review permission and a fresh reviewer thread.
1209
+ abandonReview({reason,authorized=false}={}){
1210
+ need(!closed&&active===null,'fix_busy');need(authorized===true,'fix_review_abandon_authorization_required');
1211
+ need(typeof reason==='string'&&reason.trim().length>0&&Buffer.byteLength(reason,'utf8')<=1000
1212
+ &&!/[\r\n\0\u0085\u2028\u2029]/.test(reason),'fix_review_abandon_reason_required');
1213
+ const current=project();
1214
+ need(current.reviewAbandonBudgetExhausted!==true,'fix_review_abandon_budget_exhausted');
1215
+ need(current.reviewAbandonable,'fix_review_abandon_unavailable');
1216
+ const records=store.snapshot().records,prefix=REVIEW_ABANDON[current.reviewAbandonable];
1217
+ const registration=records.find(row=>row.id===`${prefix}-registered`),result=records.find(row=>row.id===`${prefix}-result`)??null;
1218
+ append(`${prefix}-abandoned`,'result',{invocationId:registration.payload.request.invocationId,registrationDigest:digest(registration.payload),
1219
+ providerThreadId:records.find(row=>row.id===`${prefix}-started`)?.payload.providerThreadId??null,
1220
+ resultDigest:result===null?null:digest(result.payload),reason,abandonedAt:Date.now()});
1221
+ logFixEvent({specsRoot:evidenceSpecsRoot,identity,configuration,event:'abandon',phase:current.reviewAbandonable,
1222
+ detail:`显式放弃无结果的审查:${current.reviewAbandonable}`,data:{pending:current.reviewAbandonable,reason}});
1223
+ return project();
1224
+ },
1151
1225
  recoverFinalReview({authorized=false,recoveryInvocationId=null,invocationId,packageDigest,previousInvocationStopped,reason}={}){
1152
1226
  need(!closed&&active===null,'fix_busy');need(authorized===true,'fix_review_recovery_authorization_required');
1153
1227
  const current=project(),records=store.snapshot().records;
@@ -1176,7 +1250,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1176
1250
  if(configuration.qaSource)readFixQaSourceHistory({specsRoot,identity,configuration});
1177
1251
  const revised=Boolean(current.revisionN5),selected=revised?revisionCloseoutStatus(current):current;
1178
1252
  const records=store.snapshot().records;
1179
- const registration=(revised?records.find(row=>row.id==='fix-revision-final-registered'):finalRecord(records,'registered')).payload;
1253
+ const registration=(revised?reviewCycleRecord(records,'fix-revision-final','registered'):finalRecord(records,'registered')).payload;
1180
1254
  const reviewPackage=registration.request.payload.reviewPackage;
1181
1255
  need(selected.n5.packageDigest===reviewPackage.packageDigest,'fix_completion_evidence_unavailable');
1182
1256
  // Only a projection of the original owner and gate, never a new completion
@@ -1272,7 +1346,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1272
1346
  }
1273
1347
  if(status.revisionN5){
1274
1348
  need(['revision_closeout_required','revision_closeout_incomplete','completed'].includes(status.stage),'fix_closeout_unavailable');
1275
- const registration=store.snapshot().records.find(row=>row.id==='fix-revision-final-registered');
1349
+ const registration=reviewCycleRecord(store.snapshot().records,'fix-revision-final','registered');
1276
1350
  finishFix({specsRoot:evidenceSpecsRoot,identity:status.revision.nextIdentity,configuration,status:revisionCloseoutStatus(status),registeredAt:registration.payload.registeredAt},{assertOwned(){
1277
1351
  const current=project();need(['revision_closeout_required','revision_closeout_incomplete','completed'].includes(current.stage),'fix_evidence_changed');
1278
1352
  need(digest(current.revisionN5)===digest(status.revisionN5)&&digest(current.revisionWalkthrough)===digest(status.revisionWalkthrough),'fix_evidence_changed');
@@ -1341,7 +1415,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1341
1415
  need(!closed&&active===null,'fix_busy');const current=project();
1342
1416
  if(current.stage==='revision_completion_gate_required'){
1343
1417
  need(!current.revisionN5,'n5_evidence_changed');
1344
- const gate=checkN5(revisionN5Options()),registration=store.snapshot().records.find(row=>row.id==='fix-revision-final-registered').payload;
1418
+ const gate=checkN5(revisionN5Options()),registration=reviewCycleRecord(store.snapshot().records,'fix-revision-final','registered').payload;
1345
1419
  append('fix-revision-n5-result','result',{gate,packageDigest:registration.request.payload.reviewPackage.packageDigest});return project();
1346
1420
  }
1347
1421
  if(current.stage!=='completion_gate_required')return current;
@@ -1354,7 +1428,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1354
1428
  need(!closed&&active===null,'fix_busy');const current=project();
1355
1429
  if(['revision_final_review_evidence_required','revision_review_limit_reached','revision_final_review_blocked','revision_completion_gate_required','revision_post_review_regression_required','revision_post_review_regression_blocked','revision_closeout_required','revision_walkthrough_blocked'].includes(current.stage)){
1356
1430
  need(current.revisionFinalReview?.observationStatus==='completed','final_review_evidence_unavailable');publishRevisionFinal();
1357
- const registration=store.snapshot().records.find(row=>row.id==='fix-revision-final-registered').payload,result=current.revisionFinalReview;
1431
+ const registration=reviewCycleRecord(store.snapshot().records,'fix-revision-final','registered').payload,result=current.revisionFinalReview;
1358
1432
  logFixEvent({specsRoot:evidenceSpecsRoot,identity:current.revision.nextIdentity,configuration,event:'review',phase:'complete',
1359
1433
  detail:'Independent fix second implementation review evidence published',data:{feature:`fix-${identity.taskId.slice(6)}`,review_kind:'implementation',round:2,
1360
1434
  result:result.review.verdict,provider:result.provider,package_digest:registration.request.payload.reviewPackage.packageDigest,
@@ -1377,7 +1451,8 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1377
1451
  },
1378
1452
  async reviewFinal(){
1379
1453
  need(!closed&&active===null,'fix_busy');const start=project();if(!['final_review_required','revision_final_review_required'].includes(start.stage))return start;
1380
- const revising=start.stage==='revision_final_review_required',prefix=revising?'fix-revision-final':recoveryPrefix(start.finalReviewRecoveryCount);
1454
+ const revising=start.stage==='revision_final_review_required';
1455
+ const prefix=revising?(start.revisionFinalReviewAbandonment?'fix-revision-final-retry':'fix-revision-final'):recoveryPrefix(start.finalReviewRecoveryCount);
1381
1456
  need(finalReview&&typeof assertReviewReady==='function','final_review_unavailable');
1382
1457
  const ready=assertReviewReady();if(types.isPromise(ready))Promise.prototype.then.call(ready,()=>{},()=>{});
1383
1458
  need(ready===undefined,'final_sync_registration_required');
@@ -1386,7 +1461,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1386
1461
  const pkg=createReviewPackage({root:configuration.reproduction.cwd,baseline,checks,handoffPath:selectedHandoff});
1387
1462
  if(start.finalReviewRecovery&&!revising)need(pkg.packageDigest===start.finalReviewRecovery.packageDigest,'fix_review_recovery_drift');
1388
1463
  const run=createFixFinalReview({reviewPackage:pkg,configuration:revising?fixRevisionReviewConfiguration(revisionFeedback(),start.revision.nextIdentity,hostContextIds):fixFinalReviewConfiguration(reviewConfiguration,start.causeReview?.providerThreadId??null),
1389
- timeoutMs:configuration.reproduction.timeoutMs},finalReview);
1464
+ timeoutMs:reviewTimeout(finalReview,configuration.reproduction.timeoutMs)},finalReview);
1390
1465
  const controller=new AbortController();active=controller;let registered=false;
1391
1466
  try{
1392
1467
  const result=await run({signal:controller.signal,register(value){
@@ -1397,7 +1472,8 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1397
1472
  need(current.packageDigest===pkg.packageDigest,'final_package_mismatch');
1398
1473
  joinLiveHost();append(`${prefix}-registered`,'intent',value);registered=true;
1399
1474
  },onStarted(providerThreadId){
1400
- need(providerThreadId!==start.finalReviewRecovery?.providerThreadId,'final_context_mismatch');
1475
+ need(providerThreadId!==start.finalReviewRecovery?.providerThreadId
1476
+ &&providerThreadId!==(revising?start.revisionFinalReviewAbandonment?.providerThreadId:undefined),'final_context_mismatch');
1401
1477
  if(!revising)need(!store.snapshot().records.some(row=>finalCycleRecord(row,'started')
1402
1478
  &&row.payload.providerThreadId===providerThreadId),'final_context_mismatch');
1403
1479
  append(`${prefix}-started`,'result',{providerThreadId});
@@ -1687,6 +1763,9 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1687
1763
  &&!(status.stage==='observation_cause_review_correction_required'&&status.causeReviewCorrection))return status;
1688
1764
  need(configuration.causeReview&&causeReview&&typeof causeReview.authorize==='function'&&typeof causeReview.run==='function','cause_review_unavailable');
1689
1765
  const reviewer=configuration.causeReview;
1766
+ const budget=reviewTimeout(causeReview,configuration.reproduction.timeoutMs);
1767
+ const prefix=status.causeReviewAbandonment?'fix-cause-retry':'fix-cause';
1768
+ const abandonedThread=status.causeReviewAbandonment?.providerThreadId??null;
1690
1769
  const pkg=createFixCausePackage({codeProject:configuration.reproduction.cwd,defect:configuration.defect,status});
1691
1770
  const request=requestFor({invocationId:`fix-cause.${randomUUID()}`,identity,role:'reviewer',provider:reviewer.provider,
1692
1771
  requestedModel:reviewer.requestedModel,contextId:reviewer.contextId,payload:{reviewPackage:pkg,priorReview:null}});
@@ -1697,7 +1776,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1697
1776
  need(!controller.signal.aborted,'cancelled');
1698
1777
  if(digest(grant)===digest({status:'denied',code:'permission_denied'}))return {...project(),reason:'permission_denied'};
1699
1778
  const registration=inspectCauseRegistration({request,authorizationAt,registeredAt:Date.now(),grant},reviewConfiguration);
1700
- joinLiveHost();append('fix-cause-registered','intent',registration);
1779
+ joinLiveHost();append(`${prefix}-registered`,'intent',registration);
1701
1780
  registered=true;
1702
1781
  const dispatchAt=Date.now();need(dispatchAt>=registration.registeredAt&&dispatchAt<grant.expiresAt,'grant_expired');
1703
1782
  const events=[];let invalid=false,sealed=false,timedOut=false,started=null;
@@ -1709,7 +1788,9 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1709
1788
  inspectProviderCauseReview(JSON.stringify({...observation({status:'failed',code:'in_progress'}),events:[...events,event]}),
1710
1789
  JSON.stringify(causeExpectation(request,reviewConfiguration)));
1711
1790
  if(event.event==='thread.started'){
1712
- append('fix-cause-started','result',{providerThreadId:event.provider_thread});started=event.provider_thread;
1791
+ // A retry is a fresh reviewer thread, never the abandoned one.
1792
+ need(event.provider_thread!==abandonedThread,'observation_context');
1793
+ append(`${prefix}-started`,'result',{providerThreadId:event.provider_thread});started=event.provider_thread;
1713
1794
  }
1714
1795
  events.push(event);return true;
1715
1796
  }catch{invalid=true;controller.abort();return false;}
@@ -1717,18 +1798,21 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1717
1798
  let rejectAbort;
1718
1799
  const interrupted=new Promise((resolve,reject)=>{rejectAbort=()=>reject(Object.assign(new Error('cause_review_interrupted'),{code:'cause_review_interrupted'}));});
1719
1800
  controller.signal.addEventListener('abort',rejectAbort,{once:true});
1720
- timer=setTimeout(()=>{timedOut=true;controller.abort();},configuration.reproduction.timeoutMs);
1801
+ timer=setTimeout(()=>{timedOut=true;controller.abort();},budget);
1721
1802
  let result;
1722
1803
  try{
1723
1804
  result=await Promise.race([interrupted,Promise.resolve().then(()=>{
1724
1805
  need(!controller.signal.aborted,'cause_review_interrupted');
1725
1806
  return causeReview.run(request,{signal:controller.signal,onEvent});
1726
1807
  })]);
1727
- }finally{sealed=true;controller.signal.removeEventListener('abort',rejectAbort);}
1728
- if(invalid||controller.signal.aborted)return project();
1808
+ }catch(error){if(!timedOut||invalid)throw error;}
1809
+ finally{sealed=true;controller.signal.removeEventListener('abort',rejectAbort);}
1810
+ // The review budget expiring is a recorded no-result observation, not an
1811
+ // unrecorded interruption; a cancellation or invalid stream stays unknown.
1812
+ if(invalid||controller.signal.aborted&&!timedOut||project().stage==='cancelled')return project();
1729
1813
  const value={dispatchAt,observation:observation(timedOut?{status:'failed',code:'timeout'}:result)};
1730
1814
  inspectCauseResult(value,registration,reviewConfiguration,started);
1731
- append('fix-cause-result','result',value);
1815
+ append(`${prefix}-result`,'result',value);
1732
1816
  if(project().causeReview?.observationStatus==='completed')publishCause();
1733
1817
  return project();
1734
1818
  }catch(error){
@@ -8,6 +8,7 @@ import {createHostReviewAuthority} from '../cm-ai/host-review-authority.mjs';
8
8
  import {fixFinalReviewConfiguration} from './final-review.mjs';
9
9
  import {digest,id,json,need} from '../cm-ai/effect-contract.mjs';
10
10
 
11
+ const DEFAULT_REVIEW_TIMEOUT_MS=900000;
11
12
  export function createFixReviewHost({codeProject,hostContextId,runtime='codex',review=null,permissions=[],workerFactory=null}){
12
13
  id(hostContextId);need(['codex','claude'].includes(runtime),'invalid_runtime');
13
14
  const allowed=new Set(json(permissions)),config=review===null?null:json(review);
@@ -16,8 +17,11 @@ export function createFixReviewHost({codeProject,hostContextId,runtime='codex',r
16
17
  need(runtime!=='claude'||!config||config.disabledSkills.length===0,'invalid_review_config');
17
18
  const enabled=['--allow-cause-review','--allow-final-review','--allow-test-author','--allow-repair'].some(flag=>allowed.has(flag));
18
19
  need(!enabled||config!==null,'review_configuration_required');
20
+ // Review transport budget from the review configuration (outside its
21
+ // authorized digest), shared by the worker and the owner's review watchdog.
22
+ const timeoutMs=config?.timeoutMs??DEFAULT_REVIEW_TIMEOUT_MS;
19
23
  const workerOptions=config?{cwd:codeProject,model:config.model,disabledSkills:config.disabledSkills,
20
- promptTransport:'stdin',preflight:config.preflight,
24
+ promptTransport:'stdin',preflight:config.preflight,timeoutMs,
21
25
  schemaPath:fileURLToPath(new URL('../cm-ai/review-result.schema.json',import.meta.url))}:null;
22
26
  const assertReviewReady=()=>need(config&&matches(config.preflight,workerOptions),'tool_preflight_missing');
23
27
  if(enabled)assertReviewReady();
@@ -31,8 +35,8 @@ export function createFixReviewHost({codeProject,hostContextId,runtime='codex',r
31
35
  const authority=config?authorityFor(reviewer,'--allow-cause-review'):null;
32
36
  const finalAuthority=config?authorityFor(fixFinalReviewConfiguration({hostContextId,causeReview:reviewer}).reviewer,'--allow-final-review'):null;
33
37
  return {reviewer,authority,finalAuthority,execution:{assertReviewReady,
34
- ...(config?{causeReview:{authorize:authority.authorize,
38
+ ...(config?{causeReview:{authorize:authority.authorize,timeoutMs,
35
39
  run:(request,control)=>createCauseReviewRun(worker(workerOptions),runtime)(request,control)},
36
- finalReview:{authorize:finalAuthority.authorize,run:(request,control)=>
40
+ finalReview:{authorize:finalAuthority.authorize,timeoutMs,run:(request,control)=>
37
41
  (runtime==='claude'?createClaudeReviewRun:createCodexReviewRun)(worker(workerOptions))(request,control)}}:{})}};
38
42
  }
@@ -9,7 +9,7 @@ export function createFixHost({owner,config,runtime='codex',permissions=[],autho
9
9
  const extra=new Set(permissions);
10
10
  const host={async handle(request){
11
11
  shape(request,['requestId','operation',...(request.operation==='resume'?['evidenceFiles']:[]),
12
- ...(request.operation==='abandon_step'&&Object.hasOwn(request,'reason')?['reason']:[]),
12
+ ...(['abandon_step','abandon_review'].includes(request.operation)&&Object.hasOwn(request,'reason')?['reason']:[]),
13
13
  ...(request.operation==='prepare_revision'&&Object.hasOwn(request,'tests')?['tests']:[]),
14
14
  ...(request.operation==='recover_final_review'?['invocationId','packageDigest','previousInvocationStopped','reason']:[])]);
15
15
  if(config.qaSource&&!['status','cancel','completion_evidence'].includes(request.operation))
@@ -27,6 +27,8 @@ export function createFixHost({owner,config,runtime='codex',permissions=[],autho
27
27
  authorized:extra.has('--allow-final-review-recovery'),recoveryInvocationId,invocationId:request.invocationId,
28
28
  packageDigest:request.packageDigest,previousInvocationStopped:request.previousInvocationStopped,reason:request.reason});
29
29
  if(request.operation==='abandon_step')return owner.abandonStep({authorized:extra.has('--allow-abandon'),reason:request.reason});
30
+ // Reviewer-invocation authority stays separate from local step abandonment.
31
+ if(request.operation==='abandon_review')return owner.abandonReview({authorized:extra.has('--allow-abandon-review'),reason:request.reason});
30
32
  if(request.operation==='completion_evidence')return owner.completionEvidence();
31
33
  if(request.operation==='finish')return owner.finish({authorized:extra.has('--allow-finish')});
32
34
  if(request.operation==='author_tests')return owner.authorTests({authorized:extra.has('--allow-test-author')});
@@ -53,6 +53,7 @@ export function fixProgress(status,config={},authorization={}){
53
53
  remaining:finalPending?['取得有效独立审查结果','保存审查证据','核对完成条件','审后回归',...(config.walkthrough?['走查']:[]),'完成收尾']:null,
54
54
  nextAction:finalPending&&invocation.providerThreadId
55
55
  ?'先确认原调用已停止;核对当前审查包并取得本次一次续审授权,再恢复原任务。'
56
+ :status.reviewAbandonable?'审查没有结论:先确认原审查进程已停止,再用 abandon_review(--allow-abandon-review,原因审查与第二轮最终审查各一次)放弃这次调用,然后重新审查。'
56
57
  :'核对原操作与实际结果;不要重跑已完成步骤或推定成功。',requiresUser:true,
57
58
  ...(finalPending?{recovery:{invocationId:invocation.invocationId,packageDigest:invocation.packageDigest,
58
59
  completedRecoveryPreparations:status.finalReviewRecoveryCount??0,
@@ -22,12 +22,15 @@ function snapshot(cwd,file){
22
22
  }catch(error){if(error.code==='ENOENT')return null;throw error;}
23
23
  }
24
24
 
25
+ // Optional mode sets the permission bits of a written file (never of a deletion).
26
+ const EDIT_MODES=new Map([['0644',0o644],['0755',0o755]]);
25
27
  export function applyProtectedEdits({cwd,scope,edits}){
26
28
  validateDeveloperScope(scope);need(fs.realpathSync(cwd)===cwd,'unsupported_path');
27
29
  need(Array.isArray(edits)&&edits.length>0&&edits.length<=scope.length,'protected_edit_invalid');
28
30
  const seen=new Set();
29
31
  for(const edit of edits){
30
- shape(edit,['path','beforeSha256','content']);
32
+ shape(edit,['path','beforeSha256','content',...(Object.hasOwn(edit,'mode')?['mode']:[])]);
33
+ need(!Object.hasOwn(edit,'mode')||edit.content!==null&&EDIT_MODES.has(edit.mode),'protected_edit_invalid');
31
34
  need(scope.includes(edit.path)&&!seen.has(edit.path),'out_of_scope');seen.add(edit.path);
32
35
  need(edit.content===null||typeof edit.content==='string','protected_edit_invalid');
33
36
  need(edit.content===null||Buffer.byteLength(edit.content)<=1024*1024,'limit_exceeded');
@@ -40,9 +43,15 @@ export function applyProtectedEdits({cwd,scope,edits}){
40
43
  if(edit.content===null)fs.unlinkSync(target);
41
44
  else{
42
45
  fs.mkdirSync(path.dirname(target),{recursive:true});
43
- // O_NOFOLLOW avoids silently replacing a last-moment link target.
44
- const fd=fs.openSync(target,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_TRUNC|fs.constants.O_NOFOLLOW,0o600);
45
- try{fs.writeFileSync(fd,edit.content);fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
46
+ // O_NOFOLLOW avoids silently replacing a last-moment link target. A new
47
+ // file is ordinary source (0644); an existing one keeps its mode unless set.
48
+ const created=edit.beforeSha256===null;
49
+ const fd=fs.openSync(target,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_TRUNC|fs.constants.O_NOFOLLOW,0o644);
50
+ try{
51
+ fs.writeFileSync(fd,edit.content);
52
+ if(created||Object.hasOwn(edit,'mode'))fs.fchmodSync(fd,EDIT_MODES.get(edit.mode)??0o644);
53
+ fs.fsyncSync(fd);
54
+ }finally{fs.closeSync(fd);}
46
55
  }
47
56
  }
48
57
  }
@@ -81,6 +90,8 @@ export function protectedFixBridge({bridge,cwd,specsRoot,timeoutMs}){
81
90
  shape(result,['outcome','edits']);
82
91
  need(['blocked',kind==='fix_repair'?'repaired':'authored'].includes(result.outcome),'protected_edit_invalid');
83
92
  need(Array.isArray(result.edits),'protected_edit_invalid');
93
+ // cm-fix keeps its original text-only proposal shape; mode is a cm-ai develop field.
94
+ for(const edit of result.edits)shape(edit,['path','beforeSha256','content']);
84
95
  if(result.outcome==='blocked'){need(result.edits.length===0,'protected_edit_invalid');return {outcome:'blocked'};}
85
96
  need(result.edits.length>0||kind==='fix_repair'&&payload.allowUnchanged===true,'protected_edit_invalid');
86
97
  await commitProtectedEdits({cwd,specsRoot,scope:payload.scope,edits:result.edits,expected,
@@ -2,7 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {readHostQaFixHandoff,readHostQaFixHistory} from '../cm-ai/host-qa-fix.mjs';
5
- import {scanRows} from '../cm-ai/cm-ai-qa-log.mjs';
5
+ import {effectiveQaDecisionRow,scanRows} from '../cm-ai/cm-ai-qa-log.mjs';
6
6
  import {readReviewSourceFiles} from '../cm-ai/review-package.mjs';
7
7
  import {digest,hex,id,json,need,shape,text,validIdentity} from '../cm-ai/effect-contract.mjs';
8
8
 
@@ -39,9 +39,11 @@ function inspectSource({specsRoot,identity,configuration},readHandoff){
39
39
  &&row.task===source.identity.taskId&&row.attempt===source.identity.attempt
40
40
  &&row.feature===source.feature&&row.package_digest===source.packageDigest)rows.push(row);
41
41
  });
42
- need(rows.length===1&&typeof rows[0].project_path==='string'&&typeof rows[0].specs_path==='string'
43
- &&fs.realpathSync(rows[0].project_path)===fs.realpathSync(configuration.reproduction.cwd)
44
- &&fs.realpathSync(rows[0].specs_path)===fs.realpathSync(specsRoot),'fix_qa_project_mismatch');
42
+ // A recovered timeout decision appends one linked row; bind the effective one.
43
+ const decision=effectiveQaDecisionRow(rows,'fix_qa_project_mismatch');
44
+ need(decision&&typeof decision.project_path==='string'&&typeof decision.specs_path==='string'
45
+ &&fs.realpathSync(decision.project_path)===fs.realpathSync(configuration.reproduction.cwd)
46
+ &&fs.realpathSync(decision.specs_path)===fs.realpathSync(specsRoot),'fix_qa_project_mismatch');
45
47
  need(handoff.handoffDigest===handoffDigest,'fix_qa_source_changed');
46
48
  need(handoff.status!=='blocked','fix_qa_source_blocked');
47
49
  return handoff;
@@ -14,6 +14,7 @@ import {preparePrdReview} from './review-preparation.mjs';
14
14
  import {inspectAcceptedPrdDesign} from './accepted-design.mjs';
15
15
  import {inspectPrdDesignRiskSelection} from './design-risk.mjs';
16
16
  import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
17
+ import {prdDraftJson} from './validation-reason.mjs';
17
18
 
18
19
  export function createCmPrdAnalysis({input,runtime,analyze,record,processMaterials,generate,checkContext,restored=null,allowInputDrift=false}){
19
20
  need(['codex','claude'].includes(runtime)&&typeof analyze==='function'&&typeof record==='function','prd_host_invalid');
@@ -178,7 +179,7 @@ export function createCmPrdAnalysis({input,runtime,analyze,record,processMateria
178
179
  await record({event:'degrade',phase:'route',data:{outcome:'planner_adapter_unavailable'}});
179
180
  stage='blocked';return this.status();
180
181
  }
181
- const reply=json(await generate({project:admission.project,specs:admission.specs,analysis:result,
182
+ const reply=prdDraftJson(await generate({project:admission.project,specs:admission.specs,analysis:result,
182
183
  userAnswers:messages.filter(message=>message.role==='user'),messages:next,role:roles.planner,nextIndex,
183
184
  phase:designOnly?'design':acceptedDesign!==null?'tasks_after_design':'full_draft',
184
185
  acceptedDesign,
@@ -7,6 +7,7 @@ import path from 'node:path';
7
7
  import {createHash} from 'node:crypto';
8
8
  import {loadConfig,resolveRole} from '../../../scripts/cm-workflow-config.mjs';
9
9
  import {buildManifest} from '../../../scripts/cm-spec-manifest.mjs';
10
+ import {specLines,taskDeclarations,TASK_GRAMMAR,LEGACY_TASK_GRAMMAR} from '../spec-task-line.mjs';
10
11
  import {inspectPrdReview} from '../../../scripts/cm-prd-review-gate.mjs';
11
12
  import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
12
13
  import {writeImmutableWorkflowFile} from '../cm-ai/review-evidence-file.mjs';
@@ -53,13 +54,27 @@ export function inspectPrdChangeSnapshot(specs){
53
54
  const status=read(specs,'.cm-specs-status');
54
55
  return json({directories,files,trees,reviews,status},4*1024*1024);
55
56
  }
56
- function completedLines(source){return source.split(/\r?\n/).filter(line=>/^\s*-\s+\[[xX]\]\s+T-[\w.-]+\s*:/.test(line));}
57
- function taskLines(source){return new Map(source.split(/\r?\n/).flatMap(line=>{
58
- const match=line.match(/^\s*-\s+\[[ xX]\]\s+(?:~~)?(T-[\w.-]+)\s*:/);return match?[[match[1],line]]:[];
59
- }));}
57
+ // Same declaration grammar as admission and N5 mark-done (spec-task-line.mjs):
58
+ // the approved original is read with the grammar its approval bound, the
59
+ // proposed text (a new approval) with the current grammar.
60
+ function completedLines(source,grammar=TASK_GRAMMAR){return taskDeclarations(source,{grammar}).filter(item=>item.completed).map(item=>item.body);}
61
+ function taskLines(source,grammar=TASK_GRAMMAR){return new Map(taskDeclarations(source,{grammar}).map(item=>[item.id,item.body]));}
62
+ // The grammar the last approval established. cm-prd's own awaiting_review
63
+ // statuses (change invalidation/result, summary publication) only ever carry
64
+ // that value forward, so a chain of changes before re-approval keeps reading
65
+ // the approved originals the same way. The one exception is a first summary
66
+ // publication with no earlier status at all, where nothing was ever approved
67
+ // under another grammar.
68
+ function approvedGrammar(before){
69
+ try{const status=JSON.parse(before.status??'null');
70
+ return ['approved','awaiting_review'].includes(status?.status)&&status.taskGrammar===TASK_GRAMMAR?TASK_GRAMMAR:LEGACY_TASK_GRAMMAR;}
71
+ catch{return LEGACY_TASK_GRAMMAR;}
72
+ }
73
+ function sourceLines(source){return specLines(source).map(line=>line.body);}
60
74
  function userCases(files){return Object.entries(files).filter(([file])=>file.endsWith('/test-cases.json'))
61
75
  .flatMap(([file,content])=>JSON.parse(content).cases.filter(c=>c.origin==='user').map(c=>({feature:file.split('/')[0],value:c})));}
62
76
  export function inspectPrdChangeProposal(before,raw,selected,config){
77
+ const grammar=approvedGrammar(before);
63
78
  shape(raw,['status','summary','features','removed']);need(raw.status==='draft'&&text(raw.summary)&&Array.isArray(raw.features)
64
79
  &&Array.isArray(raw.removed)&&new Set(raw.removed).size===raw.removed.length,'prd_change_proposal_invalid');
65
80
  const files={},features=[],seen=new Set();
@@ -88,10 +103,10 @@ export function inspectPrdChangeProposal(before,raw,selected,config){
88
103
  &&new Set(resultDirs.map(dir=>dir.split('.')[0])).size===resultDirs.length,'prd_change_inventory_collision');
89
104
  for(const directory of selected){
90
105
  const original=before.files[`${directory}/tasks.md`],after=files[`${directory}/tasks.md`]??'';
91
- for(const line of completedLines(original))need(after.split(/\r?\n/).includes(line),'prd_completed_task_changed');
92
- need(completedLines(after).every(line=>completedLines(original).includes(line)),'prd_completed_task_invented');
106
+ for(const line of completedLines(original,grammar))need(sourceLines(after).includes(line),'prd_completed_task_changed');
107
+ need(completedLines(after).every(line=>completedLines(original,grammar).includes(line)),'prd_completed_task_invented');
93
108
  if(raw.removed.includes(directory))continue;
94
- const prior=taskLines(original),next=taskLines(after);
109
+ const prior=taskLines(original,grammar),next=taskLines(after);
95
110
  for(const [id,line] of prior)need(next.has(id)&&(next.get(id)===line||/\[(?:CHANGED|DROPPED)\b/.test(next.get(id))),
96
111
  'prd_change_task_history_missing');
97
112
  for(const [id,line] of next)if(!prior.has(id))need(/\[NEW\b/.test(line)&&!/\[[xX]\]/.test(line),'prd_change_new_task_invalid');
@@ -115,7 +130,7 @@ export function inspectPrdChangeProposal(before,raw,selected,config){
115
130
  return json({...draft,mechanicalSelfCheck:mechanics,removed:raw.removed,files,changedUserCases,
116
131
  proposalDigest:digest({before,raw,selected}),counts:{added:resultDirs.filter(dir=>!before.directories.includes(dir)).length,
117
132
  removed:raw.removed.length,changed:selected.filter(dir=>seen.has(dir)).length,
118
- preservedCompletedTasks:selected.reduce((n,dir)=>n+completedLines(before.files[`${dir}/tasks.md`]).length,0)}},4*1024*1024);
133
+ preservedCompletedTasks:selected.reduce((n,dir)=>n+completedLines(before.files[`${dir}/tasks.md`],grammar).length,0)}},4*1024*1024);
119
134
  }
120
135
 
121
136
  export function createPrdChange({admission,runtime,call,restored=null,selected=[admission.feature],reason=null}){
@@ -259,7 +274,9 @@ export function applyPrdChange({specs,before,proposal,selected}){
259
274
  current();
260
275
  // Invalidate approval BEFORE replacing the first byte (also safe after crash).
261
276
  const statusFile='.cm-specs-status',invalidated=JSON.stringify({status:'awaiting_review',revisionDigest:proposal.proposalDigest,
262
- at:new Date().toISOString(),features:newDirs,specFiles:[],testCases:[]})+'\n';
277
+ at:new Date().toISOString(),features:newDirs,specFiles:[],testCases:[],
278
+ // Carry the last approval's tasks.md grammar to the next approval.
279
+ ...(approvedGrammar(before)===TASK_GRAMMAR?{taskGrammar:TASK_GRAMMAR}:{})})+'\n';
263
280
  if(read(specs,statusFile)===before.status)replaceSessionFile(specs,statusFile,before.status,invalidated);
264
281
  for(const [file,content] of Object.entries(expected)){
265
282
  if(!selected.includes(file.split('/')[0])&&oldDirs.includes(file.split('/')[0]))continue;
@@ -281,7 +298,8 @@ export function applyPrdChange({specs,before,proposal,selected}){
281
298
  current();const specFiles=buildManifest(specs);
282
299
  need(digest(fs.readdirSync(specs).filter(dir=>/^\d+\./.test(dir)).sort())===digest(newDirs),'prd_change_inventory_conflict');
283
300
  const result={status:'awaiting_review',at:JSON.parse(read(specs,statusFile)).at,revisionDigest:proposal.proposalDigest,
284
- features:newDirs,specFiles,testCases:specFiles.filter(item=>item.path.endsWith('/test-cases.json'))};
301
+ features:newDirs,specFiles,testCases:specFiles.filter(item=>item.path.endsWith('/test-cases.json')),
302
+ ...(approvedGrammar(before)===TASK_GRAMMAR?{taskGrammar:TASK_GRAMMAR}:{})};
285
303
  replaceSessionFile(specs,statusFile,read(specs,statusFile),JSON.stringify(result)+'\n');
286
304
  return json({...result,archive:`.reviews/${name}`,counts:proposal.counts,priorReviews:'retained_as_history_not_current_approval',
287
305
  next:'human_review_then_explicit_cm_ai',completionAuthorized:false});
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import {need,shape,json,digest} from '../cm-ai/effect-contract.mjs';
4
4
  import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
5
+ import {needPrd,prdDraftJson} from './validation-reason.mjs';
5
6
  export function prdFeatureInventory(specs){
6
7
  return fs.readdirSync(specs).filter(name=>/^\d+\./.test(name)).sort();
7
8
  }
@@ -37,7 +38,7 @@ export function inspectPrdDesignDraft(raw,{nextIndex}){
37
38
  writeAuthorized:false,completionAuthorized:false});
38
39
  }
39
40
  export function inspectPrdDraft(raw,{nextIndex,generateCases,userCasesProvided}){
40
- const reply=json(raw,64*1024);shape(reply,['status','summary','features']);
41
+ const reply=prdDraftJson(raw);shape(reply,['status','summary','features']);
41
42
  need(reply.status==='draft'&&typeof reply.summary==='string'&&reply.summary.trim()
42
43
  &&Array.isArray(reply.features)&&reply.features.length>0,'prd_draft_invalid');
43
44
  const seen=new Set(),features=[];let userCases=0;
@@ -55,7 +56,9 @@ export function inspectPrdDraft(raw,{nextIndex,generateCases,userCasesProvided})
55
56
  need(['requirements.md','design.md','tasks.md'].every(file=>files.has(file)),'prd_draft_triad_missing');
56
57
  if(files.has('test-cases.json')){
57
58
  const cases=JSON.parse(files.get('test-cases.json'));
58
- need(validateTestCases(cases).length===0&&cases.feature===feature.name&&feature.testCasesReason===null,'prd_draft_cases_invalid');
59
+ needPrd(feature.testCasesReason===null,'prd_draft_cases_invalid',
60
+ {field:`features[${index}].testCasesReason`,expected:'testCasesReason must be null when test cases are present'});
61
+ need(validateTestCases(cases).length===0&&cases.feature===feature.name,'prd_draft_cases_invalid');
59
62
  need(generateCases||cases.cases.every(item=>item.origin!=='generated'),'prd_generated_cases_disabled');
60
63
  userCases+=cases.cases.filter(item=>item.origin==='user').length;
61
64
  }else need(['no_observable_behavior','generation_disabled'].includes(feature.testCasesReason)