@aibyzero/cm-workflow 0.16.8 → 0.16.9

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 (157) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +19 -0
  3. package/README.md +14 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +25 -1
  8. package/docs/next-steps.md +8 -2
  9. package/docs/user-guide.md +105 -5
  10. package/package.json +2 -1
  11. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  12. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -20
  13. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +69 -22
  14. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  15. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  16. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  17. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  18. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  19. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  20. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  21. package/runtime/js/cm-ai/host-check.mjs +4 -1
  22. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  23. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  24. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  25. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  26. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  27. package/runtime/js/cm-ai/host-session.mjs +1 -1
  28. package/runtime/js/cm-ai/host-tool-bridge.mjs +40 -3
  29. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  30. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  31. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  32. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  33. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  34. package/runtime/js/cm-ai/review-package.mjs +10 -1
  35. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  36. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  37. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  38. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  39. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  40. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  41. package/runtime/js/cm-fix/execution.mjs +176 -48
  42. package/runtime/js/cm-fix/host.mjs +2 -1
  43. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  44. package/runtime/js/cm-fix/progress.mjs +13 -3
  45. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  46. package/runtime/js/cm-fix/repair.mjs +11 -3
  47. package/runtime/js/cm-fix/test-author.mjs +10 -3
  48. package/runtime/js/cm-idea/session.mjs +67 -4
  49. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  50. package/runtime/js/cm-prd/session.mjs +43 -0
  51. package/runtime/js/cm-refactor/records.mjs +98 -8
  52. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  53. package/runtime/js/cm-test/host.mjs +10 -3
  54. package/runtime/js/cm-test/session.mjs +45 -6
  55. package/runtime/js/notify-safe-read.mjs +49 -0
  56. package/runtime/js/notify-send.mjs +312 -0
  57. package/runtime/js/notify.mjs +137 -33
  58. package/runtime/js/policy-binding-compat.mjs +54 -0
  59. package/scripts/ci-test-shards.mjs +67 -0
  60. package/scripts/ci-test-shards.test.mjs +64 -0
  61. package/scripts/ci-test-weights.json +222 -0
  62. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  63. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  64. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  65. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  66. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  67. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  68. package/scripts/cm-ai-batch-drive.mjs +55 -10
  69. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  70. package/scripts/cm-ai-batch-host.mjs +132 -13
  71. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  72. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  73. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  74. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  75. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  76. package/scripts/cm-ai-batch-run.mjs +184 -22
  77. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  78. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  79. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  80. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  81. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  82. package/scripts/cm-ai-drive.mjs +64 -22
  83. package/scripts/cm-ai-drive.test.mjs +29 -2
  84. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  85. package/scripts/cm-ai-host-fixture.mjs +268 -0
  86. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  87. package/scripts/cm-ai-host.mjs +27 -15
  88. package/scripts/cm-ai-host.test.mjs +17 -759
  89. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  90. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  91. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  92. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  93. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  94. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +56 -10
  95. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  96. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  97. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  98. package/scripts/cm-ai-run.mjs +15 -6
  99. package/scripts/cm-ai-supersede.test.mjs +486 -41
  100. package/scripts/cm-check-drive-files.mjs +8 -0
  101. package/scripts/cm-check-drive.test.mjs +2 -5
  102. package/scripts/cm-check-runtime.sh +4 -2
  103. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  104. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  105. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  106. package/scripts/cm-claude-worker.test.mjs +18 -2
  107. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  108. package/scripts/cm-fix-abandon.test.mjs +163 -10
  109. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  110. package/scripts/cm-fix-drive.mjs +25 -7
  111. package/scripts/cm-fix-host.mjs +8 -7
  112. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  113. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  114. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  115. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  116. package/scripts/cm-host-documentation.test.mjs +49 -0
  117. package/scripts/cm-host-qa-executor.test.mjs +22 -10
  118. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  119. package/scripts/cm-idea-drive.mjs +49 -11
  120. package/scripts/cm-idea-drive.test.mjs +66 -0
  121. package/scripts/cm-idea-host.mjs +106 -16
  122. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  123. package/scripts/cm-init-drive.mjs +41 -7
  124. package/scripts/cm-init-host.mjs +61 -12
  125. package/scripts/cm-log-event.mjs +21 -10
  126. package/scripts/cm-notify-command.test.mjs +900 -0
  127. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  128. package/scripts/cm-notify.mjs +469 -0
  129. package/scripts/cm-notify.test.mjs +221 -4
  130. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  131. package/scripts/cm-prd-drive.mjs +18 -5
  132. package/scripts/cm-prd-drive.test.mjs +15 -0
  133. package/scripts/cm-prd-host.mjs +37 -4
  134. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  135. package/scripts/cm-prd-review-gate.mjs +56 -0
  136. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  137. package/scripts/cm-refactor-drive.mjs +52 -8
  138. package/scripts/cm-refactor-drive.test.mjs +44 -0
  139. package/scripts/cm-refactor-host.test.mjs +10 -6
  140. package/scripts/cm-release-smoke.sh +2 -0
  141. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  142. package/scripts/cm-test-drive.mjs +21 -5
  143. package/scripts/fixtures/claude-review-process.mjs +1 -1
  144. package/scripts/policy-binding-compat.test.mjs +99 -0
  145. package/scripts/scan-public-safety.py +4 -0
  146. package/scripts/validate-public-repo.py +4 -0
  147. package/skills/cm-ai/references/js-host-qa-recovery.md +27 -1
  148. package/skills/cm-ai/references/js-host-recovery.md +120 -8
  149. package/skills/cm-ai/references/js-host.md +14 -7
  150. package/skills/cm-check/SKILL.md +3 -3
  151. package/skills/cm-fix/references/js-host.md +44 -5
  152. package/skills/cm-idea/references/js-host.md +27 -2
  153. package/skills/cm-init/references/js-host.md +16 -3
  154. package/skills/cm-notify/SKILL.md +34 -0
  155. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  156. package/skills/cm-refactor/references/js-host.md +17 -0
  157. package/skills/cm-test/references/js-host.md +14 -1
@@ -5,6 +5,9 @@ import {findCmAiQaDecision,inspectCmAiQaDecision,inspectCmAiQaResult,recordCmAiQ
5
5
  latestCmAiQaRun,recordCmAiQaRun,inspectCmAiQaRecovery,inspectCmAiQaConfigurationRecovery,timedOutQaDecision,
6
6
  replacesTimedOutQaDecision,validEnvironmentFailureReason} from './cm-ai-qa-log.mjs';
7
7
  import {recordCmAiRunDone} from './cm-ai-run-finalizer.mjs';
8
+ import {releaseVerifiedQaResources} from './qa-resource-release.mjs';
9
+ import {QA_MAX_ROUNDS} from './qa-round-budget.mjs';
10
+ import {qaRoundDeadlineMs} from './host-qa-executor.mjs';
8
11
  import {projectHostResult} from './host-progress.mjs';
9
12
  import {operatorGuidance} from './operator-guidance.mjs';
10
13
  import {outstandingFeatureQa,describeOutstandingQa} from './project-qa-gate.mjs';
@@ -21,22 +24,40 @@ const boundStatus=(status,identity)=>{validIdentity(status?.identity);
21
24
  // verdict and a verdict that broke the written contract share one redispatch
22
25
  // per attempt. Exported for the batch driver, like developmentRetryable.
23
26
  export const reviewRetryable=status=>status.state==='pending_review'
24
- &&['review_transport_timeout','review_abandoned','review_provider_failed','review_verdict_invalid'].includes(status.code);
27
+ &&(['review_transport_timeout','review_abandoned','review_provider_failed','review_verdict_invalid'].includes(status.code)
28
+ // Registered but never dispatched (expired grant, clock ran backwards): no reviewer
29
+ // ran, so a fresh authorization redispatches it (REVIEW_NOT_DISPATCHED_CODES; the
30
+ // runner's not_dispatched halt is the only source of pending_review with these codes).
31
+ ||['grant_expired','clock_invalid'].includes(status.code)
32
+ // A refused authorization the operator has since confirmed (abandon_review): the same
33
+ // round asks for a fresh authorization. Unconfirmed (reviewDispatchConfirmRequired) it
34
+ // is not retryable here, so neither advance nor the batch driver ever redispatches it.
35
+ ||status.code==='permission_denied_confirmed');
25
36
  const retryReview=reviewRetryable;
26
37
  // Both mean the delivery itself must be redone: an invalid developer result, or
27
38
  // one that does not satisfy the task's own written verification. Exported so the
28
39
  // batch driver decides retryability from the same predicate instead of keeping a
29
40
  // second copy of the code list that silently drifts.
30
41
  export const developmentRetryable=status=>status.state==='blocked'
31
- &&['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed'].includes(status.code);
42
+ &&['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed','develop_call_timeout','develop_answer_invalid',
43
+ 'check_answer_missing','check_answer_invalid','develop_out_of_scope','develop_answer_missing','develop_dispatch_failed','develop_interrupted',
44
+ // Q16/Q17: only documentation_sync is asked again (durable-runner-state.mjs DOCUMENTATION_SYNC_CODES).
45
+ 'documentation_sync_answer_missing','documentation_sync_answer_invalid','documentation_sync_answer_blocked','documentation_sync_out_of_scope','documentation_sync_interrupted'].includes(status.code)
46
+ // Shown before the operator confirmed the session stopped: not yet redoable.
47
+ &&status.developRedoRequired!==true;
32
48
  const retryDeveloper=developmentRetryable;
33
49
  export const completionRetryable=status=>status.state==='blocked'
34
- &&['completion_checks_changed','completion_package_changed'].includes(status.code)
50
+ &&['completion_checks_changed','completion_package_changed','complete_recheck_failed','complete_commit_interrupted'].includes(status.code)
35
51
  &&status.retryReady!==false;
36
52
  const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approval':
37
53
  // The runner reports spec_drift over any state whose next effect would be refused.
38
54
  status.code==='spec_drift'?(status.specificationRebind==='available'?'spec_rebind':'none'):
39
55
  status.bootstrapReviewRecovery===true?'bootstrap_review_recover':
56
+ status.developRedoRequired===true?'develop_redo':
57
+ // V5: the round's second no-result redispatch needs the operator's stop confirmation.
58
+ status.reviewRedispatchStopRequired===true?'abandon_review':
59
+ // A review that never started and needs the operator's confirmation (abandon_review).
60
+ status.reviewDispatchConfirmRequired===true?'abandon_review':
40
61
  status.reviewReconciliation?.available?'reconcile_review':
41
62
  status.state==='changes_requested'||retryDeveloper(status)||retryReview(status)?'resume':
42
63
  status.state==='awaiting_review'?'decision':status.state==='unknown'
@@ -60,6 +81,11 @@ const summary=(operation,status,outcome)=>freeze({version:1,workflow:'cm-ai',ope
60
81
  requestDigest:digest(operation),identity:status.identity,outcome,state:status.state,code:status.code??null,
61
82
  packageDigest:status.packageDigest??null,pendingAction:pendingAction(status),
62
83
  ...(status.reviewReconciliation?{reviewReconciliation:status.reviewReconciliation}:{}),
84
+ ...(status.developRedoRequired===true?{developRedoRequired:true}:{}),
85
+ ...(status.documentationSyncPending===true?{documentationSyncPending:true}:{}),
86
+ ...(status.reviewRedispatchStopRequired===true?{reviewRedispatchStopRequired:true}:{}),
87
+ ...(status.reviewDispatchConfirmRequired===true?{reviewDispatchConfirmRequired:true}:{}),
88
+ ...(typeof status.reviewAbandonRefusal==='string'?{reviewAbandonRefusal:status.reviewAbandonRefusal}:{}),
63
89
  ...(typeof status.reason==='string'?{reason:status.reason}:{}),
64
90
  ...(status.code==='handoff_exists'?{reason:REVIEWED_HANDOFF_HINT}:{}),
65
91
  ...(status.state==='blocked'&&status.calls?.at(-1)?.blockedReason!==undefined
@@ -82,11 +108,11 @@ function readOperation(raw) {
82
108
  const operation=json(raw),keys=['version','operation','requestId','identity'];
83
109
  if(['decision','complete','qa','qa_result','context_refresh','finish','run_finalize'].includes(operation?.operation))keys.push('packageDigest');
84
110
  if(['qa_result','context_refresh','finish','run_finalize'].includes(operation?.operation))keys.push('testRunId');
85
- if(['abandon_review','abandon_effect','bootstrap_review_recover'].includes(operation?.operation))keys.push('reason');
111
+ if(['abandon_review','abandon_effect','bootstrap_review_recover','develop_redo'].includes(operation?.operation))keys.push('reason');
86
112
  if(operation?.operation==='reconcile_review')keys.push('invocationId');
87
113
  shape(operation,keys);
88
114
  if(operation?.operation==='reconcile_review')id(operation.invocationId);
89
- need(operation.version===1&&['advance','start','status','decision','complete','qa','qa_result','context_refresh','finish','run_finalize','cancel','resume','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover']
115
+ need(operation.version===1&&['advance','start','status','decision','complete','qa','qa_result','context_refresh','finish','run_finalize','cancel','resume','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover','develop_redo']
90
116
  .includes(operation.operation));
91
117
  id(operation.requestId);validIdentity(operation.identity);
92
118
  if(operation.operation==='abandon_review')need(typeof operation.reason==='string'
@@ -95,6 +121,9 @@ function readOperation(raw) {
95
121
  if(operation.operation==='abandon_effect')need(typeof operation.reason==='string'
96
122
  &&operation.reason.trim().length>0&&Buffer.byteLength(operation.reason,'utf8')<=500
97
123
  &&!/[\r\n\0]/.test(operation.reason),'effect_abandon_reason_required');
124
+ if(operation.operation==='develop_redo')need(typeof operation.reason==='string'
125
+ &&operation.reason.trim().length>0&&Buffer.byteLength(operation.reason,'utf8')<=500
126
+ &&!/[\r\n\0]/.test(operation.reason),'develop_redo_reason_required');
98
127
  if(operation.operation==='bootstrap_review_recover')need(typeof operation.reason==='string'
99
128
  &&operation.reason.trim().length>0&&Buffer.byteLength(operation.reason,'utf8')<=500
100
129
  &&!/[\r\n\0]/.test(operation.reason),'bootstrap_review_recovery_reason_required');
@@ -136,6 +165,11 @@ function effectSummary(operation,result,runner,identity) {
136
165
  boundStatus(runner.status(),next);
137
166
  return summary(operation,boundStatus(result,next),'advanced');
138
167
  }
168
+ // A rejected current-session answer is checkpointed blocked/failed; the
169
+ // runner's status shows it as the retryable develop_answer_invalid block.
170
+ if(result?.state==='blocked'&&['failed','unavailable'].includes(result.code)){
171
+ const current=runner.status();if(['develop_answer_invalid','develop_answer_missing'].includes(current.code))result=current;
172
+ }
139
173
  return summary(operation,boundStatus(result,identity),result?.code==='handoff_exists'?'blocked':'advanced');
140
174
  }
141
175
 
@@ -195,6 +229,7 @@ export function createCmAiConversationEntry(options) {
195
229
  if(options&&Object.hasOwn(options,'allowAbandonReview'))optionKeys.push('allowAbandonReview');
196
230
  if(options&&Object.hasOwn(options,'allowAbandonEffect'))optionKeys.push('allowAbandonEffect');
197
231
  if(options&&Object.hasOwn(options,'allowBootstrapReviewRecovery'))optionKeys.push('allowBootstrapReviewRecovery');
232
+ if(options&&Object.hasOwn(options,'allowDevelopRedo'))optionKeys.push('allowDevelopRedo');
198
233
  if(options&&Object.hasOwn(options,'holdRevision'))optionKeys.push('holdRevision');
199
234
  if(options&&Object.hasOwn(options,'featureSelection'))optionKeys.push('featureSelection');
200
235
  shape(options,optionKeys);
@@ -207,6 +242,8 @@ export function createCmAiConversationEntry(options) {
207
242
  const runnerKeys=['executeEffect','status','cancel','run'];
208
243
  if(runner&&Object.hasOwn(runner,'verificationBlocks'))runnerKeys.push('verificationBlocks');
209
244
  if(runner&&Object.hasOwn(runner,'completionBlocks'))runnerKeys.push('completionBlocks');
245
+ if(runner&&Object.hasOwn(runner,'reviewEffectIds'))runnerKeys.push('reviewEffectIds');
246
+ if(runner&&Object.hasOwn(runner,'recheckLearningInput'))runnerKeys.push('recheckLearningInput');
210
247
  if(runner&&Object.hasOwn(runner,'attachLearningEvidence'))runnerKeys.push('attachLearningEvidence');
211
248
  if(runner&&Object.hasOwn(runner,'inspectFixAssociation'))runnerKeys.push('inspectFixAssociation');
212
249
  if(runner&&Object.hasOwn(runner,'acceptCompletedFix'))runnerKeys.push('acceptCompletedFix');
@@ -218,10 +255,15 @@ export function createCmAiConversationEntry(options) {
218
255
  if(runner&&Object.hasOwn(runner,'reconcileReview'))runnerKeys.push('reconcileReview');
219
256
  if(runner&&Object.hasOwn(runner,'abandonEffect'))runnerKeys.push('abandonEffect');
220
257
  if(runner&&Object.hasOwn(runner,'recoverBootstrapReview'))runnerKeys.push('recoverBootstrapReview');
258
+ if(runner&&Object.hasOwn(runner,'redoDevelop'))runnerKeys.push('redoDevelop');
259
+ if(runner&&Object.hasOwn(runner,'recoverCommit'))runnerKeys.push('recoverCommit');
260
+ if(runner&&Object.hasOwn(runner,'interruptions'))runnerKeys.push('interruptions');
221
261
  if(runner&&Object.hasOwn(runner,'inspectBootstrapAdmission'))runnerKeys.push('inspectBootstrapAdmission');
222
262
  shape(runner,runnerKeys);
223
263
  for(const name of ['executeEffect','status','cancel','run'])need(typeof runner[name]==='function');
224
264
  if(Object.hasOwn(runner,'completionBlocks'))need(typeof runner.completionBlocks==='function');
265
+ if(Object.hasOwn(runner,'reviewEffectIds'))need(typeof runner.reviewEffectIds==='function');
266
+ if(Object.hasOwn(runner,'recheckLearningInput'))need(typeof runner.recheckLearningInput==='function');
225
267
  if(Object.hasOwn(runner,'attachLearningEvidence'))need(typeof runner.attachLearningEvidence==='function');
226
268
  if(Object.hasOwn(runner,'inspectFixAssociation'))need(typeof runner.inspectFixAssociation==='function');
227
269
  if(Object.hasOwn(runner,'acceptCompletedFix'))need(typeof runner.acceptCompletedFix==='function');
@@ -231,6 +273,9 @@ export function createCmAiConversationEntry(options) {
231
273
  if(Object.hasOwn(runner,'reconcileReview'))need(typeof runner.reconcileReview==='function');
232
274
  if(Object.hasOwn(runner,'abandonEffect'))need(typeof runner.abandonEffect==='function');
233
275
  if(Object.hasOwn(runner,'recoverBootstrapReview'))need(typeof runner.recoverBootstrapReview==='function');
276
+ if(Object.hasOwn(runner,'redoDevelop'))need(typeof runner.redoDevelop==='function');
277
+ if(Object.hasOwn(runner,'recoverCommit'))need(typeof runner.recoverCommit==='function');
278
+ if(Object.hasOwn(runner,'interruptions'))need(typeof runner.interruptions==='function');
234
279
  if(Object.hasOwn(runner,'inspectBootstrapAdmission'))need(typeof runner.inspectBootstrapAdmission==='function');
235
280
  need(options.allowAbandonReview===undefined||typeof options.allowAbandonReview==='boolean','invalid_input');
236
281
  let abandonPermission=options.allowAbandonReview===true;
@@ -238,6 +283,8 @@ export function createCmAiConversationEntry(options) {
238
283
  let abandonEffectPermission=options.allowAbandonEffect===true;
239
284
  need(options.allowBootstrapReviewRecovery===undefined||typeof options.allowBootstrapReviewRecovery==='boolean','invalid_input');
240
285
  let bootstrapReviewRecoveryPermission=options.allowBootstrapReviewRecovery===true;
286
+ need(options.allowDevelopRedo===undefined||typeof options.allowDevelopRedo==='boolean','invalid_input');
287
+ let developRedoPermission=options.allowDevelopRedo===true;
241
288
 
242
289
  const hostDecision=Object.hasOwn(options,'hostDecision')?json(options.hostDecision):null;
243
290
  let hostDecisionProvider=null,pendingReviewDecision=null;
@@ -258,6 +305,12 @@ export function createCmAiConversationEntry(options) {
258
305
  const decideQa=qaProvider?.decide,qaTimeout=qaProvider?.timeoutMs;
259
306
  let pendingQa=null;
260
307
  let qaExecutor=null,pendingExecution=null,cancellationEpoch=0;
308
+ // Q13: a scan failure (no log yet) leaves resources as they are; the writer still refuses closure.
309
+ const releaseQaResources=identity=>{
310
+ try{return releaseVerifiedQaResources({specsDir:options.specsDir,codeProject:options.codeProject,runId:identity.runId,
311
+ ...(Object.hasOwn(options,'qaLogHome')?{logHome:options.qaLogHome}:{})});}
312
+ catch(error){if(error?.code==='qa_resource_release_failed')throw error;return {released:[],open:[]};}
313
+ };
261
314
  const inFlightHandles=new Set();
262
315
  let rerunUnknownQa=options.rerunUnknownQa??false;need(typeof rerunUnknownQa==='boolean');
263
316
  let rerunBlockedQa=options.rerunBlockedQa??false;need(typeof rerunBlockedQa==='boolean');
@@ -351,7 +404,7 @@ export function createCmAiConversationEntry(options) {
351
404
  need(sameTask(identity,ownerIdentity)&&identity.attempt>=ownerIdentity.attempt,'identity_mismatch');
352
405
  // Stable run-definition identity can query/control or resume the current
353
406
  // attempt. Package-bound mutations must name the current attempt exactly.
354
- const stableControl=['status','cancel','advance','resume','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover'].includes(operation.operation)
407
+ const stableControl=['status','cancel','advance','resume','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover','develop_redo'].includes(operation.operation)
355
408
  &&sameIdentity(operation.identity,ownerIdentity);
356
409
  need(sameIdentity(operation.identity,identity)||stableControl,'identity_mismatch');
357
410
  if(operation.operation==='advance'){
@@ -390,6 +443,8 @@ export function createCmAiConversationEntry(options) {
390
443
  notCancelled();
391
444
  need(pendingExecution===null,'qa_execution_pending');
392
445
  const binding={specsDir:options.specsDir,feature:options.feature,identity:result.identity,packageDigest:result.packageDigest};
446
+ // Q13: close cleanup_failed command resources whose process group is proven gone.
447
+ releaseQaResources(result.identity);
393
448
  let previous,recovery=null,configurationRecovery=false,incompleteReport=false,timedOutCall=false;
394
449
  const timedOutRecovery=()=>inspectCmAiQaRecovery(binding,{timedOut:true,requestTimeoutMs:qaExecutor.requestTimeoutMs??null,
395
450
  attestation:rerunUnknownQa?qaEnvironmentFailure:null});
@@ -446,7 +501,7 @@ export function createCmAiConversationEntry(options) {
446
501
  // Later rounds require an accepted completed repair or explicit
447
502
  // evidence recovery/configuration revision. Unknown execution stops.
448
503
  const qaRound=recovery?recovery.qaRound+(rerunBlockedQa||configurationRecovery||timedOutCall?1:0):(repaired?accepted.qaRound+1:1);
449
- need(qaRound>=1&&qaRound<=3,'qa_round_invalid');
504
+ need(qaRound>=1&&qaRound<=QA_MAX_ROUNDS,'qa_round_invalid');
450
505
  testRunId=`qa-${digest(recovery?{...binding,previousTestRunId:recovery.testRunId}:
451
506
  repaired?{...binding,qaRound,repair:accepted.evidenceDigest}:binding).slice(0,48)}`;
452
507
  const invocation={...binding,codeProject:options.codeProject,testRunId,mode:qaExecutor.mode,caseCount:qaExecutor.caseCount,
@@ -472,7 +527,8 @@ export function createCmAiConversationEntry(options) {
472
527
  const interrupted=new Promise((_,reject)=>{
473
528
  controller.signal.addEventListener('abort',()=>reject(Object.assign(new Error('QA interrupted'),
474
529
  {code:timedOut?'qa_execution_timeout':'cancelled'})),{once:true});
475
- timer=setTimeout(()=>{timedOut=true;controller.abort();},qaExecutor.timeoutMs);
530
+ // Q12: the round deadline scales with the frozen plan.
531
+ timer=setTimeout(()=>{timedOut=true;controller.abort();},qaRoundDeadlineMs(qaExecutor));
476
532
  });
477
533
  const executed=await Promise.race([Promise.resolve().then(()=>{
478
534
  notCancelled();
@@ -543,7 +599,8 @@ export function createCmAiConversationEntry(options) {
543
599
  abandonPermission=false;
544
600
  const result=runner.abandonReview?.({allowed:true,reason:operation.reason})
545
601
  ??{outcome:'rejected',code:'review_abandon_unavailable'};
546
- if(result.outcome==='rejected')return summary(operation,{...runner.status(),code:result.code},'rejected');
602
+ if(result.outcome==='rejected')return summary(operation,{...runner.status(),code:result.code,
603
+ ...(typeof result.reason==='string'?{reason:result.reason}:{})},'rejected');
547
604
  return summary(operation,boundStatus(result,identity),'abandoned');
548
605
  }
549
606
  if(operation.operation==='abandon_effect'){
@@ -554,7 +611,18 @@ export function createCmAiConversationEntry(options) {
554
611
  ??{outcome:'rejected',code:'effect_abandon_unavailable'};
555
612
  if(result.outcome==='rejected')return summary(operation,{...runner.status(),code:result.code,
556
613
  ...(result.reason?{reason:result.reason}:{})},'rejected');
557
- return summary(operation,boundStatus(result,identity),'abandoned');
614
+ // V8: an interrupted step continues in the run (recorded); a void ends it.
615
+ return summary(operation,boundStatus(result,identity),result.code==='effect_abandoned'?'abandoned':'recorded');
616
+ }
617
+ if(operation.operation==='develop_redo'){
618
+ if(!developRedoPermission)return summary(operation,{...runner.status(),
619
+ code:'develop_redo_authorization_required'},'rejected');
620
+ developRedoPermission=false;
621
+ const result=runner.redoDevelop?.({allowed:true,reason:operation.reason})
622
+ ??{outcome:'rejected',code:'develop_redo_unavailable'};
623
+ if(result.outcome==='rejected')return summary(operation,{...runner.status(),code:result.code,
624
+ ...(result.reason?{reason:result.reason}:{})},'rejected');
625
+ return summary(operation,boundStatus(result,identity),'recorded');
558
626
  }
559
627
  if(operation.operation==='bootstrap_review_recover'){
560
628
  if(!bootstrapReviewRecoveryPermission)return summary(operation,{...runner.status(),
@@ -600,10 +668,21 @@ export function createCmAiConversationEntry(options) {
600
668
  if(decision===null)return summary(operation,{...status,code:'decision_required'},'awaiting');
601
669
  if(validateHostDecision(decision,status)==='denied')
602
670
  return summary(operation,{...status,code:'permission_denied'},'denied');
603
- const retries=retryReview(status)?status.calls.filter(call=>call.channel==='host-authorized'
604
- &&['failed','abandoned'].includes(call.terminal)
605
- &&call.contextId===status.reviewInvocation.registration.grant.logicalContextId).length:0;
606
- const effectId=`review-${identity.attempt}${retries?`-retry-${retries}`:''}`;
671
+ // A redispatch takes the next free id: at least the number of review effects THIS round's cache
672
+ // holds (runner.reviewEffectIds) and at least the host-authorized calls that ended without a
673
+ // verdict (an abandoned intent has a call but no cache entry), then skips any id already
674
+ // cached. A refused authorization leaves no call and keeps the previous round's
675
+ // reviewInvocation, so the call count alone can repeat an id and the cache would answer.
676
+ const resumed=runner.interruptions?.('review')??0,roundIds=runner.reviewEffectIds?.();
677
+ const idFor=n=>`review-${identity.attempt}${n?`-retry-${n}`:''}${resumed?`-resume-${resumed}`:''}`;
678
+ let retries=0;
679
+ if(retryReview(status)){
680
+ retries=Math.max(Array.isArray(roundIds)?roundIds.length:0,
681
+ status.calls.filter(call=>call.channel==='host-authorized'&&['failed','abandoned','not_dispatched'].includes(call.terminal)
682
+ &&call.contextId===status.reviewInvocation?.registration?.grant.logicalContextId).length);
683
+ if(Array.isArray(roundIds))while(roundIds.includes(idFor(retries)))retries++;
684
+ }
685
+ const effectId=idFor(retries);
607
686
  const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'review'});
608
687
  return effectSummary(operation,result,runner,identity);
609
688
  }
@@ -614,8 +693,13 @@ export function createCmAiConversationEntry(options) {
614
693
  if(status.code==='completion_package_changed'&&status.retryReady===false)return summary(operation,status,'rejected');
615
694
  const correction=correctionSummary(operation,status);if(correction)return correction;
616
695
  need(['approved','fixture_completed'].includes(status.state)||completionRetryable(status),'completion_not_ready');
617
- const retries=runner.completionBlocks?.()??0;
618
- const effectId=`complete-${identity.attempt}${retries?`-retry-${retries}`:''}`;
696
+ // A45: finish the interrupted task commit from its journaled plan only.
697
+ if(status.code==='complete_commit_interrupted'){
698
+ const recovered=runner.recoverCommit?.()??{outcome:'rejected',code:'commit_recovery_unavailable'};
699
+ return effectSummary(operation,recovered,runner,identity);
700
+ }
701
+ const retries=runner.completionBlocks?.()??0,resumed=runner.interruptions?.('complete')??0;
702
+ const effectId=`complete-${identity.attempt}${retries?`-retry-${retries}`:''}${resumed?`-resume-${resumed}`:''}`;
619
703
  const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'complete'});
620
704
  return effectSummary(operation,result,runner,identity);
621
705
  }
@@ -758,6 +842,10 @@ export function createCmAiConversationEntry(options) {
758
842
  return freeze({...summary(operation,{...status,code:'documentation_sync_blocked'},'blocked'),
759
843
  ...closeoutSummary(knowledgeCloseout,documentation)});
760
844
  const finalQa=projectQaSummary(operation,status,options);if(finalQa)return finalQa;
845
+ const resources=releaseQaResources(identity);
846
+ if(resources.open.length)return summary(operation,{...status,code:'qa_resources_open',
847
+ reason:`qa_resources_open: 以下运行资源仍未释放(写入器会拒绝 run_done):${resources.open.slice(0,10).map(item=>`${item.resourceId}(${item.verdict})`).join('、')}。`
848
+ +'宿主只在运行日志记有该命令进程组身份且核对进程组已退出时补记释放;先结束残留进程后重发 run_finalize,记录里没有进程身份的旧资源需人工处理。'},'blocked');
761
849
  const input={specsDir:options.specsDir,codeProject:options.codeProject,feature:options.feature,identity,
762
850
  packageDigest:operation.packageDigest,contextDigest:refresh.contextDigest,
763
851
  documentationSyncId:documentation.syncId};
@@ -784,7 +872,10 @@ export function createCmAiConversationEntry(options) {
784
872
  // the review that asked for it, before any develop intent, and say so.
785
873
  if(options.holdRevision===true&&status.state==='changes_requested')
786
874
  return summary(operation,{...status,code:'revision_answer_required'},'awaiting');
787
- const learningInput=inspectCmAiTaskLearningInput({specsDir:options.specsDir,codeProject:options.codeProject,
875
+ // A re-check (check_answer_*) re-runs the checks of the delivery already made:
876
+ // it binds that delivery's Learning input, never a freshly read one (its
877
+ // writeback may already have changed AGENTS.md).
878
+ const learningInput=runner.recheckLearningInput?.()??inspectCmAiTaskLearningInput({specsDir:options.specsDir,codeProject:options.codeProject,
788
879
  feature:options.feature,identity,applicableAgentFiles:applicableAgentFiles??[],
789
880
  ...(options.featureSelection===undefined?{}:{featureSelection:options.featureSelection})},
790
881
  {admission:runner.inspectBootstrapAdmission?.()??null,parallelSelection:options.parallelSelection??null});
@@ -794,8 +885,8 @@ export function createCmAiConversationEntry(options) {
794
885
  &&call.failureResult?.code==='invalid_result'&&call.failureResult.retryable===true).length;
795
886
  // Both kinds of local rejection need a fresh effect id: an invalid developer
796
887
  // result, and one the host gate blocked before the review package existed.
797
- const retries=rejectedValues+(runner.verificationBlocks?.()??0);
798
- const effectId=`develop-${identity.attempt}${retries?`-retry-${retries}`:''}`;
888
+ const retries=rejectedValues+(runner.verificationBlocks?.()??0),resumed=runner.interruptions?.('develop')??0;
889
+ const effectId=`develop-${identity.attempt}${retries?`-retry-${retries}`:''}${resumed?`-resume-${resumed}`:''}`;
799
890
  const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'develop',learningInput});
800
891
  return effectSummary(operation,result,runner,identity);
801
892
  }
@@ -803,7 +894,7 @@ export function createCmAiConversationEntry(options) {
803
894
  let token=null,operation=null;const epoch=cancellationEpoch;
804
895
  try{
805
896
  operation=readOperation(raw);
806
- if(!['status','cancel','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover'].includes(operation.operation)){
897
+ if(!['status','cancel','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover','develop_redo'].includes(operation.operation)){
807
898
  token=Symbol(operation.operation);inFlightHandles.add(token);
808
899
  }
809
900
  const routed=await route(operation);
@@ -7,6 +7,7 @@ import {digest,hex,id,json,need,shape,text,validIdentity} from './effect-contrac
7
7
  import {readQaAttachment} from './qa-attachment.mjs';
8
8
  import {writeCmAiQaStatus} from './cm-ai-run-finalizer.mjs';
9
9
  import {scanRows} from './log-rows.mjs';
10
+ import {QA_MAX_ROUNDS,qaRoundLimit,nonProductSupersession} from './qa-round-budget.mjs';
10
11
  import {readExecutionSnapshot} from './execution-snapshot.mjs';
11
12
  import {beforeFirstQaRound,qaRevisionChain,readQaConfigRevision} from './qa-config-revision.mjs';
12
13
 
@@ -204,16 +205,33 @@ function partialPassCases(items,code){
204
205
  // elapsed since case_start (log times are whole seconds) and an explicit operator
205
206
  // attestation (--qa-environment-failure), recorded on the superseded row.
206
207
  // A session-declared BLOCKED, any FAIL or other BLOCKED refuses.
207
- function timedOutCases(items,code,requestTimeoutMs,attestation=null){
208
+ // Q06/Q11: the same holds for a call stopped by a host death or a hard-invalid
209
+ // answer. Rows the session itself declared BLOCKED (host_declared_blocked), and
210
+ // rows the host judged BLOCKED for an evidence, environment or cleanup gap
211
+ // (blocked_reason, written by current executors), are host or answer problems
212
+ // too: they are listed as host_blocked_cases. An unresolved [需确认], a missing
213
+ // capability, a FAIL, or an older row that cannot tell still refuses.
214
+ const HOST_JUDGED_BLOCKED=['evidence','environment','cleanup'];
215
+ // context {specsDir,feature}: the approved test contract decides [需确认].
216
+ function timedOutCases(items,code,requestTimeoutMs,attestation=null,allowHostBlocked=false,context=null){
208
217
  need(attestation===null||validEnvironmentFailureReason(attestation),code);
209
218
  need(requestTimeoutMs===null||Number.isSafeInteger(requestTimeoutMs)&&requestTimeoutMs>0&&requestTimeoutMs<=3600000,code);
210
219
  need(!items.some(({row})=>['complete','abandoned','superseded'].includes(row.phase)
211
220
  ||(row.phase==='case_complete'&&row.result!=='PASS')),code);
212
- const started=new Map(),timedOut=[];
221
+ const started=new Map(),timedOut=[],hostBlocked=[];
213
222
  for(const {row} of items){
214
223
  if(row.phase==='case_start'){id(row.case_id);started.set(row.case_id,row.at);}
215
224
  if(row.phase!=='case_blocked')continue;
216
- id(row.case_id);need(row.result==='BLOCKED'&&row.host_declared_blocked!==true,code);
225
+ id(row.case_id);need(row.result==='BLOCKED',code);
226
+ if(row.host_declared_blocked===true||HOST_JUDGED_BLOCKED.includes(row.blocked_reason)){
227
+ // An original FAIL the host downgraded, a row that does not keep the
228
+ // session's verdict, and an unresolved [需确认] in the approved contract
229
+ // refuse before any host-fault eligibility.
230
+ need(allowHostBlocked&&context!==null&&['PASS','BLOCKED'].includes(row.answered_verdict)
231
+ &&(row.host_declared_blocked!==true||row.answered_verdict==='BLOCKED')
232
+ &&!['needs_confirmation','unavailable'].includes(row.blocked_reason),code);
233
+ hostBlocked.push(row.case_id);continue;
234
+ }
217
235
  if(Object.hasOwn(row,'host_request_timeout'))need(row.host_request_timeout===true,code);
218
236
  else{
219
237
  const elapsed=Date.parse(row.at)-Date.parse(started.get(row.case_id));
@@ -222,9 +240,11 @@ function timedOutCases(items,code,requestTimeoutMs,attestation=null){
222
240
  }
223
241
  timedOut.push(row.case_id);
224
242
  }
225
- need(timedOut.length>0,code);
243
+ need(timedOut.length+hostBlocked.length>0,code);
244
+ if(hostBlocked.length){const contract=contractCases(context.specsDir,context.feature,code);
245
+ for(const caseId of hostBlocked)need(!confirmationPending(contract.get(caseId)),code);}
226
246
  const passed=items.filter(({row})=>row.phase==='case_complete').map(({row})=>row.case_id);
227
- return {timedOut:[...new Set(timedOut)].sort(),passed:[...new Set(passed)].sort()};
247
+ return {timedOut:[...new Set(timedOut)].sort(),hostBlocked:[...new Set(hostBlocked)].sort(),passed:[...new Set(passed)].sort()};
228
248
  }
229
249
 
230
250
  // host-check reports a command that produced no exit code as `unavailable`
@@ -293,7 +313,10 @@ function passBacking(items,specsDir,feature,cases,code){
293
313
  // incomplete: the call wrote its fixed report but no complete row (a pre-fix host
294
314
  // rejected stale_qa in between). The report is then the only result; its counts
295
315
  // stand in for the complete row and every other rule applies unchanged.
296
- function recoverableCases(items,specsDir,environment,code='qa_rerun_not_blocked_by_evidence',environmentFailure=false,legacyRule=false,incomplete=false){
316
+ // verdictRule (recovery_rule 3): a browser BLOCKED counts as a host fault only
317
+ // when the durable case row keeps the session's own verdict (answered_verdict)
318
+ // and it was not a FAIL; rows without it (older format) are not recoverable here.
319
+ function recoverableCases(items,specsDir,environment,code='qa_rerun_not_blocked_by_evidence',environmentFailure=false,legacyRule=false,incomplete=false,verdictRule=false){
297
320
  const completes=items.filter(({row})=>row.phase==='complete'),start=items[0]?.row;
298
321
  need(completes.length===(incomplete?0:1)&&start?.phase==='start'&&!(incomplete&&(legacyRule||environmentFailure)),code);
299
322
  let complete=incomplete?null:completes[0].row;
@@ -336,12 +359,23 @@ function recoverableCases(items,specsDir,environment,code='qa_rerun_not_blocked_
336
359
  // executor appended when the session answered, not by the mutable report.
337
360
  const declaredInLog=new Set(items.filter(({row})=>row.phase==='case_blocked'&&row.host_declared_blocked===true)
338
361
  .map(({row})=>row.case_id));
362
+ const blockedRows=new Map(items.filter(({row})=>row.phase==='case_blocked').map(({row})=>[row.case_id,row]));
363
+ // An original FAIL the host downgraded, a missing capability and an unresolved
364
+ // [需确认] refuse before any host-fault eligibility.
365
+ const sessionVerdictOk=row=>{
366
+ if(!verdictRule)return true;
367
+ const logged=blockedRows.get(row.id);
368
+ if(!logged||['needs_confirmation','unavailable'].includes(logged.blocked_reason))return false;
369
+ if(row.hostRequestTimeout===true&&logged.host_request_timeout===true&&!Object.hasOwn(logged,'answered_verdict'))return true;
370
+ return ['PASS','BLOCKED'].includes(logged.answered_verdict)
371
+ &&(logged.answered_verdict!=='BLOCKED'||logged.host_declared_blocked===true);
372
+ };
339
373
  const eligible=row=>(
340
374
  row.kind==='logic'&&resolved(row)&&(row.staticVerdict==='INSUFFICIENT_EVIDENCE'
341
375
  // Blocked only by a mapped command without exit code, derived from the
342
376
  // recorded command rows; the executor's marker has to agree.
343
377
  ||row.staticVerdict==='SUPPORTED'&&mapped(row,unavailableCommand)&&row.commandUnavailable===true)
344
- ||row.kind==='browser'&&resolved(row)&&(typeof row.evidenceProblem==='string'&&row.evidenceProblem.length>0
378
+ ||row.kind==='browser'&&resolved(row)&&sessionVerdictOk(row)&&(typeof row.evidenceProblem==='string'&&row.evidenceProblem.length>0
345
379
  ||row.cleanup==='failed'||row.hostRequestTimeout===true||declaredInLog.has(row.id)&&row.hostDeclaredBlocked===true
346
380
  ||environment!=null&&row.environment!=null&&digest(row.environment)!==digest(environment))
347
381
  ||unavailableCommand(row));
@@ -381,12 +415,12 @@ function validateConfigurationSupersession(row,specsDir,code){
381
415
 
382
416
  // Abandonment reuses a round; superseded completed evidence advances it.
383
417
  function validateRunSequence(items,code='qa_round_invalid',specsDir){
384
- const starts=[],ids=new Set();let current=null,abandoned=false,superseded=false;
418
+ const starts=[],ids=new Set();let current=null,abandoned=false,superseded=false,freed=0;
385
419
  for(const item of items){
386
420
  const row=item.row;
387
421
  if(row.phase==='start'){
388
422
  id(row.operation_id);need(!ids.has(row.operation_id),code);ids.add(row.operation_id);
389
- need(row.attempt===(current?current.attempt+(abandoned?0:1):1)&&row.attempt<=3,code);
423
+ need(row.attempt===(current?current.attempt+(abandoned?0:1):1)&&row.attempt<=qaRoundLimit(freed),code);
390
424
  if(abandoned){
391
425
  // Legacy successors retain their plan; explicit links may bind a fresh plan.
392
426
  if(row.previous_test_run_id===undefined)need(row.mode===current.mode&&row.case_count===current.case_count,code);
@@ -401,30 +435,35 @@ function validateRunSequence(items,code='qa_round_invalid',specsDir){
401
435
  }else{
402
436
  need(current&&row.operation_id===current.operation_id&&row.attempt===current.attempt&&!abandoned&&!superseded,code);
403
437
  if(row.phase==='superseded'){
404
- need(current.attempt<3&&row.previous_test_run_id===current.operation_id
438
+ need(current.attempt<qaRoundLimit(freed+(nonProductSupersession(row.reason)?1:0))&&row.previous_test_run_id===current.operation_id
405
439
  &&row.mode===current.mode&&row.case_count===current.case_count,code);
406
440
  const prior=items.filter(entry=>entry.position<item.position&&entry.row.operation_id===row.operation_id);
407
441
  if(row.reason==='qa_configuration_revision'){
408
442
  need(prior.filter(entry=>entry.row.phase==='complete').length===1,code);
409
443
  validateConfigurationSupersession(row,specsDir,code);
410
444
  }else if(row.reason==='host_request_timeout'){
411
- const cases=timedOutCases(prior,code,row.request_timeout_ms??null,row.legacy_timeout_attestation??null);
445
+ // Rows before host_blocked_cases existed could list no such case.
446
+ const cases=timedOutCases(prior,code,row.request_timeout_ms??null,row.legacy_timeout_attestation??null,
447
+ Object.hasOwn(row,'host_blocked_cases'),{specsDir,feature:row.feature});
412
448
  need(row.request_timeout_ms!==null&&JSON.stringify(row.timed_out_cases)===JSON.stringify(cases.timedOut)
449
+ &&JSON.stringify(row.host_blocked_cases??[])===JSON.stringify(cases.hostBlocked)
450
+ &&(!Object.hasOwn(row,'host_blocked_cases')||cases.hostBlocked.length>0)
413
451
  &&JSON.stringify(row.partial_pass_cases)===JSON.stringify(cases.passed),code);
414
452
  }else{
415
453
  const declared=row.reason==='declared_environment_failure';
416
454
  need(declared?validEnvironmentFailureReason(row.environment_failure_reason):row.reason==='host_evidence_problem',code);
417
455
  // Rows without recovery_rule were written by released versions before
418
456
  // this change (the pre-branch format) under the original rule.
419
- const legacy=row.recovery_rule===undefined;need(legacy||row.recovery_rule===2,code);
457
+ const legacy=row.recovery_rule===undefined;need(legacy||[2,3].includes(row.recovery_rule),code);
420
458
  // incomplete_report: the superseded call had a fixed report but no complete row.
421
459
  const incomplete=row.incomplete_report===true;
422
460
  need(row.incomplete_report===undefined||incomplete&&!legacy&&!declared
423
461
  &&!prior.some(entry=>entry.row.phase==='complete'),code);
424
- const cases=recoverableCases(prior,specsDir,row.expected_environment,code,declared,legacy,incomplete);
462
+ const cases=recoverableCases(prior,specsDir,row.expected_environment,code,declared,legacy,incomplete,row.recovery_rule===3);
425
463
  need(JSON.stringify(row.blocked_cases)===JSON.stringify(cases.blocked)
426
464
  &&(declared?JSON.stringify(row.failed_cases)===JSON.stringify(cases.failed):row.failed_cases===undefined),code);
427
465
  }
466
+ if(nonProductSupersession(row.reason))freed++;
428
467
  superseded=true;
429
468
  }
430
469
  if(row.phase==='abandoned'){
@@ -439,7 +478,7 @@ function validateRunSequence(items,code='qa_round_invalid',specsDir){
439
478
  }
440
479
  }
441
480
  }
442
- need(starts.length>0,code);return starts;
481
+ need(starts.length>0,code);starts.freed=freed;return starts;
443
482
  }
444
483
 
445
484
  function qaRunRows(input){
@@ -472,9 +511,11 @@ export function inspectCmAiQaRecovery(input,{blocked=false,environment=null,envi
472
511
  const declared=recorded?recorded.reason==='declared_environment_failure':environmentFailure!==null;
473
512
  const prior=runs.filter(({row})=>row.phase!=='superseded');
474
513
  const incomplete=recorded?recorded.incomplete_report===true:!prior.some(({row})=>row.phase==='complete');
514
+ // A fresh supersession is written under recovery_rule 3; a recorded row keeps its own rule.
475
515
  const cases=recoverableCases(prior,input.specsDir,environment,'qa_rerun_not_blocked_by_evidence',declared,
476
- recorded!==undefined&&recorded.recovery_rule===undefined,incomplete);
477
- need(start.attempt<3,'qa_round_invalid');
516
+ recorded!==undefined&&recorded.recovery_rule===undefined,incomplete,recorded===undefined||recorded.recovery_rule===3);
517
+ // A recorded supersession is already counted in starts.freed.
518
+ need(start.attempt<qaRoundLimit(starts.freed+(recorded===undefined&&!declared?1:0)),'qa_round_invalid');
478
519
  return {testRunId:start.operation_id,qaRound:start.attempt,mode:start.mode,caseCount:start.case_count,
479
520
  blockedCases:cases.blocked,failedCases:cases.failed,superseded:recorded!==undefined,incompleteReport:incomplete};
480
521
  }
@@ -486,10 +527,12 @@ export function inspectCmAiQaRecovery(input,{blocked=false,environment=null,envi
486
527
  need(recorded===undefined?!exists:recorded.reason==='host_request_timeout','qa_execution_unknown');
487
528
  const timeout=recorded?recorded.request_timeout_ms??null:requestTimeoutMs;
488
529
  const attested=recorded?recorded.legacy_timeout_attestation??null:attestation;
489
- const cases=timedOutCases(runs.filter(({row})=>row.phase!=='superseded'),'qa_execution_unknown',timeout,attested);
490
- need(start.attempt<3,'qa_round_invalid');
530
+ const cases=timedOutCases(runs.filter(({row})=>row.phase!=='superseded'),'qa_execution_unknown',timeout,attested,
531
+ recorded===undefined||Object.hasOwn(recorded,'host_blocked_cases'),{specsDir:input.specsDir,feature:start.feature});
532
+ need(start.attempt<qaRoundLimit(starts.freed+(recorded===undefined?1:0)),'qa_round_invalid');
491
533
  return {testRunId:start.operation_id,qaRound:start.attempt,mode:start.mode,caseCount:start.case_count,
492
- timedOutCases:cases.timedOut,partialPassCases:cases.passed,requestTimeoutMs:timeout,attestation:attested,superseded:recorded!==undefined};
534
+ timedOutCases:cases.timedOut,hostBlockedCases:cases.hostBlocked,partialPassCases:cases.passed,
535
+ requestTimeoutMs:timeout,attestation:attested,superseded:recorded!==undefined};
493
536
  }
494
537
  const passed=partialPassCases(runs,'qa_execution_unknown');
495
538
  // A report without complete is an unconfirmed result: a host that found the run
@@ -610,7 +653,7 @@ export function recordCmAiQaRun(input) {
610
653
  need(Number.isSafeInteger(input.caseCount)&&input.caseCount>0);
611
654
  need(['start','complete','abandoned','superseded'].includes(input.phase));
612
655
  const qaRound=input.qaRound??1;
613
- need(Number.isSafeInteger(qaRound)&&qaRound>=1&&qaRound<=3,'qa_round_invalid');
656
+ need(Number.isSafeInteger(qaRound)&&qaRound>=1&&qaRound<=QA_MAX_ROUNDS,'qa_round_invalid');
614
657
  const binding={specsDir:input.specsDir,feature:input.feature,identity:input.identity,packageDigest:input.packageDigest};
615
658
  let passed=[],blockedCases=[],failedCases=[],declaredFailure=null,incompleteReport=false,timedOut=null;
616
659
  if(Object.hasOwn(input,'environmentFailure'))need(input.phase==='superseded'&&!input.configurationRevision
@@ -654,6 +697,9 @@ export function recordCmAiQaRun(input) {
654
697
  scanRows(path.join(input.specsDir,'运行日志.jsonl'),row=>{
655
698
  need(!(row.event==='test_run'&&row.operation_id===input.testRunId),'qa_round_invalid');
656
699
  });
700
+ // Q14: a round beyond three starts only when host-caused rounds gave one back.
701
+ const prior=qaRunRows(binding);
702
+ need(qaRound<=qaRoundLimit(prior.length?validateRunSequence(prior,'qa_round_invalid',input.specsDir).freed:0),'qa_round_invalid');
657
703
  if(previous===null)need(qaRound===1,'qa_round_invalid');
658
704
  else if(!Object.hasOwn(input,'previousTestRunId')){
659
705
  const failure=inspectCmAiQaFailure({...binding,testRunId:previous.testRunId});
@@ -687,10 +733,11 @@ export function recordCmAiQaRun(input) {
687
733
  if(input.phase==='abandoned')Object.assign(data,{previous_test_run_id:input.testRunId,reason:'host_terminated',partial_pass_cases:passed});
688
734
  if(timedOut)Object.assign(data,{previous_test_run_id:input.testRunId,reason:'host_request_timeout',
689
735
  timed_out_cases:timedOut.timedOutCases,partial_pass_cases:timedOut.partialPassCases,
736
+ ...(timedOut.hostBlockedCases.length?{host_blocked_cases:timedOut.hostBlockedCases}:{}),
690
737
  ...(timedOut.requestTimeoutMs===null?{}:{request_timeout_ms:timedOut.requestTimeoutMs}),
691
738
  ...(timedOut.attestation===null?{}:{legacy_timeout_attestation:timedOut.attestation})});
692
739
  else if(input.phase==='superseded')Object.assign(data,{previous_test_run_id:input.testRunId,
693
- reason:declaredFailure===null?'host_evidence_problem':'declared_environment_failure',recovery_rule:2,
740
+ reason:declaredFailure===null?'host_evidence_problem':'declared_environment_failure',recovery_rule:3,
694
741
  blocked_cases:blockedCases,expected_environment:input.expectedEnvironment??null,
695
742
  ...(incompleteReport?{incomplete_report:true}:{}),
696
743
  ...(declaredFailure===null?{}:{failed_cases:failedCases,environment_failure_reason:declaredFailure})});
@@ -782,7 +829,7 @@ function inspectQaResult(input,failureSource,historical=false) {
782
829
  need(candidates.length>0,'qa_result_invalid');
783
830
  for(const {row} of candidates)need(typeof row.operation_id==='string'
784
831
  &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(row.operation_id)
785
- &&Number.isSafeInteger(row.attempt)&&row.attempt>=1&&row.attempt<=3,'qa_result_invalid');
832
+ &&Number.isSafeInteger(row.attempt)&&row.attempt>=1&&row.attempt<=QA_MAX_ROUNDS,'qa_result_invalid');
786
833
  const latestStarts=candidates.filter(item=>item.row.phase==='start');
787
834
  need(latestStarts.length>0,'qa_result_incomplete');
788
835
  validateRunSequence(candidates,'qa_result_invalid',input.specsDir);
@@ -14,8 +14,11 @@ function relativeFile(value){
14
14
 
15
15
  // Pure validation also used by offline baseline/package readers. Never repairs
16
16
  // or requires the present filesystem merely to read historical evidence.
17
+ // A proposal is applied once per selected root, so this also bounds the
18
+ // apply subprocesses one develop journals (durable-runner-state.mjs).
19
+ export const MAX_CODE_PROJECTS=256;
17
20
  export function validateCodeProjectPaths(raw){
18
- const values=json(raw);need(Array.isArray(values)&&values.length>0&&values.length<=256,'invalid_code_projects');
21
+ const values=json(raw);need(Array.isArray(values)&&values.length>0&&values.length<=MAX_CODE_PROJECTS,'invalid_code_projects');
19
22
  const selected=values.map(relativeFile).sort(),aliases=selected.map(value=>value.toLowerCase());
20
23
  for(let i=0;i<aliases.length;i++)for(let j=0;j<i;j++)
21
24
  need(aliases[i]!==aliases[j]&&!aliases[i].startsWith(aliases[j]+'/')
@@ -20,6 +20,9 @@ Application status is applied (note explains the lesson and action) or no_releva
20
20
  Retrospective status is no_new_lesson (candidates empty and reason null), lesson_candidate (1-3 candidates and reason null),
21
21
  or writeback_pending (1-3 candidates and a reason). Each candidate has classification (structured or memory_only),
22
22
  trigger, action and evidence (relative file paths). The host binds identities and computes digests; do not invent hashes.
23
+ Bounds (an answer over any bound is rejected; lengths count UTF-16 code units, so an emoji counts as 2): application.note is one line of at most 512;
24
+ retrospective reason and each candidate trigger and action are one line of at most 240;
25
+ 1-3 candidates, each with 1-8 distinct relative evidence paths of at most 512; a blocked reason is at most 1000 bytes.
23
26
  Without learningInput, return only outcome and reason. A blocked result may include reason explaining why implementation is impossible (string, at most 1000 UTF-8 bytes, no NUL); application and retrospective are optional when blocked.
24
27
  The top-level reason explains blocked outcomes; otherwise it must be null. Use null when no explanation is available.
25
28
  Use outcome blocked when implementation is not possible. Do not claim implementation if no implementation was made.
@@ -86,6 +89,10 @@ export function validateDeveloperValue(value,request) {
86
89
  const input=request.payload.learningInput;
87
90
  validTaskLearningInput(input,request.identity,input.feature);
88
91
  shape(value.application,['status','note']);shape(value.retrospective,['status','candidates','reason']);
92
+ // Name the most common bound in the failure (the Learning constructor below
93
+ // enforces the same rule, with the generic code).
94
+ if(typeof value.application.note==='string')need(value.application.note.length<=512
95
+ &&!/[\n\r\0\u2028\u2029]/u.test(value.application.note),'application_note_limit');
89
96
  const binding={feature:input.feature,identity:request.identity,learningDigest:input.learningDigest};
90
97
  return {outcome:'implemented',
91
98
  application:createCmAiTaskLearningApplication({...binding,...value.application}),
@@ -47,11 +47,20 @@ export const hostResponseFailed=row=>Boolean(row.error||row.result?.state==='unk
47
47
  // leave the host waiting forever on the same call. Say why and end the session.
48
48
  const rejectedReplyHint=code=>code==='host_response_too_large'
49
49
  ?'应答超过宿主输入上限:在 PLAN.permissions 加 "--input-limit","<字节数>"(65536–4194304,默认 65536)'
50
+ :code==='host_response_late'?'应答到得太晚:宿主已按应答期限或取消停止等待这次反问(期限见 CM_HOST_ANSWER_TIMEOUT_MINUTES)'
50
51
  :'应答与宿主这次反问不匹配(会话、调用或请求摘要不对)';
51
52
 
52
53
  // beforeRequest runs after host_ready, i.e. after the host itself accepted every
53
54
  // launch input, admission and the run store, and before the operation is sent.
54
55
  // A returned refusal closes the session without any operation and exits 2.
56
+ // A driver that deliberately leaves a host question unanswered (a re-asked
57
+ // confirmation the current user must decide) ends with exit code 2, whatever the
58
+ // host's final row says, so callers see a stop that needs a person.
59
+ let deliberateStop=false;
60
+ export function deliberatelyUnanswered(message){
61
+ if(!deliberateStop){deliberateStop=true;process.on('exit',()=>{process.exitCode=2;});}
62
+ return Object.assign(new Error(message),{code:'confirm_reask_decision_required'});
63
+ }
55
64
  export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null}){
56
65
  const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe']});
57
66
  const control=new AbortController();