@aibyzero/cm-workflow 0.16.3 → 0.16.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +55 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/next-steps.md +14 -24
  9. package/docs/runtime-failover.md +1 -1
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  12. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
  15. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  16. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  17. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  18. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  19. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  21. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  22. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  24. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  25. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  27. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  28. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  29. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  30. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  31. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  32. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  34. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  38. package/runtime/js/cm-ai/host-session.mjs +20 -5
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  43. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  44. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  45. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  46. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  47. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  48. package/runtime/js/cm-ai/review-package.mjs +427 -31
  49. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  50. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  52. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  53. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  54. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  56. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  57. package/runtime/js/cm-fix/execution.mjs +109 -25
  58. package/runtime/js/cm-fix/host-review.mjs +7 -3
  59. package/runtime/js/cm-fix/host.mjs +3 -1
  60. package/runtime/js/cm-fix/progress.mjs +1 -0
  61. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  62. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  63. package/runtime/js/cm-prd/analysis.mjs +2 -1
  64. package/runtime/js/cm-prd/change.mjs +28 -10
  65. package/runtime/js/cm-prd/draft.mjs +5 -2
  66. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  67. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  68. package/runtime/js/cm-prd/self-check.mjs +6 -3
  69. package/runtime/js/cm-prd/summary.mjs +6 -2
  70. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  71. package/runtime/js/spec-task-line.mjs +117 -0
  72. package/runtime/js/specs-status.mjs +14 -3
  73. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  74. package/scripts/cm-ai-admission.mjs +19 -10
  75. package/scripts/cm-ai-admission.test.mjs +65 -1
  76. package/scripts/cm-ai-batch-drive.mjs +93 -21
  77. package/scripts/cm-ai-batch-drive.test.mjs +171 -3
  78. package/scripts/cm-ai-batch-host.mjs +37 -13
  79. package/scripts/cm-ai-batch-host.test.mjs +26 -0
  80. package/scripts/cm-ai-batch-run.mjs +33 -10
  81. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  82. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  84. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  85. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  86. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  87. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  88. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  89. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  90. package/scripts/cm-ai-drive.mjs +480 -47
  91. package/scripts/cm-ai-drive.test.mjs +247 -10
  92. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  93. package/scripts/cm-ai-host.mjs +89 -25
  94. package/scripts/cm-ai-host.test.mjs +274 -12
  95. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  96. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  97. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  98. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  99. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  100. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  101. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  102. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  103. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  104. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  105. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  106. package/scripts/cm-ai-run.mjs +160 -60
  107. package/scripts/cm-ai-run.test.mjs +4 -3
  108. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  109. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  110. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  111. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  112. package/scripts/cm-ai-supersede.test.mjs +571 -17
  113. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  114. package/scripts/cm-capability-gate.test.mjs +21 -2
  115. package/scripts/cm-check-drive.mjs +4 -3
  116. package/scripts/cm-check-drive.test.mjs +17 -1
  117. package/scripts/cm-check-entry.mjs +13 -2
  118. package/scripts/cm-check-host.mjs +2 -2
  119. package/scripts/cm-check-host.test.mjs +57 -1
  120. package/scripts/cm-check-runtime.sh +16 -7
  121. package/scripts/cm-claude-developer-worker.test.mjs +43 -2
  122. package/scripts/cm-claude-probe.test.mjs +9 -1
  123. package/scripts/cm-claude-review-stream.test.mjs +68 -0
  124. package/scripts/cm-claude-worker.test.mjs +11 -4
  125. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  126. package/scripts/cm-failover.mjs +8 -8
  127. package/scripts/cm-fix-abandon.test.mjs +123 -5
  128. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  129. package/scripts/cm-fix-drive.mjs +45 -13
  130. package/scripts/cm-fix-drive.test.mjs +36 -1
  131. package/scripts/cm-fix-host.mjs +9 -6
  132. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  133. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  134. package/scripts/cm-host-check.test.mjs +6 -3
  135. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  136. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  137. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  138. package/scripts/cm-log-event.mjs +17 -0
  139. package/scripts/cm-log-event.test.mjs +31 -0
  140. package/scripts/cm-prd-completion.test.mjs +105 -2
  141. package/scripts/cm-prd-draft.test.mjs +14 -0
  142. package/scripts/cm-prd-drive.mjs +13 -7
  143. package/scripts/cm-prd-drive.test.mjs +10 -0
  144. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  145. package/scripts/cm-prd-review-gate.mjs +126 -81
  146. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  147. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  148. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  149. package/scripts/cm-prd-self-check.test.mjs +6 -0
  150. package/scripts/cm-prd-summary.test.mjs +40 -0
  151. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  152. package/scripts/cm-review-inventory.test.mjs +253 -1
  153. package/scripts/cm-spec-manifest.mjs +28 -10
  154. package/scripts/cm-spec-manifest.test.mjs +8 -4
  155. package/scripts/cm-spec-task-line.test.mjs +138 -0
  156. package/scripts/cm-specs-status.test.mjs +31 -1
  157. package/scripts/cm-task-gate.mjs +18 -10
  158. package/scripts/cm-task-gate.py +1 -1
  159. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  160. package/scripts/fixtures/claude-review-process.mjs +1 -0
  161. package/scripts/fixtures/process-cleanup.mjs +99 -0
  162. package/scripts/test-cm-log-event.py +2 -0
  163. package/scripts/test-cm-prd-review-gate.py +2 -1
  164. package/scripts/test-npm-install.py +1 -1
  165. package/scripts/test-scan-public-safety.py +1 -1
  166. package/scripts/test-shell-compat.sh +67 -0
  167. package/scripts/test-spec-manifest.py +16 -8
  168. package/scripts/test-task-gate.py +2 -2
  169. package/scripts/test-workflow-config.py +1 -0
  170. package/scripts/validate-public-repo.py +1 -0
  171. package/skills/cm-ai/references/N1-init.md +1 -1
  172. package/skills/cm-ai/references/js-host.md +264 -40
  173. package/skills/cm-check/SKILL.md +6 -1
  174. package/skills/cm-check/references/js-host.md +3 -3
  175. package/skills/cm-fix/references/js-host.md +22 -1
  176. package/skills/cm-prd/references/js-change-recovery.md +30 -0
  177. package/skills/cm-prd/references/js-host.md +6 -0
@@ -2,8 +2,10 @@
2
2
  import {inspectCmAiAdmission,matchesCmAiTaskSelection} from './cm-ai-admission.mjs';
3
3
  import {inspectCmAiContextRefresh,inspectCmAiTaskLearningInput} from './cm-ai-context-refresh.mjs';
4
4
  import {findCmAiQaDecision,inspectCmAiQaDecision,inspectCmAiQaResult,recordCmAiQaDecision,
5
- latestCmAiQaRun,recordCmAiQaRun,inspectCmAiQaRecovery,inspectCmAiQaConfigurationRecovery} from './cm-ai-qa-log.mjs';
5
+ latestCmAiQaRun,recordCmAiQaRun,inspectCmAiQaRecovery,inspectCmAiQaConfigurationRecovery,timedOutQaDecision,
6
+ replacesTimedOutQaDecision,validEnvironmentFailureReason} from './cm-ai-qa-log.mjs';
6
7
  import {recordCmAiRunDone} from './cm-ai-run-finalizer.mjs';
8
+ import {outstandingFeatureQa,describeOutstandingQa} from './project-qa-gate.mjs';
7
9
  import {REVIEWED_HANDOFF_HINT} from './host-handoff.mjs';
8
10
  import {readHostQaFixHandoff} from './host-qa-fix.mjs';
9
11
  import {digest,freeze,hex,id,json,need,shape,text,validIdentity} from './effect-contract.mjs';
@@ -12,19 +14,31 @@ const sameIdentity=(left,right)=>['repositoryId','runId','taskId','attempt'].eve
12
14
  const sameTask=(left,right)=>['repositoryId','runId','taskId'].every(key=>left[key]===right[key]);
13
15
  const boundStatus=(status,identity)=>{validIdentity(status?.identity);
14
16
  need(sameIdentity(status.identity,identity),'identity_mismatch');return status;};
15
- const retryReview=status=>status.state==='pending_review'&&status.code==='review_transport_timeout';
17
+ // A no-result timeout, an explicit abandonment, a reviewer failure with no
18
+ // verdict and a verdict that broke the written contract share one redispatch
19
+ // per attempt. Exported for the batch driver, like developmentRetryable.
20
+ export const reviewRetryable=status=>status.state==='pending_review'
21
+ &&['review_transport_timeout','review_abandoned','review_provider_failed','review_verdict_invalid'].includes(status.code);
22
+ const retryReview=reviewRetryable;
16
23
  // Both mean the delivery itself must be redone: an invalid developer result, or
17
24
  // one that does not satisfy the task's own written verification. Exported so the
18
25
  // batch driver decides retryability from the same predicate instead of keeping a
19
26
  // second copy of the code list that silently drifts.
20
27
  export const developmentRetryable=status=>status.state==='blocked'
21
- &&['developer_result_invalid','verification_precheck_failed'].includes(status.code);
28
+ &&['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);
22
29
  const retryDeveloper=developmentRetryable;
30
+ export const completionRetryable=status=>status.state==='blocked'
31
+ &&['completion_checks_changed','completion_package_changed'].includes(status.code)
32
+ &&status.retryReady!==false;
23
33
  const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approval':
34
+ // The runner reports spec_drift over any state whose next effect would be refused.
35
+ status.code==='spec_drift'?(status.specificationRebind==='available'?'spec_rebind':'none'):
24
36
  status.state==='changes_requested'||retryDeveloper(status)||retryReview(status)?'resume':
25
- status.state==='awaiting_review'?'decision':status.state==='unknown'?'reconcile':
37
+ status.state==='awaiting_review'?'decision':status.state==='unknown'
38
+ ?(status.pendingEffectKind?'abandon_effect':
39
+ status.pendingReviewInvocation||status.abandonableReviewResult?'abandon_review':'reconcile'):
26
40
  status.state==='pending_review'&&status.code==='provider_review_observed'?'review_evidence':
27
- status.state==='pending_review'?'decision':status.state==='approved'?'complete':
41
+ status.state==='pending_review'?'decision':status.state==='approved'||completionRetryable(status)?'complete':
28
42
  status.state==='fixture_completed'&&status.code==='qa_triggered'?'qa_execution':
29
43
  status.state==='fixture_completed'&&status.code==='qa_skipped'?'context_refresh':
30
44
  status.state==='fixture_completed'&&status.code==='qa_passed'?'context_refresh':
@@ -32,6 +46,7 @@ const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approv
32
46
  status.state==='fixture_completed'&&status.code==='documentation_sync_required'?'documentation_sync':
33
47
  status.state==='fixture_completed'&&status.code==='documentation_synced'?'run_finalize':
34
48
  status.state==='fixture_completed'&&status.code==='documentation_sync_blocked'?'none':
49
+ status.state==='fixture_completed'&&status.code==='project_qa_not_passed'?'none':
35
50
  status.state==='fixture_completed'&&status.code==='qa_blocked'?'none':
36
51
  status.state==='fixture_completed'&&status.code==='qa_execution_unknown'?'reconcile':
37
52
  status.state==='fixture_completed'&&['qa_failed','qa_result_blocked'].includes(status.code)?'none':
@@ -39,20 +54,39 @@ const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approv
39
54
  const summary=(operation,status,outcome)=>freeze({version:1,workflow:'cm-ai',operation:operation.operation,
40
55
  requestDigest:digest(operation),identity:status.identity,outcome,state:status.state,code:status.code??null,
41
56
  packageDigest:status.packageDigest??null,pendingAction:pendingAction(status),
57
+ ...(typeof status.reason==='string'?{reason:status.reason}:{}),
42
58
  ...(status.code==='handoff_exists'?{reason:REVIEWED_HANDOFF_HINT}:{}),
43
59
  ...(status.state==='blocked'&&status.calls?.at(-1)?.blockedReason!==undefined
44
60
  ?{blockedReason:status.calls.at(-1).blockedReason}:{})});
45
61
  const correctionSummary=(operation,status)=>status.code==='correction_review_required'
46
62
  ?summary(operation,status,'blocked'):null;
63
+ // run_done is a project claim: every approved feature's latest mandatory QA must
64
+ // have passed, not only this final run's own. Read with the strict owner validator.
65
+ function projectQaSummary(operation,status,options){
66
+ const admission=inspectCmAiAdmission({specsDir:options.specsDir,codeProject:options.codeProject});
67
+ const outstanding=outstandingFeatureQa({specsDir:options.specsDir,features:admission.features.map(({name,pending})=>({name,pending})),
68
+ currentRunId:status.identity.runId,inspect:latestCmAiQaRun});
69
+ if(!outstanding.length)return null;
70
+ return freeze({...summary(operation,{...status,code:'project_qa_not_passed',
71
+ reason:`以下 feature 的最新一轮 QA 未通过:${outstanding.map(describeOutstandingQa).join(';')}。先恢复对应运行让 QA 通过,再重新推进本运行收尾。`},'blocked'),
72
+ outstandingQa:outstanding});
73
+ }
47
74
 
48
75
  function readOperation(raw) {
49
76
  const operation=json(raw),keys=['version','operation','requestId','identity'];
50
77
  if(['decision','complete','qa','qa_result','context_refresh','finish','run_finalize'].includes(operation?.operation))keys.push('packageDigest');
51
78
  if(['qa_result','context_refresh','finish','run_finalize'].includes(operation?.operation))keys.push('testRunId');
79
+ if(['abandon_review','abandon_effect'].includes(operation?.operation))keys.push('reason');
52
80
  shape(operation,keys);
53
- need(operation.version===1&&['advance','start','status','decision','complete','qa','qa_result','context_refresh','finish','run_finalize','cancel','resume']
81
+ need(operation.version===1&&['advance','start','status','decision','complete','qa','qa_result','context_refresh','finish','run_finalize','cancel','resume','abandon_review','abandon_effect']
54
82
  .includes(operation.operation));
55
83
  id(operation.requestId);validIdentity(operation.identity);
84
+ if(operation.operation==='abandon_review')need(typeof operation.reason==='string'
85
+ &&operation.reason.trim().length>0&&Buffer.byteLength(operation.reason,'utf8')<=500
86
+ &&!/[\r\n\0]/.test(operation.reason),'review_abandon_reason_required');
87
+ if(operation.operation==='abandon_effect')need(typeof operation.reason==='string'
88
+ &&operation.reason.trim().length>0&&Buffer.byteLength(operation.reason,'utf8')<=500
89
+ &&!/[\r\n\0]/.test(operation.reason),'effect_abandon_reason_required');
56
90
  if(['decision','complete','qa','qa_result','context_refresh','finish','run_finalize'].includes(operation.operation))hex(operation.packageDigest);
57
91
  if(operation.operation==='qa_result')id(operation.testRunId);
58
92
  if(['context_refresh','finish','run_finalize'].includes(operation.operation)){
@@ -82,9 +116,9 @@ function validateHostDecision(decision,status) {
82
116
 
83
117
  function effectSummary(operation,result,runner,identity) {
84
118
  if(result?.outcome==='rejected'){
85
- const rejection=json(result);shape(rejection,['outcome','code']);id(rejection.code);
119
+ const rejection=json(result);shape(rejection,['outcome','code',...(Object.hasOwn(rejection,'reason')?['reason']:[])]);id(rejection.code);
86
120
  const current=boundStatus(runner.status(),identity);
87
- return summary(operation,{...current,code:rejection.code},'rejected');
121
+ return summary(operation,{...current,code:rejection.code,...(rejection.reason?{reason:rejection.reason}:{})},'rejected');
88
122
  }
89
123
  if(operation.operation==='decision'&&identity.attempt===1&&result?.state==='changes_requested'){
90
124
  const next={...identity,attempt:2};
@@ -137,33 +171,49 @@ export function createCmAiConversationEntry(options) {
137
171
  if(options&&Object.hasOwn(options,'qaExecutor'))optionKeys.push('qaExecutor');
138
172
  if(options&&Object.hasOwn(options,'rerunUnknownQa'))optionKeys.push('rerunUnknownQa');
139
173
  if(options&&Object.hasOwn(options,'rerunBlockedQa'))optionKeys.push('rerunBlockedQa');
174
+ if(options&&Object.hasOwn(options,'qaEnvironmentFailure'))optionKeys.push('qaEnvironmentFailure');
140
175
  if(options&&Object.hasOwn(options,'qaLogHome'))optionKeys.push('qaLogHome');
141
176
  if(options&&Object.hasOwn(options,'applicableAgentFiles'))optionKeys.push('applicableAgentFiles');
142
177
  if(options&&Object.hasOwn(options,'documentationResult'))optionKeys.push('documentationResult');
143
178
  if(options&&Object.hasOwn(options,'documentationProvider'))optionKeys.push('documentationProvider');
144
179
  if(options&&Object.hasOwn(options,'parallelSelection'))optionKeys.push('parallelSelection');
180
+ if(options&&Object.hasOwn(options,'allowAbandonReview'))optionKeys.push('allowAbandonReview');
181
+ if(options&&Object.hasOwn(options,'allowAbandonEffect'))optionKeys.push('allowAbandonEffect');
182
+ if(options&&Object.hasOwn(options,'holdRevision'))optionKeys.push('holdRevision');
145
183
  shape(options,optionKeys);
184
+ need(!Object.hasOwn(options,'holdRevision')||options.holdRevision===true,'invalid_input');
146
185
  if(Object.hasOwn(options,'developmentAttempt'))need([1,2].includes(options.developmentAttempt),'invalid_development_attempt');
147
186
  text(options.specsDir);text(options.codeProject);text(options.feature);
148
187
  const ownerIdentity=json(options.identity);validIdentity(ownerIdentity);
149
188
  const runner=options.runner;
150
189
  const runnerKeys=['executeEffect','status','cancel','run'];
151
190
  if(runner&&Object.hasOwn(runner,'verificationBlocks'))runnerKeys.push('verificationBlocks');
191
+ if(runner&&Object.hasOwn(runner,'completionBlocks'))runnerKeys.push('completionBlocks');
152
192
  if(runner&&Object.hasOwn(runner,'attachLearningEvidence'))runnerKeys.push('attachLearningEvidence');
153
193
  if(runner&&Object.hasOwn(runner,'inspectFixAssociation'))runnerKeys.push('inspectFixAssociation');
154
194
  if(runner&&Object.hasOwn(runner,'acceptCompletedFix'))runnerKeys.push('acceptCompletedFix');
155
195
  if(runner&&Object.hasOwn(runner,'attachQa'))runnerKeys.push('attachQa');
156
196
  if(runner&&Object.hasOwn(runner,'reviseQa'))runnerKeys.push('reviseQa');
157
197
  if(runner&&Object.hasOwn(runner,'supersedeEvidence'))runnerKeys.push('supersedeEvidence');
198
+ if(runner&&Object.hasOwn(runner,'rebindSpecification'))runnerKeys.push('rebindSpecification');
199
+ if(runner&&Object.hasOwn(runner,'abandonReview'))runnerKeys.push('abandonReview');
200
+ if(runner&&Object.hasOwn(runner,'abandonEffect'))runnerKeys.push('abandonEffect');
158
201
  if(runner&&Object.hasOwn(runner,'inspectBootstrapAdmission'))runnerKeys.push('inspectBootstrapAdmission');
159
202
  shape(runner,runnerKeys);
160
203
  for(const name of ['executeEffect','status','cancel','run'])need(typeof runner[name]==='function');
204
+ if(Object.hasOwn(runner,'completionBlocks'))need(typeof runner.completionBlocks==='function');
161
205
  if(Object.hasOwn(runner,'attachLearningEvidence'))need(typeof runner.attachLearningEvidence==='function');
162
206
  if(Object.hasOwn(runner,'inspectFixAssociation'))need(typeof runner.inspectFixAssociation==='function');
163
207
  if(Object.hasOwn(runner,'acceptCompletedFix'))need(typeof runner.acceptCompletedFix==='function');
164
208
  if(Object.hasOwn(runner,'attachQa'))need(typeof runner.attachQa==='function');
165
209
  if(Object.hasOwn(runner,'reviseQa'))need(typeof runner.reviseQa==='function');
210
+ if(Object.hasOwn(runner,'abandonReview'))need(typeof runner.abandonReview==='function');
211
+ if(Object.hasOwn(runner,'abandonEffect'))need(typeof runner.abandonEffect==='function');
166
212
  if(Object.hasOwn(runner,'inspectBootstrapAdmission'))need(typeof runner.inspectBootstrapAdmission==='function');
213
+ need(options.allowAbandonReview===undefined||typeof options.allowAbandonReview==='boolean','invalid_input');
214
+ let abandonPermission=options.allowAbandonReview===true;
215
+ need(options.allowAbandonEffect===undefined||typeof options.allowAbandonEffect==='boolean','invalid_input');
216
+ let abandonEffectPermission=options.allowAbandonEffect===true;
167
217
 
168
218
  const hostDecision=Object.hasOwn(options,'hostDecision')?json(options.hostDecision):null;
169
219
  let hostDecisionProvider=null,pendingReviewDecision=null;
@@ -184,9 +234,14 @@ export function createCmAiConversationEntry(options) {
184
234
  const decideQa=qaProvider?.decide,qaTimeout=qaProvider?.timeoutMs;
185
235
  let pendingQa=null;
186
236
  let qaExecutor=null,pendingExecution=null,cancellationEpoch=0;
237
+ const inFlightHandles=new Set();
187
238
  let rerunUnknownQa=options.rerunUnknownQa??false;need(typeof rerunUnknownQa==='boolean');
188
239
  let rerunBlockedQa=options.rerunBlockedQa??false;need(typeof rerunBlockedQa==='boolean');
189
240
  need(!(rerunUnknownQa&&rerunBlockedQa),'qa_recovery_authorization_required');
241
+ // Operator declaration that the latest FAIL came from the environment; only
242
+ // meaningful with the one-shot rerun authorization and consumed with it.
243
+ const qaEnvironmentFailure=options.qaEnvironmentFailure??null;
244
+ need(qaEnvironmentFailure===null||rerunBlockedQa&&validEnvironmentFailureReason(qaEnvironmentFailure),'qa_recovery_authorization_required');
190
245
  if(Object.hasOwn(options,'qaExecutor')){
191
246
  shape(options.qaExecutor,['mode','caseCount','timeoutMs','run',
192
247
  ...(Object.hasOwn(options.qaExecutor,'configuration')?['configuration']:[]),
@@ -259,7 +314,7 @@ export function createCmAiConversationEntry(options) {
259
314
  need(sameTask(identity,ownerIdentity)&&identity.attempt>=ownerIdentity.attempt,'identity_mismatch');
260
315
  // Stable run-definition identity can query/control or resume the current
261
316
  // attempt. Package-bound mutations must name the current attempt exactly.
262
- const stableControl=['status','cancel','advance','resume'].includes(operation.operation)
317
+ const stableControl=['status','cancel','advance','resume','abandon_review','abandon_effect'].includes(operation.operation)
263
318
  &&sameIdentity(operation.identity,ownerIdentity);
264
319
  need(sameIdentity(operation.identity,identity)||stableControl,'identity_mismatch');
265
320
  if(operation.operation==='advance'){
@@ -277,7 +332,8 @@ export function createCmAiConversationEntry(options) {
277
332
  result=await call('decision',result.packageDigest);
278
333
  if(result.outcome==='advanced'&&result.code===null&&result.state==='changes_requested'
279
334
  &&result.identity.attempt===round+1)continue;
280
- if(['reported','advanced'].includes(result.outcome)&&result.code===null&&result.state==='approved')
335
+ if(['reported','advanced'].includes(result.outcome)
336
+ &&(result.code===null&&result.state==='approved'||completionRetryable(result)))
281
337
  result=await call('complete',result.packageDigest);
282
338
  break;
283
339
  }
@@ -313,13 +369,20 @@ export function createCmAiConversationEntry(options) {
313
369
  previous=null;
314
370
  }
315
371
  }
372
+ // The authorization's durable effect is a replacement of a timed-out
373
+ // decision with no QA run under it yet (just written, or written
374
+ // before an interruption): run the ordinary first round, not a rerun.
375
+ if(rerunBlockedQa&&previous===null&&replacesTimedOutQaDecision(binding))rerunBlockedQa=false;
316
376
  if(rerunBlockedQa){
317
377
  need(previous!==null,'qa_rerun_not_blocked_by_evidence');
318
- recovery=inspectCmAiQaRecovery(binding,{blocked:true,environment:qaExecutor.configuration?.environment});
378
+ recovery=inspectCmAiQaRecovery(binding,{blocked:true,environment:qaExecutor.configuration?.environment,
379
+ environmentFailure:qaEnvironmentFailure});
319
380
  }
320
381
  let testRunId=previous?.testRunId;
321
382
  const accepted=runner.status().acceptedQaFix;
322
383
  const repaired=previous?.status==='failed'&&accepted?.testRunId===previous.testRunId;
384
+ // An accepted repair already owns the next round of that FAIL.
385
+ need(!(rerunBlockedQa&&repaired),'qa_rerun_not_blocked_by_evidence');
323
386
  if(previous===null||repaired||rerunBlockedQa){
324
387
  // Later rounds require an accepted completed repair or explicit
325
388
  // evidence recovery/configuration revision. Unknown execution stops.
@@ -334,7 +397,8 @@ export function createCmAiConversationEntry(options) {
334
397
  if(recovery&&!configurationRecovery){
335
398
  recordCmAiQaRun({...logInput,testRunId:recovery.testRunId,mode:recovery.mode,
336
399
  caseCount:recovery.caseCount,qaRound:recovery.qaRound,phase:rerunBlockedQa?'superseded':'abandoned',
337
- ...(rerunBlockedQa?{expectedEnvironment:qaExecutor.configuration?.environment??null}:{})});
400
+ ...(rerunBlockedQa?{expectedEnvironment:qaExecutor.configuration?.environment??null}:{}),
401
+ ...(rerunBlockedQa&&qaEnvironmentFailure!==null?{environmentFailure:qaEnvironmentFailure}:{})});
338
402
  rerunUnknownQa=false;rerunBlockedQa=false;
339
403
  }
340
404
  recordCmAiQaRun({...logInput,phase:'start',
@@ -386,17 +450,39 @@ export function createCmAiConversationEntry(options) {
386
450
  return summary(operation,status,'reported');
387
451
  }
388
452
  if(operation.operation==='cancel'){
453
+ const interrupted=inFlightHandles.size>0||pendingReviewDecision!==null||pendingQa!==null
454
+ ||pendingExecution!==null||pendingDocumentation!==null;
389
455
  cancellationEpoch++;
390
456
  pendingReviewDecision?.abort();
391
457
  pendingQa?.abort();
392
458
  pendingExecution?.abort();
393
459
  pendingDocumentation?.abort();
394
460
  const status=boundStatus(runner.cancel(),identity);
395
- return summary(operation,status,'cancelled');
461
+ return summary(operation,status,status.state==='cancelled'||interrupted?'cancelled':'reported');
462
+ }
463
+ if(operation.operation==='abandon_review'){
464
+ if(!abandonPermission)return summary(operation,{...runner.status(),
465
+ code:'review_abandon_authorization_required'},'rejected');
466
+ abandonPermission=false;
467
+ const result=runner.abandonReview?.({allowed:true,reason:operation.reason})
468
+ ??{outcome:'rejected',code:'review_abandon_unavailable'};
469
+ if(result.outcome==='rejected')return summary(operation,{...runner.status(),code:result.code},'rejected');
470
+ return summary(operation,boundStatus(result,identity),'abandoned');
471
+ }
472
+ if(operation.operation==='abandon_effect'){
473
+ if(!abandonEffectPermission)return summary(operation,{...runner.status(),
474
+ code:'effect_abandon_authorization_required'},'rejected');
475
+ abandonEffectPermission=false;
476
+ const result=runner.abandonEffect?.({allowed:true,reason:operation.reason})
477
+ ??{outcome:'rejected',code:'effect_abandon_unavailable'};
478
+ if(result.outcome==='rejected')return summary(operation,{...runner.status(),code:result.code,
479
+ ...(result.reason?{reason:result.reason}:{})},'rejected');
480
+ return summary(operation,boundStatus(result,identity),'abandoned');
396
481
  }
397
482
  if(operation.operation==='decision'){
398
483
  const status=boundStatus(runner.status(),identity);
399
484
  need(status.packageDigest===operation.packageDigest,'stale_decision');
485
+ if(status.code==='review_package_changed')return summary(operation,status,'rejected');
400
486
  let decision=hostDecision;
401
487
  if(hostDecisionProvider!==null){
402
488
  // A historical terminal or outstanding invocation is owned by the runner;
@@ -428,7 +514,8 @@ export function createCmAiConversationEntry(options) {
428
514
  if(validateHostDecision(decision,status)==='denied')
429
515
  return summary(operation,{...status,code:'permission_denied'},'denied');
430
516
  const retries=retryReview(status)?status.calls.filter(call=>call.channel==='host-authorized'
431
- &&call.terminal==='failed'&&call.contextId===status.reviewInvocation.registration.grant.logicalContextId).length:0;
517
+ &&['failed','abandoned'].includes(call.terminal)
518
+ &&call.contextId===status.reviewInvocation.registration.grant.logicalContextId).length:0;
432
519
  const effectId=`review-${identity.attempt}${retries?`-retry-${retries}`:''}`;
433
520
  const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'review'});
434
521
  return effectSummary(operation,result,runner,identity);
@@ -436,9 +523,13 @@ export function createCmAiConversationEntry(options) {
436
523
  if(operation.operation==='complete'){
437
524
  const status=boundStatus(runner.status(),identity);
438
525
  need(status.packageDigest===operation.packageDigest,'stale_completion');
526
+ if(status.code==='review_package_changed')return summary(operation,status,'rejected');
527
+ if(status.code==='completion_package_changed'&&status.retryReady===false)return summary(operation,status,'rejected');
439
528
  const correction=correctionSummary(operation,status);if(correction)return correction;
440
- need(['approved','fixture_completed'].includes(status.state),'completion_not_ready');
441
- const result=await runner.executeEffect({version:1,id:`complete-${identity.attempt}`,identity,kind:'complete'});
529
+ need(['approved','fixture_completed'].includes(status.state)||completionRetryable(status),'completion_not_ready');
530
+ const retries=runner.completionBlocks?.()??0;
531
+ const effectId=`complete-${identity.attempt}${retries?`-retry-${retries}`:''}`;
532
+ const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'complete'});
442
533
  return effectSummary(operation,result,runner,identity);
443
534
  }
444
535
  if(operation.operation==='qa'){
@@ -446,14 +537,19 @@ export function createCmAiConversationEntry(options) {
446
537
  need(status.packageDigest===operation.packageDigest,'stale_qa');
447
538
  const correction=correctionSummary(operation,status);if(correction)return correction;
448
539
  need(status.state==='fixture_completed','qa_not_ready');
449
- let decision=qaDecision;
540
+ let decision=qaDecision,previousDecisionId=null;
450
541
  if(qaProvider!==null){
451
542
  need(pendingQa===null,'qa_decision_pending');
452
543
  const binding={specsDir:options.specsDir,feature:options.feature,identity,packageDigest:operation.packageDigest};
453
544
  decision=findCmAiQaDecision(binding);
545
+ // An older host recorded a missed qa_assess window as this durable
546
+ // block. Only the explicit one-shot rerun authorization asks again; the
547
+ // new decision is appended with a link, the old row stays history.
548
+ if(rerunBlockedQa&&timedOutQaDecision(decision)){previousDecisionId=decision.decisionId;decision=null;}
454
549
  // A bound historical decision is evidence, not a fresh proposal. Keep
455
550
  // the existing downstream compatibility path; do not rewrite its log.
456
- if(decision!==null)return summary(operation,{...status,code:`qa_${decision.status}`},'recorded');
551
+ if(decision!==null)return summary(operation,{...status,code:`qa_${decision.status}`,
552
+ ...(decision.status==='blocked'?{reason:decision.reason}:{})},'recorded');
457
553
  if(decision===null){
458
554
  const controller=new AbortController();pendingQa=controller;
459
555
  let timer,timedOut=false;
@@ -461,13 +557,14 @@ export function createCmAiConversationEntry(options) {
461
557
  const interrupted=new Promise((_,reject)=>{
462
558
  controller.signal.addEventListener('abort',()=>reject(Object.assign(new Error('QA decision interrupted'),
463
559
  {code:timedOut?'qa_decision_timeout':'cancelled'})),{once:true});
464
- // Allow the request watchdog to publish its BLOCKED decision at
465
- // the same configured deadline before the outer cancellation.
560
+ // The request watchdog normally settles first with the same
561
+ // retryable qa_decision_timeout; this is the outer backstop.
466
562
  timer=setTimeout(()=>{timedOut=true;controller.abort();},qaTimeout+1000);
467
563
  });
468
564
  decision=json(await Promise.race([
469
565
  Promise.resolve().then(()=>{need(!controller.signal.aborted,'cancelled');
470
- return decideQa(freeze({...binding,codeProject:options.codeProject}),controller.signal);}),interrupted]));
566
+ return decideQa(freeze({...binding,codeProject:options.codeProject,
567
+ ...(previousDecisionId===null?{}:{previousDecisionId})}),controller.signal);}),interrupted]));
471
568
  need(!controller.signal.aborted,'cancelled');
472
569
  const current=boundStatus(runner.status(),identity);
473
570
  need(current.state==='fixture_completed'&&current.code==null&&current.packageDigest===operation.packageDigest,'stale_qa');
@@ -488,6 +585,7 @@ export function createCmAiConversationEntry(options) {
488
585
  const input={specsDir:options.specsDir,codeProject:options.codeProject,feature:options.feature,identity,
489
586
  packageDigest:operation.packageDigest,decision};
490
587
  if(Object.hasOwn(options,'qaLogHome'))input.logHome=options.qaLogHome;
588
+ if(previousDecisionId!==null)input.previousDecisionId=previousDecisionId;
491
589
  recordCmAiQaDecision(input);
492
590
  return summary(operation,{...status,code:`qa_${decision.status}`},'recorded');
493
591
  }
@@ -532,6 +630,7 @@ export function createCmAiConversationEntry(options) {
532
630
  const refresh=inspectCmAiContextRefresh({specsDir:options.specsDir,codeProject:options.codeProject,
533
631
  feature:options.feature,applicableAgentFiles});
534
632
  need(refresh.state==='complete','run_not_ready');
633
+ const projectQa=projectQaSummary(operation,status,options);if(projectQa)return projectQa;
535
634
  const documentationEpoch=cancellationEpoch;
536
635
  const documentation=await documentationFor(status,refresh);
537
636
  need(documentationEpoch===cancellationEpoch,'cancelled');
@@ -555,6 +654,7 @@ export function createCmAiConversationEntry(options) {
555
654
  const refresh=inspectCmAiContextRefresh({specsDir:options.specsDir,codeProject:options.codeProject,
556
655
  feature:options.feature,applicableAgentFiles});
557
656
  need(refresh.state==='complete','run_not_ready');
657
+ const projectQa=projectQaSummary(operation,status,options);if(projectQa)return projectQa;
558
658
  const documentationEpoch=cancellationEpoch;
559
659
  const documentation=await documentationFor(status,refresh);need(documentation!==null,'run_not_ready');
560
660
  need(documentationEpoch===cancellationEpoch,'cancelled');
@@ -568,6 +668,7 @@ export function createCmAiConversationEntry(options) {
568
668
  const documentationStatus=validateDocumentationResult(documentation,status,refresh);
569
669
  if(documentationStatus==='blocked')
570
670
  return summary(operation,{...status,code:'documentation_sync_blocked'},'blocked');
671
+ const finalQa=projectQaSummary(operation,status,options);if(finalQa)return finalQa;
571
672
  const input={specsDir:options.specsDir,codeProject:options.codeProject,feature:options.feature,identity,
572
673
  packageDigest:operation.packageDigest,contextDigest:refresh.contextDigest,
573
674
  documentationSyncId:documentation.syncId};
@@ -589,6 +690,10 @@ export function createCmAiConversationEntry(options) {
589
690
  // An unapproved next attempt is waiting, not a dispatched effect of unknown outcome.
590
691
  if(developable&&Object.hasOwn(options,'developmentAttempt')&&options.developmentAttempt!==identity.attempt)
591
692
  return summary(operation,{...status,code:'provider_development_authorization_required'},'awaiting');
693
+ // Transient launch option: the caller has no revision answer yet. Stop after
694
+ // the review that asked for it, before any develop intent, and say so.
695
+ if(options.holdRevision===true&&status.state==='changes_requested')
696
+ return summary(operation,{...status,code:'revision_answer_required'},'awaiting');
592
697
  const learningInput=inspectCmAiTaskLearningInput({specsDir:options.specsDir,codeProject:options.codeProject,
593
698
  feature:options.feature,identity,applicableAgentFiles:applicableAgentFiles??[]},
594
699
  {admission:runner.inspectBootstrapAdmission?.()??null,parallelSelection:options.parallelSelection??null});
@@ -603,6 +708,16 @@ export function createCmAiConversationEntry(options) {
603
708
  const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'develop',learningInput});
604
709
  return effectSummary(operation,result,runner,identity);
605
710
  }
606
- const handle=async raw=>{try{return await route(raw);}catch(error){return rejected(ownerIdentity,error);}};
711
+ const handle=async raw=>{
712
+ let token=null;
713
+ try{
714
+ const operation=readOperation(raw);
715
+ if(!['status','cancel','abandon_review','abandon_effect'].includes(operation.operation)){
716
+ token=Symbol(operation.operation);inFlightHandles.add(token);
717
+ }
718
+ return await route(operation);
719
+ }catch(error){return rejected(ownerIdentity,error);}
720
+ finally{if(token!==null)inFlightHandles.delete(token);}
721
+ };
607
722
  return Object.freeze({handle});
608
723
  }
@@ -38,6 +38,15 @@ function validateHandoff(target,identity) {
38
38
  &&result.stdout.length<=MiB,'handoff_invalid');
39
39
  }
40
40
 
41
+ // Pure: the handoff bytes once Learning evidence is attached, exactly as written.
42
+ export function taskLearningHandoffBytes({handoff,feature,identity,learningInput,application,retrospective,includeAgents}){
43
+ const applied=attachCmAiTaskLearningApplicationEvidence({handoff,feature,identity,learningInput,application});
44
+ const attached=attachCmAiTaskLearningEvidence({handoff:applied,feature,identity,learningInput,retrospective});
45
+ const changedFiles=arrayItems(attached.changed_files);for(const item of changedFiles)text(item);
46
+ const next={...attached,changed_files:includeAgents&&!changedFiles.includes('AGENTS.md')
47
+ ?[...changedFiles,'AGENTS.md']:changedFiles};
48
+ return Buffer.from(`${JSON.stringify(next,null,2)}\n`);
49
+ }
41
50
  export function writeCmAiTaskLearningHandoff(raw) {
42
51
  const input=json(raw,512*1024);
43
52
  shape(input,['handoffPath','feature','identity','learningInput','application','retrospective','writeback']);
@@ -55,15 +64,8 @@ export function writeCmAiTaskLearningHandoff(raw) {
55
64
  need(sameSnapshot(before,readHandoff(input.handoffPath)),'handoff_changed');
56
65
  let handoff;
57
66
  try {handoff=JSON.parse(before.source);}catch{need(false,'handoff_invalid');}
58
- const applied=attachCmAiTaskLearningApplicationEvidence({handoff,feature:input.feature,identity:input.identity,
59
- learningInput:input.learningInput,application:input.application});
60
- const attached=attachCmAiTaskLearningEvidence({handoff:applied,feature:input.feature,identity:input.identity,
61
- learningInput:input.learningInput,retrospective:input.retrospective});
62
- const changedFiles=arrayItems(attached.changed_files);for(const item of changedFiles)text(item);
63
- const includeAgents=writeback.outcome==='written';
64
- const next={...attached,changed_files:includeAgents&&!changedFiles.includes('AGENTS.md')
65
- ?[...changedFiles,'AGENTS.md']:changedFiles};
66
- const bytes=Buffer.from(`${JSON.stringify(next,null,2)}\n`);
67
+ const bytes=taskLearningHandoffBytes({handoff,feature:input.feature,identity:input.identity,learningInput:input.learningInput,
68
+ application:input.application,retrospective:input.retrospective,includeAgents:writeback.outcome==='written'});
67
69
  need(bytes.length<=LIMIT,'limit_exceeded');
68
70
  if(bytes.equals(before.bytes))return freeze({outcome:'unchanged',handoffSha256:before.sha256});
69
71
 
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {digest,freeze,hex,json,need,shape,text,validIdentity,validTaskLearningInput} from './effect-contract.mjs';
6
6
  import {encodeCmAiTaskLearningEvidence,readLearningRetrospectiveContent} from './cm-ai-context-refresh.mjs';
7
+ import {identifyApprovedBootstrapFeature} from './bootstrap-feature.mjs';
7
8
 
8
9
  const LIMIT=256*1024,PREFIX='cm-learning-retrospective-v1:';
9
10
  const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
@@ -63,6 +64,19 @@ export function mergeLessons(source,retrospective) {
63
64
  return `${before}${block}${newline}${after?newline:''}${after}`;
64
65
  }
65
66
 
67
+ // Pure: what a writeback does to this AGENTS.md text, without touching any file.
68
+ function lessonMerge(source,retrospective){
69
+ const next=mergeLessons(source,retrospective);
70
+ if(next===source)return {outcome:'deduplicated',content:source};
71
+ return Buffer.byteLength(next)>LIMIT?{outcome:'writeback_pending',content:source}:{outcome:'written',content:next};
72
+ }
73
+ // The same plan for a task Learning retrospective, for callers that size a
74
+ // delivery before it is written (the driver's journal preflight).
75
+ export function projectLearningWriteback({source,retrospective}){
76
+ const canonical=canonicalRetrospective(retrospective);
77
+ if(canonical.status!=='lesson_candidate')return {outcome:canonical.status,content:source};
78
+ return lessonMerge(source,canonical);
79
+ }
66
80
  function result(retrospective,outcome,changed,agentsFile,reason) {
67
81
  const body={version:1,workflow:'cm-ai',phase:'task_learning_writeback',feature:retrospective.feature,
68
82
  identity:retrospective.identity,learningDigest:retrospective.learningDigest,
@@ -99,7 +113,7 @@ export function readCmAiProjectLearningWriteback(raw,{learningInput,retrospectiv
99
113
  return freeze(value);
100
114
  }
101
115
 
102
- export function writeCmAiProjectLearning(raw,bootstrapAgentsSha256=null) {
116
+ export function writeCmAiProjectLearning(raw,bootstrapAgentsSha256=null,bootstrapFeature=null) {
103
117
  const input=json(raw,256*1024);shape(input,['codeProject','learningInput','retrospective']);
104
118
  text(input.codeProject);need(path.isAbsolute(input.codeProject)&&path.resolve(input.codeProject)===input.codeProject);
105
119
  validTaskLearningInput(input.learningInput,input.learningInput.identity,input.learningInput.feature);
@@ -109,7 +123,9 @@ export function writeCmAiProjectLearning(raw,bootstrapAgentsSha256=null) {
109
123
  &&retrospective.learningDigest===input.learningInput.learningDigest,'identity_mismatch');
110
124
  // Only the runner supplies a hash from its validated host bootstrap result.
111
125
  // The Learning identity/digest still describes the original task-start read.
112
- if(bootstrapAgentsSha256!==null){need(input.learningInput.feature==='0.bootstrap','bootstrap_task_required');hex(bootstrapAgentsSha256);}
126
+ if(bootstrapAgentsSha256!==null){need(bootstrapFeature!==null
127
+ &&bootstrapFeature===identifyApprovedBootstrapFeature([bootstrapFeature])
128
+ &&input.learningInput.feature===bootstrapFeature,'bootstrap_task_required');hex(bootstrapAgentsSha256);}
113
129
  const expected=bootstrapAgentsSha256===null
114
130
  ?input.learningInput.learningFiles.find(file=>file.scope==='project'&&file.path==='AGENTS.md')??null
115
131
  :{scope:'project',path:'AGENTS.md',sha256:bootstrapAgentsSha256};
@@ -147,10 +163,11 @@ function writeLearningContent(codeProject,expected,retrospective,makeResult){
147
163
  } catch(error) {
148
164
  return result(retrospective,'writeback_pending',null,expected,error?.code==='agents_changed'?'agents_changed':'agents_unsafe');
149
165
  }
150
- const source=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(before.bytes),next=mergeLessons(source,retrospective);
151
- if(next===source)return result(retrospective,'deduplicated',false,
166
+ const source=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(before.bytes),plan=lessonMerge(source,retrospective);
167
+ if(plan.outcome==='deduplicated')return result(retrospective,'deduplicated',false,
152
168
  before.exists?{scope:'project',path:'AGENTS.md',sha256:before.sha256}:null,null);
153
- const bytes=Buffer.from(next);if(bytes.length>LIMIT)return result(retrospective,'writeback_pending',null,expected,'agents_too_large');
169
+ if(plan.outcome==='writeback_pending')return result(retrospective,'writeback_pending',null,expected,'agents_too_large');
170
+ const bytes=Buffer.from(plan.content);
154
171
  const temporary=path.join(root,`.AGENTS.md.cm-learning.${process.pid}.${randomUUID()}`);let descriptor,renamed=false;
155
172
  try {
156
173
  descriptor=fs.openSync(temporary,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL