@aibyzero/cm-workflow 0.16.9 → 0.17.1

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 (165) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +18 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +16 -1
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +29 -13
  8. package/docs/cm-control-policy-v2.md +331 -0
  9. package/docs/execution-optimizations.md +1 -1
  10. package/docs/external-models.md +3 -3
  11. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  12. package/docs/human-correction.md +5 -5
  13. package/docs/installation.md +1 -1
  14. package/docs/js-workflow-control.md +104 -85
  15. package/docs/next-steps.md +11 -0
  16. package/docs/untested-branches.md +2 -3
  17. package/docs/user-guide.md +3 -3
  18. package/package.json +1 -1
  19. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
  20. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  21. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  22. package/runtime/js/cm-ai/control-policy.mjs +112 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  24. package/runtime/js/cm-ai/drive-core.mjs +124 -25
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  26. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  27. package/runtime/js/cm-ai/host-check.mjs +3 -1
  28. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  29. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  31. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  32. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  33. package/runtime/js/cm-ai/host-session.mjs +41 -8
  34. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  35. package/runtime/js/cm-ai/host-tool-bridge.mjs +25 -9
  36. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  37. package/runtime/js/cm-ai/host.mjs +1 -2
  38. package/runtime/js/cm-ai/operator-guidance.mjs +57 -54
  39. package/runtime/js/cm-ai/review-package.mjs +16 -4
  40. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  41. package/runtime/js/cm-ai/task-runner.mjs +41 -101
  42. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  43. package/runtime/js/cm-prd/review-host.mjs +1 -1
  44. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  45. package/runtime/js/cm-prd/summary.mjs +27 -12
  46. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  47. package/runtime/js/notify-send.mjs +15 -14
  48. package/runtime/js/notify.mjs +27 -4
  49. package/runtime/js/policy-binding-compat.mjs +2 -1
  50. package/runtime/review.md +61 -7
  51. package/runtime/task-gates.md +107 -9
  52. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  53. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  54. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  55. package/scripts/cm-ai-batch-drive.mjs +50 -31
  56. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  57. package/scripts/cm-ai-batch-host.mjs +39 -20
  58. package/scripts/cm-ai-batch-host.test.mjs +83 -47
  59. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  60. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  61. package/scripts/cm-ai-batch-run.mjs +46 -14
  62. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  63. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  64. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  65. package/scripts/cm-ai-control-policy.test.mjs +192 -0
  66. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  67. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  68. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  69. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  70. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  71. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  72. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +57 -27
  73. package/scripts/cm-ai-drive.mjs +96 -54
  74. package/scripts/cm-ai-drive.test.mjs +46 -87
  75. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  77. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  78. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  79. package/scripts/cm-ai-host-fixture.mjs +47 -16
  80. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  81. package/scripts/cm-ai-host.mjs +103 -93
  82. package/scripts/cm-ai-host.test.mjs +34 -18
  83. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  84. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  85. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  86. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  87. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  88. package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
  89. package/scripts/cm-ai-progress.test.mjs +10 -8
  90. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  91. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  92. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  93. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  94. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  95. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  96. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  97. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  98. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  99. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  100. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  101. package/scripts/cm-ai-review-timeout.test.mjs +35 -128
  102. package/scripts/cm-ai-run.mjs +78 -24
  103. package/scripts/cm-ai-run.test.mjs +11 -38
  104. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  105. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  106. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  107. package/scripts/cm-ai-supersede.test.mjs +3 -10
  108. package/scripts/cm-blocked-reason.test.mjs +2 -3
  109. package/scripts/cm-capability-gate.test.mjs +33 -1
  110. package/scripts/cm-check-drive-files.mjs +1 -1
  111. package/scripts/cm-check-host.test.mjs +1 -1
  112. package/scripts/cm-check-runtime.sh +1 -1
  113. package/scripts/cm-claude-probe.test.mjs +26 -0
  114. package/scripts/cm-claude-review-stream.test.mjs +36 -0
  115. package/scripts/cm-claude-worker.test.mjs +21 -3
  116. package/scripts/cm-controlled-correction.test.mjs +469 -0
  117. package/scripts/cm-drive-liveness.test.mjs +83 -0
  118. package/scripts/cm-external-batch-host.test.mjs +38 -17
  119. package/scripts/cm-external-model-host.test.mjs +1 -1
  120. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  121. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  122. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  123. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  124. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  125. package/scripts/cm-host-liveness.test.mjs +150 -0
  126. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  127. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  128. package/scripts/cm-host-review-authority.test.mjs +0 -31
  129. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  130. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  131. package/scripts/cm-notify-command.test.mjs +54 -18
  132. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  133. package/scripts/cm-notify.mjs +16 -4
  134. package/scripts/cm-notify.test.mjs +135 -29
  135. package/scripts/cm-patrol.test.mjs +3 -2
  136. package/scripts/cm-prd-drive.test.mjs +1 -1
  137. package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
  138. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  139. package/scripts/cm-prd-summary.test.mjs +31 -0
  140. package/scripts/cm-release-smoke.sh +2 -14
  141. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  142. package/scripts/cm-task-gate.mjs +368 -34
  143. package/scripts/cm-task-gate.py +2 -0
  144. package/scripts/cm-task-gate.test.mjs +252 -4
  145. package/scripts/cm-test-suite.mjs +109 -0
  146. package/scripts/cm-test-suite.test.mjs +162 -0
  147. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  148. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  149. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  150. package/scripts/policy-binding-compat.test.mjs +4 -0
  151. package/skills/cm-ai/SKILL.md +8 -6
  152. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  153. package/skills/cm-ai/references/N4-review.md +11 -21
  154. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  155. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  156. package/skills/cm-ai/references/js-host-modes.md +35 -14
  157. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  158. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  159. package/skills/cm-ai/references/js-host.md +98 -29
  160. package/skills/cm-fix/SKILL.md +12 -0
  161. package/skills/cm-init/references/js-host.md +1 -1
  162. package/skills/cm-prd/references/js-host.md +1 -1
  163. package/skills/cm-refactor/SKILL.md +12 -0
  164. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  165. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibyzero/cm-workflow",
3
- "version": "0.16.9",
3
+ "version": "0.17.1",
4
4
  "description": "Spec-driven business development workflow for Pi, Codex, and Claude Code",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -33,6 +33,12 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
33
33
  b: typeof block?.type === 'string' && /^[A-Za-z_]{1,32}$/.test(block.type) ? block.type : null,
34
34
  t: typeof tool === 'string' && /^[A-Za-z0-9_.:-]{1,64}$/.test(tool) ? tool : null,
35
35
  e: typeof isError === 'boolean' ? isError : null});
36
+ const startupNotice = subtype => {
37
+ if (noticeCount >= 32) reject('unexpected_event');
38
+ noticeCount++;
39
+ if (subtype === 'dev_intent') reportClaudeDevIntentNotice(onNotice);
40
+ else try { if (typeof onNotice === 'function') onNotice({kind:'claude_system_notice', subtype:'ui_invalidate'}); } catch {}
41
+ };
36
42
  return Object.freeze({
37
43
  accept(message) {
38
44
  if (!message || typeof message !== 'object' || Array.isArray(message)) reject('invalid_event');
@@ -41,11 +47,11 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
41
47
  || message.session_id.length > 256) reject('invalid_session');
42
48
  if (session !== null && session !== message.session_id) reject('session_mismatch');
43
49
  if (stage === 'init') {
44
- if (message.type === 'system' && message.subtype === 'dev_intent') {
45
- if (noticeCount >= 32) reject('unexpected_event');
46
- noticeCount++;
50
+ // CLI 2.1.289 emits UI invalidation before init. It has no review
51
+ // result and never initializes a turn; retain only its fixed subtype.
52
+ if (message.type === 'system' && ['dev_intent','ui_invalidate'].includes(message.subtype)) {
47
53
  session = message.session_id;
48
- reportClaudeDevIntentNotice(onNotice);
54
+ startupNotice(message.subtype);
49
55
  return;
50
56
  }
51
57
  if (message.type !== 'system' || message.subtype !== 'init') reject('missing_init');
@@ -62,10 +68,8 @@ export function createClaudeReviewStream(onEvent, onNotice = null) {
62
68
  return;
63
69
  }
64
70
  if (message.type === 'system') {
65
- if (message.subtype === 'dev_intent') {
66
- if (noticeCount >= 32) reject('unexpected_event');
67
- noticeCount++;
68
- reportClaudeDevIntentNotice(onNotice);
71
+ if (['dev_intent','ui_invalidate'].includes(message.subtype)) {
72
+ startupNotice(message.subtype);
69
73
  return;
70
74
  }
71
75
  if (message.subtype === 'thinking_tokens') {
@@ -24,15 +24,7 @@ const boundStatus=(status,identity)=>{validIdentity(status?.identity);
24
24
  // verdict and a verdict that broke the written contract share one redispatch
25
25
  // per attempt. Exported for the batch driver, like developmentRetryable.
26
26
  export const reviewRetryable=status=>status.state==='pending_review'
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');
27
+ &&['review_transport_timeout','review_abandoned','review_provider_failed','review_verdict_invalid'].includes(status.code);
36
28
  const retryReview=reviewRetryable;
37
29
  // Both mean the delivery itself must be redone: an invalid developer result, or
38
30
  // one that does not satisfy the task's own written verification. Exported so the
@@ -56,8 +48,6 @@ const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approv
56
48
  status.developRedoRequired===true?'develop_redo':
57
49
  // V5: the round's second no-result redispatch needs the operator's stop confirmation.
58
50
  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':
61
51
  status.reviewReconciliation?.available?'reconcile_review':
62
52
  status.state==='changes_requested'||retryDeveloper(status)||retryReview(status)?'resume':
63
53
  status.state==='awaiting_review'?'decision':status.state==='unknown'
@@ -84,7 +74,6 @@ const summary=(operation,status,outcome)=>freeze({version:1,workflow:'cm-ai',ope
84
74
  ...(status.developRedoRequired===true?{developRedoRequired:true}:{}),
85
75
  ...(status.documentationSyncPending===true?{documentationSyncPending:true}:{}),
86
76
  ...(status.reviewRedispatchStopRequired===true?{reviewRedispatchStopRequired:true}:{}),
87
- ...(status.reviewDispatchConfirmRequired===true?{reviewDispatchConfirmRequired:true}:{}),
88
77
  ...(typeof status.reviewAbandonRefusal==='string'?{reviewAbandonRefusal:status.reviewAbandonRefusal}:{}),
89
78
  ...(typeof status.reason==='string'?{reason:status.reason}:{}),
90
79
  ...(status.code==='handoff_exists'?{reason:REVIEWED_HANDOFF_HINT}:{}),
@@ -146,13 +135,7 @@ const rejected=(identity,error)=>{
146
135
  outcome:'rejected',state:null,code,packageDigest:null,pendingAction:'none'});
147
136
  };
148
137
 
149
- function validateHostDecision(decision,status) {
150
- if(decision?.status==='denied'){
151
- shape(decision,['status','code']);need(decision.code==='permission_denied','invalid_host_decision');return 'denied';
152
- }
153
- shape(decision,['status']);need(decision.status==='approved','invalid_host_decision');
154
- need(status.packageDigest!==null,'stale_decision');return 'approved';
155
- }
138
+
156
139
 
157
140
  function effectSummary(operation,result,runner,identity) {
158
141
  if(result?.outcome==='rejected'){
@@ -210,8 +193,6 @@ function validateDocumentationResult(result,status,refresh,policy=null) {
210
193
 
211
194
  export function createCmAiConversationEntry(options) {
212
195
  const optionKeys=['specsDir','codeProject','feature','identity','runner'];
213
- if(options&&Object.hasOwn(options,'hostDecision'))optionKeys.push('hostDecision');
214
- if(options&&Object.hasOwn(options,'hostDecisionProvider'))optionKeys.push('hostDecisionProvider');
215
196
  if(options&&Object.hasOwn(options,'developmentAttempt'))optionKeys.push('developmentAttempt');
216
197
  if(options&&Object.hasOwn(options,'qaDecision'))optionKeys.push('qaDecision');
217
198
  if(options&&Object.hasOwn(options,'qaDecisionProvider'))optionKeys.push('qaDecisionProvider');
@@ -240,6 +221,7 @@ export function createCmAiConversationEntry(options) {
240
221
  const ownerIdentity=json(options.identity);validIdentity(ownerIdentity);
241
222
  const runner=options.runner;
242
223
  const runnerKeys=['executeEffect','status','cancel','run'];
224
+ if(runner&&Object.hasOwn(runner,'qaChangedFiles'))runnerKeys.push('qaChangedFiles');
243
225
  if(runner&&Object.hasOwn(runner,'verificationBlocks'))runnerKeys.push('verificationBlocks');
244
226
  if(runner&&Object.hasOwn(runner,'completionBlocks'))runnerKeys.push('completionBlocks');
245
227
  if(runner&&Object.hasOwn(runner,'reviewEffectIds'))runnerKeys.push('reviewEffectIds');
@@ -260,6 +242,7 @@ export function createCmAiConversationEntry(options) {
260
242
  if(runner&&Object.hasOwn(runner,'interruptions'))runnerKeys.push('interruptions');
261
243
  if(runner&&Object.hasOwn(runner,'inspectBootstrapAdmission'))runnerKeys.push('inspectBootstrapAdmission');
262
244
  shape(runner,runnerKeys);
245
+ if(Object.hasOwn(runner,'qaChangedFiles'))need(typeof runner.qaChangedFiles==='function');
263
246
  for(const name of ['executeEffect','status','cancel','run'])need(typeof runner[name]==='function');
264
247
  if(Object.hasOwn(runner,'completionBlocks'))need(typeof runner.completionBlocks==='function');
265
248
  if(Object.hasOwn(runner,'reviewEffectIds'))need(typeof runner.reviewEffectIds==='function');
@@ -286,14 +269,6 @@ export function createCmAiConversationEntry(options) {
286
269
  need(options.allowDevelopRedo===undefined||typeof options.allowDevelopRedo==='boolean','invalid_input');
287
270
  let developRedoPermission=options.allowDevelopRedo===true;
288
271
 
289
- const hostDecision=Object.hasOwn(options,'hostDecision')?json(options.hostDecision):null;
290
- let hostDecisionProvider=null,pendingReviewDecision=null;
291
- if(Object.hasOwn(options,'hostDecisionProvider')){
292
- shape(options.hostDecisionProvider,['decide','timeoutMs']);
293
- const {decide,timeoutMs}=options.hostDecisionProvider;
294
- need(typeof decide==='function'&&Number.isInteger(timeoutMs)&&timeoutMs>=1&&timeoutMs<=60000);
295
- need(hostDecision===null);hostDecisionProvider={decide,timeoutMs};
296
- }
297
272
  const qaDecision=Object.hasOwn(options,'qaDecision')?json(options.qaDecision):null;
298
273
  const qaProvider=options.qaDecisionProvider??null;
299
274
  if(qaProvider!==null){
@@ -577,10 +552,9 @@ export function createCmAiConversationEntry(options) {
577
552
  return summary(operation,status,'reported');
578
553
  }
579
554
  if(operation.operation==='cancel'){
580
- const interrupted=inFlightHandles.size>0||pendingReviewDecision!==null||pendingQa!==null
555
+ const interrupted=inFlightHandles.size>0||pendingQa!==null
581
556
  ||pendingExecution!==null||pendingDocumentation!==null;
582
557
  cancellationEpoch++;
583
- pendingReviewDecision?.abort();
584
558
  pendingQa?.abort();
585
559
  pendingExecution?.abort();
586
560
  pendingDocumentation?.abort();
@@ -638,48 +612,17 @@ export function createCmAiConversationEntry(options) {
638
612
  const status=boundStatus(runner.status(),identity);
639
613
  need(status.packageDigest===operation.packageDigest,'stale_decision');
640
614
  if(status.code==='review_package_changed')return summary(operation,status,'rejected');
641
- let decision=hostDecision;
642
- if(hostDecisionProvider!==null){
643
- // A historical terminal or outstanding invocation is owned by the runner;
644
- // never ask for fresh authorization to replay or reopen it.
645
- if(!(status.state==='awaiting_review'&&status.code===null)&&!retryReview(status))return summary(operation,status,'reported');
646
- need(pendingReviewDecision===null,'review_decision_pending');
647
- need(!status.cancellationRequested&&!status.cancelAfterCommit,'cancelled');
648
- const controller=new AbortController();pendingReviewDecision=controller;
649
- let timer,timedOut=false;
650
- try{
651
- const interrupted=new Promise((_,reject)=>{
652
- controller.signal.addEventListener('abort',()=>reject(Object.assign(new Error('Review decision interrupted'),
653
- {code:timedOut?'review_decision_timeout':'cancelled'})),{once:true});
654
- timer=setTimeout(()=>{timedOut=true;controller.abort();},hostDecisionProvider.timeoutMs);
655
- });
656
- const binding=freeze(json({specsDir:options.specsDir,codeProject:options.codeProject,feature:options.feature,
657
- identity,packageDigest:operation.packageDigest}));
658
- decision=json(await Promise.race([Promise.resolve().then(()=>{
659
- need(!controller.signal.aborted,'cancelled');return hostDecisionProvider.decide(binding,controller.signal);
660
- }),interrupted]));
661
- need(!controller.signal.aborted,'cancelled');
662
- const current=boundStatus(runner.status(),identity);
663
- need(current.state===status.state&&current.code===status.code
664
- &&current.packageDigest===operation.packageDigest,'stale_decision');
665
- need(!current.cancellationRequested&&!current.cancelAfterCommit,'cancelled');
666
- }finally{clearTimeout(timer);pendingReviewDecision=null;}
667
- }
668
- if(decision===null)return summary(operation,{...status,code:'decision_required'},'awaiting');
669
- if(validateHostDecision(decision,status)==='denied')
670
- return summary(operation,{...status,code:'permission_denied'},'denied');
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.
615
+ // Dispatch only a review-ready package. Completed or outstanding invocations
616
+ // remain runner-owned and cannot be reopened by a decision message.
617
+ if(!(status.state==='awaiting_review'&&status.code===null)&&!retryReview(status))return summary(operation,status,'reported');
618
+ need(!status.cancellationRequested&&!status.cancelAfterCommit,'cancelled');
676
619
  const resumed=runner.interruptions?.('review')??0,roundIds=runner.reviewEffectIds?.();
677
620
  const idFor=n=>`review-${identity.attempt}${n?`-retry-${n}`:''}${resumed?`-resume-${resumed}`:''}`;
678
621
  let retries=0;
679
622
  if(retryReview(status)){
680
623
  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);
624
+ status.calls.filter(call=>call.channel==='host-review'&&['failed','abandoned'].includes(call.terminal)
625
+ &&call.contextId===status.reviewInvocation?.registration?.binding.logicalContextId).length);
683
626
  if(Array.isArray(roundIds))while(roundIds.includes(idFor(retries)))retries++;
684
627
  }
685
628
  const effectId=idFor(retries);
@@ -735,6 +678,7 @@ export function createCmAiConversationEntry(options) {
735
678
  decision=json(await Promise.race([
736
679
  Promise.resolve().then(()=>{need(!controller.signal.aborted,'cancelled');
737
680
  return decideQa(freeze({...binding,codeProject:options.codeProject,
681
+ changedFiles:runner.qaChangedFiles?.(operation.packageDigest)??{paths:[],source:'unavailable'},
738
682
  ...(previousDecisionId===null?{}:{previousDecisionId})}),controller.signal);}),interrupted]));
739
683
  need(!controller.signal.aborted,'cancelled');
740
684
  const current=boundStatus(runner.status(),identity);
@@ -749,7 +693,7 @@ export function createCmAiConversationEntry(options) {
749
693
  return summary(operation,{...status,code:admission.reason},'awaiting');
750
694
  const feature=admission.features.find(item=>item.name===options.feature);
751
695
  need(feature,'qa_policy_unavailable');
752
- // N6 feature completion is a mandatory trigger, regardless of score.
696
+ // N6 feature completion is a mandatory trigger, regardless of registered paths.
753
697
  // Ask for the proper bound decision; do not synthesize authorization.
754
698
  if(feature.pending===0)return summary(operation,{...status,code:'qa_mandatory_required'},'awaiting');
755
699
  }
@@ -30,7 +30,9 @@ export function recordCmAiQaAttachment({specsDir,codeProject,feature,identity,re
30
30
  }
31
31
 
32
32
  export function readDecision(raw,identity,packageDigest) {
33
- const decision=json(raw);shape(decision,['decisionId','identity','packageDigest','status','reason','score','at']);
33
+ const decision=json(raw);shape(decision,['decisionId','identity','packageDigest','status','reason','score','at',
34
+ ...(Object.hasOwn(decision,'changedFilesSource')?['changedFilesSource']:[])]);
35
+ if(Object.hasOwn(decision,'changedFilesSource'))need(['review_package','handoff_only','unavailable'].includes(decision.changedFilesSource));
34
36
  id(decision.decisionId);validIdentity(decision.identity);hex(decision.packageDigest);
35
37
  need(sameIdentity(decision.identity,identity)&&decision.packageDigest===packageDigest,'qa_decision_mismatch');
36
38
  need(['triggered','skipped','blocked'].includes(decision.status));
@@ -39,7 +41,7 @@ export function readDecision(raw,identity,packageDigest) {
39
41
  &&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})$/.test(decision.at)
40
42
  &&Number.isFinite(Date.parse(decision.at)));
41
43
  if(decision.score!==null)need(Number.isInteger(decision.score)&&decision.score>=4&&decision.score<=20);
42
- if(decision.status==='skipped')need(Number.isInteger(decision.score)&&decision.score<=7);
44
+ if(decision.status==='skipped'&&decision.score!==null)need(decision.score<=7);
43
45
  if(decision.status==='triggered'&&decision.score!==null)need(decision.score>=8);
44
46
  return json({...decision,at:decision.at.endsWith('Z')?`${decision.at.slice(0,-1)}+00:00`:decision.at});
45
47
  }
@@ -70,7 +72,8 @@ function existingDecision(specsDir,feature,identity,packageDigest,decision,previ
70
72
  const row=effectiveQaDecisionRow(matches,'qa_decision_conflict');
71
73
  if(row.decision_id===decision.decisionId){
72
74
  need(row.status===decision.status&&row.reason===decision.reason&&row.score===decision.score&&row.at===decision.at
73
- &&(row.previous_decision_id??null)===previousDecisionId,'qa_decision_conflict');
75
+ &&(row.previous_decision_id??null)===previousDecisionId
76
+ &&(row.changed_files_source??null)===(decision.changedFilesSource??null),'qa_decision_conflict');
74
77
  return true;
75
78
  }
76
79
  // Only the single recorded timeout decision can be superseded, and once.
@@ -105,11 +108,12 @@ export function recordCmAiQaDecision(input) {
105
108
  const decision=readDecision(input.decision,input.identity,input.packageDigest);
106
109
  if(existingDecision(input.specsDir,input.feature,input.identity,input.packageDigest,decision,previousDecisionId))return;
107
110
  const detail=(decision.status==='triggered'?`触发:${decision.reason}`:
108
- decision.status==='skipped'?`跳过:评分${decision.score}`:`阻塞:${decision.reason}`)
111
+ decision.status==='skipped'?`跳过:${decision.reason}`:`阻塞:${decision.reason}`)
109
112
  +(previousDecisionId===null?'':`(重新评估,替代 ${previousDecisionId})`);
110
113
  const data={node:'N6',feature:input.feature,task:input.identity.taskId,attempt:input.identity.attempt,
111
114
  repository_id:input.identity.repositoryId,package_digest:input.packageDigest,decision_id:decision.decisionId,
112
115
  status:decision.status,reason:decision.reason,score:decision.score,
116
+ ...(Object.hasOwn(decision,'changedFilesSource')?{changed_files_source:decision.changedFilesSource}:{}),
113
117
  ...(previousDecisionId===null?{}:{previous_decision_id:previousDecisionId})};
114
118
  const args=[writer,'--workflow','cm-ai','--event','qa','--runtime','codex','--project-root',input.codeProject,
115
119
  '--specs-dir',input.specsDir,'--run-id',input.identity.runId,'--at',decision.at,'--detail',detail,
@@ -155,7 +159,8 @@ function findDecisionRow(input) {
155
159
  export function findCmAiQaDecision(input) {
156
160
  const row=findDecisionRow(input);if(row===null)return null;
157
161
  return readDecision({status:row.status,decisionId:row.decision_id,identity:input.identity,
158
- packageDigest:input.packageDigest,reason:row.reason,score:row.score,at:row.at},input.identity,input.packageDigest);
162
+ packageDigest:input.packageDigest,reason:row.reason,score:row.score,at:row.at,
163
+ ...(Object.hasOwn(row,'changed_files_source')?{changedFilesSource:row.changed_files_source}:{})},input.identity,input.packageDigest);
159
164
  }
160
165
 
161
166
  // True when the effective decision is the linked replacement of a timed-out
@@ -0,0 +1,112 @@
1
+ // Execution choices and stale-command protection, not human authentication.
2
+ import fs from 'node:fs';
3
+ import {projectOperatorGuidance} from './operator-guidance.mjs';
4
+ import {digest,json,need,shape,validIdentity,hex,id} from './effect-contract.mjs';
5
+ import {parseModelJson} from './model-configuration-file.mjs';
6
+
7
+ export const CONTROL_RECOVERY_OPERATIONS=Object.freeze(['abandon_review','abandon_effect','develop_redo',
8
+ 'bootstrap_review_recover','reconcile_review']);
9
+ export const CONTROL_FIX_RECOVERY_OPERATIONS=Object.freeze(['abandon_step','abandon_review','rediagnose',
10
+ 'rerun_blocked_step','recover_final_review','reconcile_review']);
11
+ export function readControlPolicy(raw){
12
+ const value=json(raw);shape(value,['version','development','bootstrap','qa','qaFix']);
13
+ need(value.version===2&&['conversation','provider'].includes(value.development)
14
+ &&['disabled','write'].includes(value.bootstrap)&&['disabled','run'].includes(value.qa)
15
+ &&['disabled','manual','auto'].includes(value.qaFix),'invalid_input');
16
+ need(value.qaFix==='disabled'||value.qa==='run','invalid_input');
17
+ return value;
18
+ }
19
+ export function readControlPolicyFile(file){
20
+ const before=fs.lstatSync(file);
21
+ need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1&&before.size<=65536,'invalid_input');
22
+ const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
23
+ try{
24
+ const bytes=fs.readFileSync(fd),after=fs.fstatSync(fd),current=fs.lstatSync(file);
25
+ need([after,current].every(s=>['dev','ino','size','mtimeMs','ctimeMs'].every(k=>s[k]===before[k]))
26
+ &&bytes.length===before.size,'snapshot_changed');
27
+ const text=bytes.toString('utf8');need(Buffer.from(text).equals(bytes),'invalid_input');
28
+ return readControlPolicy(parseModelJson(text));
29
+ }finally{fs.closeSync(fd);}
30
+ }
31
+ export function controlPolicyFromSnapshot(snapshot){
32
+ return snapshot.records.find(row=>row.payload.type==='init')?.payload.config?.controlPolicy??null;
33
+ }
34
+ export function assertControlEntry(snapshot,policy){
35
+ const saved=controlPolicyFromSnapshot(snapshot);
36
+ need((saved===null)===(policy===null),'fingerprint_mismatch');
37
+ if(saved!==null)need(digest(readControlPolicy(saved))===digest(readControlPolicy(policy)),'fingerprint_mismatch');
38
+ }
39
+ export function readControlTarget(raw){
40
+ const v=json(raw);shape(v,['version','identity','state','code','packageDigest','effectId','invocationId','revision',
41
+ ...(Object.hasOwn(v,'child')?['child']:[])]);
42
+ need(v.version===2&&typeof v.state==='string'&&(v.code===null||typeof v.code==='string'),'invalid_input');
43
+ validIdentity(v.identity);hex(v.revision);
44
+ if(v.packageDigest!==null)hex(v.packageDigest);
45
+ for(const key of ['effectId','invocationId'])if(v[key]!==null)id(v[key]);
46
+ if(Object.hasOwn(v,'child'))readFixControlTarget(v.child);
47
+ return v;
48
+ }
49
+ export function readFixControlTarget(raw){
50
+ const v=json(raw);shape(v,['runId','revision','stage']);id(v.runId);hex(v.revision);
51
+ need(typeof v.stage==='string'&&v.stage.length>0&&v.stage.length<=128,'invalid_input');return v;
52
+ }
53
+ export function controlTarget(status,snapshot){
54
+ const intent=snapshot.records.findLast(row=>row.payload.type==='effect-intent')?.payload.effect??null;
55
+ const registration=snapshot.records.findLast(row=>row.payload.type==='review-invocation-registered')?.payload;
56
+ return readControlTarget({version:2,identity:status.identity,state:status.state,code:status.code??null,
57
+ packageDigest:status.packageDigest??null,effectId:intent?.id??null,
58
+ invocationId:registration?.binding?.invocationId??null,revision:snapshot.revision});
59
+ }
60
+ export function isControlRecovery(request){
61
+ return CONTROL_RECOVERY_OPERATIONS.includes(request.operation)
62
+ ||request.operation==='fix_action'&&CONTROL_FIX_RECOVERY_OPERATIONS.includes(request.fixOperation);
63
+ }
64
+ export function assertExpectedControl(expected,current){
65
+ need(expected!==undefined,'invalid_input');
66
+ need(digest(readControlTarget(expected))===digest(readControlTarget(current)),'snapshot_changed');
67
+ }
68
+ // The existing store owns the writer lock. This guard never queues a previewed
69
+ // command behind another mutation; validation and invocation share that owner.
70
+ export function withControlPolicyHost(host,{identity,snapshot,launchTarget=null}){
71
+ let busy=false;
72
+ return {...host,async handle(raw){
73
+ let ownsBusy=false,checking=true;
74
+ try{
75
+ const request=json(raw);need(request.version===2,'fingerprint_mismatch');
76
+ if(busy&&!['status','cancel','fix_status'].includes(request.operation))return {outcome:'rejected',code:'host_busy'};
77
+ const recovering=isControlRecovery(request);
78
+ need(recovering||!Object.hasOwn(request,'expectedControl'),'invalid_input');
79
+ const {expectedControl,...wire}=request;wire.version=1;
80
+ // A busy poll cannot publish a recovery target.
81
+ if(busy)return projectOperatorGuidance(await host.handle(wire),{protocol:'v2'});
82
+ busy=true;ownsBusy=true;
83
+ if(recovering){
84
+ checking=false;
85
+ const status=await host.handle({version:1,requestId:request.requestId,operation:'status',identity});
86
+ checking=true;
87
+ if(request.operation==='fix_action'){
88
+ need(expectedControl!==undefined,'invalid_input');readControlTarget(expectedControl);
89
+ need(Object.hasOwn(expectedControl,'child'),'invalid_input');
90
+ const {child,...parent}=expectedControl;assertExpectedControl(parent,controlTarget(status,snapshot()));
91
+ wire.expectedFixControl=readFixControlTarget(child);
92
+ }else assertExpectedControl(expectedControl,controlTarget(status,snapshot()));
93
+ need(digest(wire.identity)===digest(status.identity),'snapshot_changed');
94
+ }
95
+ checking=false;
96
+ const result=projectOperatorGuidance(await host.handle(wire),{protocol:'v2'});
97
+ if(request.operation==='fix_status'&&result.childControlTarget){
98
+ const parent=await host.handle({version:1,requestId:request.requestId,operation:'status',identity});
99
+ return {...result,controlTarget:{...controlTarget(parent,snapshot()),child:readFixControlTarget(result.childControlTarget)}};
100
+ }
101
+ if(result.identity&&result.state&&request.operation==='status')
102
+ return {...result,controlTarget:controlTarget(result,snapshot()),
103
+ ...(launchTarget?{launchControlTarget:launchTarget(snapshot())}: {})};
104
+ return result;
105
+ }catch(error){
106
+ if(checking&&['invalid_input','snapshot_changed','fingerprint_mismatch'].includes(error.code))
107
+ return {outcome:'rejected',code:error.code,reason:error.code==='snapshot_changed'
108
+ ?'恢复目标已经变化;先核对当前状态和原操作,不自动更新旧目标后重试。':'恢复需要 status 返回的当前 controlTarget;旧运行使用原兼容入口。'};
109
+ throw error;
110
+ }finally{if(ownsBusy)busy=false;}
111
+ }};
112
+ }
@@ -50,7 +50,9 @@ export function attemptAnswerName(root,name,attempt){
50
50
  }
51
51
 
52
52
  // Returns {mode,gap}; gap is a refusal for a bootstrap case this driver does not support.
53
- export function inspectDriverBootstrap({advance,definition,permissions}){
53
+ export function inspectDriverBootstrap({advance,definition,permissions,controlPolicy=null}){
54
+ if(controlPolicy?.bootstrap==='disabled'&&permissions.includes('--bootstrap-config'))
55
+ return {mode:null,gap:'invalid_arguments: bootstrap disabled 禁止 --bootstrap-config;驾驶员未读取配置、未启动宿主'};
54
56
  if(!advance||!permissions.includes('--bootstrap-config'))return {mode:null,gap:null};
55
57
  let task;
56
58
  try{task=inspectCmAiBootstrapTask({specsDir:definition.specsDir,codeProject:definition.codeProject,
@@ -59,7 +61,8 @@ export function inspectDriverBootstrap({advance,definition,permissions}){
59
61
  }
60
62
  if(task.mode!=='instructions')return {mode:task.mode,gap:null};
61
63
  const gap=line=>({mode:'instructions',gap:`${line};可由当前 AI 会话用 cm-ai-host.mjs serve 应答 init_generate/init_verify`});
62
- if(permissions.includes('--protected-config'))return gap('规范任务不支持 --protected-config(provider 开发)驾驶');
64
+ if(controlPolicy?controlPolicy.development==='provider':permissions.includes('--protected-config'))
65
+ return gap(controlPolicy?'规范任务不支持 provider 开发驾驶':'规范任务不支持 --protected-config(provider 开发)驾驶');
63
66
  if(Object.hasOwn(definition,'codeProjects'))return gap('多代码根(codeProjects)规范任务驾驶员尚不支持');
64
67
  let selection;
65
68
  // The host's own reader: a regular, non-symlink file of at most 64 KiB with only selection.
@@ -186,9 +189,9 @@ function readVerify(root,name,{definition,plan,attempt}){
186
189
  // only when the develop effect starts, and the task entry inside it
187
190
  // (host-bootstrap.mjs run()), so both are required here; everything else the host
188
191
  // checks at launch runs before host_ready, before any command.
189
- function authorizeRulesLaunch({definition,plan,permissions}){
192
+ function authorizeRulesLaunch({definition,plan,permissions,controlPolicy=null}){
190
193
  const refusal=';驾驶员不运行 init-verify 命令、不启动宿主';
191
- refuse(permissions.includes('--allow-bootstrap-write'),
194
+ refuse(controlPolicy?controlPolicy.bootstrap==='write':permissions.includes('--allow-bootstrap-write'),
192
195
  `规范任务需要 --allow-bootstrap-write:宿主写规范前要求这一授权(bootstrap_write_authorization_required)${refusal}`);
193
196
  const protection=permissions.indexOf('--protected-conversation-config');
194
197
  if(protection!==-1)try{readConversationProtection(permissions[protection+1]);}
@@ -209,14 +212,14 @@ function authorizeRulesLaunch({definition,plan,permissions}){
209
212
  `${definition.identity.taskId} 不是当前可进入的 bootstrap 任务(nextTask ${entry?.id??'无'},宿主以 bootstrap_task_required 拒绝)${refusal}`);
210
213
  }
211
214
 
212
- export function readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable}){
215
+ export function readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable,controlPolicy=null}){
213
216
  const result=new Map(),slug=`.reviews/${definition.feature.replace(/^\d+\./,'')}-${definition.identity.taskId}`;
214
217
  const pair=attempt=>`answers/init-generate-a${attempt}.json 与 answers/init-verify-a${attempt}.json`;
215
218
  if(reachable.reviewAfterDevelop)
216
- stop(2,`规范任务的 advance 不能带 --allow-review-attempt 1 直接进入第 2 轮:修订答案须在读取首轮审查 findings 之后编写。请从 PLAN.permissions 移除 --allow-review-attempt 1,先 advance 到 awaiting_review;再用返回的 packageDigest 执行 decision,读取 ${slug}-r1.md 的 findings;若要求修改,写 ${pair(2)} 后 advance。`);
219
+ stop(2,`规范任务不能预先进入第 2 轮:修订答案须在读取首轮审查 findings 之后编写。首轮自动审查后停在 changes_requested;读取 ${slug}-r1.md 的 findings;若要求修改,写 ${pair(2)} 后 advance。`);
217
220
  if(reachable.reviewFirst)
218
- stop(2,`规范修订答案须在读取首轮审查 findings 之后编写:请先以 decision 和当前 packageDigest ${reachable.packageDigest} 单独运行审查,读取 ${slug}-r1.md 的 findings,写 ${pair(2)} 后再 advance(不要带 --allow-review-attempt 1 advance)`);
219
- if(reachable.attempts.length)authorizeRulesLaunch({definition,plan,permissions});
221
+ stop(2,`规范修订答案须在读取首轮审查 findings 之后编写:请先以 decision 和当前 packageDigest ${reachable.packageDigest} 单独运行审查,读取 ${slug}-r1.md 的 findings,写 ${pair(2)} 后再 advance`);
222
+ if(reachable.attempts.length)authorizeRulesLaunch({definition,plan,permissions,controlPolicy});
220
223
  for(const attempt of reachable.attempts){
221
224
  const names=['init-generate','init-verify'].map(name=>attemptAnswerName(answers??'',name,attempt));
222
225
  for(const name of names){