@aibyzero/cm-workflow 0.16.4 → 0.16.6

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 (283) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +22 -0
  3. package/CHANGELOG.md +57 -0
  4. package/README.md +22 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +48 -7
  17. package/docs/js-workflow-control.md +293 -33
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/runtime-failover.md +1 -1
  21. package/docs/untested-branches.md +27 -4
  22. package/docs/user-guide.md +23 -8
  23. package/install-codex.sh +28 -11
  24. package/package.json +1 -1
  25. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  26. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  27. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  28. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  29. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  30. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  31. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  32. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
  33. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  34. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  35. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
  36. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
  37. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  38. package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
  39. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  40. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  41. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  42. package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
  43. package/runtime/js/cm-ai/drive-core.mjs +47 -9
  44. package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
  45. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  46. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  47. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  48. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  49. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  50. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  51. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  52. package/runtime/js/cm-ai/external-models.mjs +52 -0
  53. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  54. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  55. package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
  56. package/runtime/js/cm-ai/host-check.mjs +30 -4
  57. package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
  58. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  59. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  60. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  61. package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
  62. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
  63. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  64. package/runtime/js/cm-ai/host-session.mjs +12 -4
  65. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  66. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
  67. package/runtime/js/cm-ai/host.mjs +1 -1
  68. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  69. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  70. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  71. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  72. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  73. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  74. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  75. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  76. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  77. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  78. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  79. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  80. package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
  81. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  82. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  83. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  84. package/runtime/js/cm-ai/review-package.mjs +438 -31
  85. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  86. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  87. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  88. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  89. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  90. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  91. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  92. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  93. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  94. package/runtime/js/cm-ai/task-runner.mjs +658 -75
  95. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  96. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  97. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  98. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  99. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  100. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  101. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  102. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  103. package/runtime/js/cm-fix/execution.mjs +279 -52
  104. package/runtime/js/cm-fix/final-review.mjs +18 -10
  105. package/runtime/js/cm-fix/host-review.mjs +32 -9
  106. package/runtime/js/cm-fix/host.mjs +6 -1
  107. package/runtime/js/cm-fix/layout.mjs +1 -1
  108. package/runtime/js/cm-fix/progress.mjs +5 -0
  109. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  110. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  111. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  112. package/runtime/js/cm-prd/analysis.mjs +2 -1
  113. package/runtime/js/cm-prd/change.mjs +28 -10
  114. package/runtime/js/cm-prd/draft.mjs +5 -2
  115. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  116. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  117. package/runtime/js/cm-prd/review-publication.mjs +27 -15
  118. package/runtime/js/cm-prd/review-time.mjs +29 -0
  119. package/runtime/js/cm-prd/self-check.mjs +6 -3
  120. package/runtime/js/cm-prd/session.mjs +53 -6
  121. package/runtime/js/cm-prd/summary.mjs +3 -1
  122. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  123. package/runtime/js/cm-security/finalize.mjs +32 -0
  124. package/runtime/js/spec-task-line.mjs +117 -0
  125. package/runtime/js/specs-status.mjs +10 -3
  126. package/runtime/review.md +5 -0
  127. package/runtime/task-gates.md +6 -0
  128. package/runtime/workflow-config.md +10 -1
  129. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  130. package/scripts/cm-ai-admission.mjs +18 -11
  131. package/scripts/cm-ai-admission.test.mjs +65 -1
  132. package/scripts/cm-ai-batch-drive.mjs +135 -34
  133. package/scripts/cm-ai-batch-drive.test.mjs +209 -3
  134. package/scripts/cm-ai-batch-host.mjs +63 -24
  135. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  136. package/scripts/cm-ai-batch-run.mjs +101 -34
  137. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  138. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  139. package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
  140. package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
  141. package/scripts/cm-ai-bootstrap.test.mjs +174 -89
  142. package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
  143. package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
  144. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  145. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  146. package/scripts/cm-ai-drive.mjs +526 -60
  147. package/scripts/cm-ai-drive.test.mjs +336 -10
  148. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  149. package/scripts/cm-ai-host.mjs +142 -43
  150. package/scripts/cm-ai-host.test.mjs +232 -12
  151. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  152. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  153. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  154. package/scripts/cm-ai-progress.test.mjs +521 -0
  155. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  156. package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
  157. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  158. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  159. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  160. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  161. package/scripts/cm-ai-review-failure.test.mjs +977 -0
  162. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  163. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  164. package/scripts/cm-ai-run.mjs +206 -62
  165. package/scripts/cm-ai-run.test.mjs +6 -4
  166. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  167. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  168. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  169. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  170. package/scripts/cm-ai-supersede.test.mjs +571 -17
  171. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  172. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  173. package/scripts/cm-capability-gate.test.mjs +21 -2
  174. package/scripts/cm-check-drive.test.mjs +2 -1
  175. package/scripts/cm-check-host.test.mjs +1 -1
  176. package/scripts/cm-check-runtime.sh +12 -1
  177. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  178. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  179. package/scripts/cm-claude-probe.test.mjs +10 -2
  180. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  181. package/scripts/cm-claude-worker.test.mjs +11 -4
  182. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  183. package/scripts/cm-codex-plugin-metadata.py +83 -0
  184. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  185. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  186. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  187. package/scripts/cm-efficiency-offline.mjs +35 -0
  188. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  189. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  190. package/scripts/cm-efficiency-response.test.mjs +117 -0
  191. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  192. package/scripts/cm-external-batch-host.test.mjs +157 -0
  193. package/scripts/cm-external-fix-host.test.mjs +281 -0
  194. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  195. package/scripts/cm-external-group-models.test.mjs +60 -0
  196. package/scripts/cm-external-model-host.test.mjs +180 -0
  197. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  198. package/scripts/cm-external-models.test.mjs +89 -0
  199. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  200. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  201. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  202. package/scripts/cm-failover.mjs +8 -8
  203. package/scripts/cm-fix-abandon.test.mjs +123 -5
  204. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  205. package/scripts/cm-fix-drive.mjs +70 -23
  206. package/scripts/cm-fix-drive.test.mjs +36 -1
  207. package/scripts/cm-fix-final-review.test.mjs +11 -6
  208. package/scripts/cm-fix-host.mjs +24 -14
  209. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  210. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  211. package/scripts/cm-fix-review-budget.test.mjs +147 -0
  212. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  213. package/scripts/cm-host-check.test.mjs +6 -3
  214. package/scripts/cm-host-qa-executor.test.mjs +213 -17
  215. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  216. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  217. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  218. package/scripts/cm-live-evidence.test.mjs +64 -0
  219. package/scripts/cm-log-event.mjs +25 -2
  220. package/scripts/cm-log-event.py +15 -0
  221. package/scripts/cm-log-event.test.mjs +31 -0
  222. package/scripts/cm-model-setup.mjs +79 -0
  223. package/scripts/cm-prd-completion.test.mjs +75 -0
  224. package/scripts/cm-prd-draft.test.mjs +14 -0
  225. package/scripts/cm-prd-drive.mjs +32 -11
  226. package/scripts/cm-prd-drive.test.mjs +15 -0
  227. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  228. package/scripts/cm-prd-host.mjs +13 -4
  229. package/scripts/cm-prd-review-gate.mjs +126 -81
  230. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  231. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  232. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  233. package/scripts/cm-prd-self-check.test.mjs +6 -0
  234. package/scripts/cm-prd-summary.test.mjs +9 -0
  235. package/scripts/cm-release-smoke.sh +5 -1
  236. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  237. package/scripts/cm-review-inventory.test.mjs +253 -1
  238. package/scripts/cm-runtime-i18n.mjs +15 -4
  239. package/scripts/cm-runtime-install.mjs +8 -4
  240. package/scripts/cm-runtime.mjs +116 -23
  241. package/scripts/cm-runtime.test.mjs +121 -12
  242. package/scripts/cm-security.test.mjs +32 -0
  243. package/scripts/cm-spec-manifest.mjs +28 -10
  244. package/scripts/cm-spec-manifest.test.mjs +8 -4
  245. package/scripts/cm-spec-task-line.test.mjs +138 -0
  246. package/scripts/cm-specs-status.test.mjs +12 -1
  247. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  248. package/scripts/cm-task-gate.mjs +164 -20
  249. package/scripts/cm-task-gate.py +2 -1
  250. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  251. package/scripts/cm-test-drive.mjs +10 -4
  252. package/scripts/cm-test-drive.test.mjs +14 -1
  253. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  254. package/scripts/cm-usage-report.py +22 -3
  255. package/scripts/cm-workflow-config.mjs +10 -1
  256. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  257. package/scripts/fixtures/claude-review-process.mjs +1 -0
  258. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  259. package/scripts/fixtures/process-cleanup.mjs +101 -0
  260. package/scripts/test-cm-log-event.py +2 -0
  261. package/scripts/test-cm-native-usage.py +62 -0
  262. package/scripts/test-cm-prd-review-gate.py +2 -1
  263. package/scripts/test-external-model-setup.py +91 -0
  264. package/scripts/test-model-configuration-write.py +201 -0
  265. package/scripts/test-npm-install.py +11 -2
  266. package/scripts/test-scan-public-safety.py +1 -1
  267. package/scripts/test-spec-manifest.py +16 -8
  268. package/scripts/test-task-gate.py +2 -2
  269. package/scripts/test-workflow-config.py +1 -0
  270. package/scripts/validate-public-repo.py +1 -0
  271. package/skills/cm-ai/SKILL.md +2 -2
  272. package/skills/cm-ai/references/N1-init.md +1 -1
  273. package/skills/cm-ai/references/N8-finish.md +5 -0
  274. package/skills/cm-ai/references/js-host.md +270 -43
  275. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  276. package/skills/cm-fix/SKILL.md +1 -1
  277. package/skills/cm-fix/references/js-host.md +52 -3
  278. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  279. package/skills/cm-prd/references/js-host.md +6 -0
  280. package/skills/cm-runtime/SKILL.md +29 -6
  281. package/skills/cm-security/SKILL.md +4 -2
  282. package/skills/cm-security/references/scan-contract.md +1 -0
  283. package/templates/cm-workflow.yml +1 -1
@@ -1,12 +1,81 @@
1
1
  // Content composition only. This does not authenticate a review or clear a gate.
2
- import {captureReviewBaseline,readReviewBaseline,readReviewPackage} from './review-package.mjs';
2
+ import {captureReviewBaseline,compareReviewInventoryToBaseline,readReviewBaseline,readReviewPackage} from './review-package.mjs';
3
3
  import {verifySpecificationMaterial} from './specification-material.mjs';
4
- import {digest,json,need} from './effect-contract.mjs';
4
+ import {CONFIG_FILENAMES} from '../../../scripts/cm-workflow-config.mjs';
5
+ import {digest,hex,id,json,need,shape} from './effect-contract.mjs';
5
6
 
6
7
  const inventoryFile=({contentBase64,...metadata})=>metadata;
7
8
  const sameFile=(a,b)=>digest(a===null?null:inventoryFile(a))===digest(b===null?null:inventoryFile(b));
9
+ // Recorded steps are compact (run id and package digest). The list is not a
10
+ // search bound: it is every qualifying delivery, and the whole accepted-fix
11
+ // record is size-checked before it is persisted.
12
+ const MAX_STEPS=2048;
8
13
 
9
- export function composeFixCode({baseline,parentPackage,fixPackages}){
14
+ // Later reviewed deliveries of other runs that precede a QA fix, recorded as the
15
+ // ordered list of their packages and the index of the fix each precedes. The
16
+ // file transitions are re-derived from the runs' verified stores, never taken
17
+ // from the journal; an empty list is the historical strict composition.
18
+ export function readSteps(raw,fixCount){
19
+ need(Array.isArray(raw)&&raw.length<=MAX_STEPS,'fix_association_invalid');
20
+ let previous=0;const seen=new Set();
21
+ for(const step of raw){
22
+ shape(step,['beforeFix','runId','packageDigest']);
23
+ need(Number.isInteger(step.beforeFix)&&step.beforeFix>=previous&&step.beforeFix<fixCount,'fix_association_invalid');
24
+ previous=step.beforeFix;id(step.runId);hex(step.packageDigest);
25
+ need(!seen.has(step.packageDigest),'fix_association_invalid');seen.add(step.packageDigest);
26
+ }
27
+ return raw;
28
+ }
29
+ // The recorded form of a real reviewed package.
30
+ export const deliveryStep=(runId,pkg,beforeFix)=>({beforeFix,runId,packageDigest:pkg.packageDigest});
31
+ const compact=steps=>steps.map(({beforeFix,runId,packageDigest})=>({beforeFix,runId,packageDigest}));
32
+ // Durable order: only packages whose own review came after the parent's approving
33
+ // review count, so a transition reviewed before the parent is never replayed over
34
+ // it (for example to disguise an unreviewed revert of the parent's change).
35
+ // deliveries: [{runId,packages:[{pkg,reviewedAt}]}].
36
+ export const deliveredAfter=(item,after)=>Number.isSafeInteger(after)
37
+ &&Number.isSafeInteger(item.reviewedAt)&&item.reviewedAt>after;
38
+ const key=file=>file===null||file===undefined?null:`${file.sha256}:${file.mode}`;
39
+ const applyMeta=(state,pkg)=>{for(const change of pkg.changes){
40
+ if(change.after===null)state.delete(change.path);else state.set(change.path,inventoryFile(change.after));}};
41
+ // Every qualifying later package, in durable review order (ties: run id, then
42
+ // package position). Nothing is chosen or dropped by content.
43
+ function laterSequence(deliveries,after,rootDigest){
44
+ return deliveries.flatMap(delivery=>delivery.packages.map((item,index)=>({runId:delivery.runId,index,reviewedAt:item.reviewedAt,raw:item.pkg})))
45
+ .filter(entry=>deliveredAfter(entry,after)).map(entry=>({...entry,pkg:readReviewPackage(entry.raw)}))
46
+ .filter(entry=>entry.pkg.rootDigest===rootDigest)
47
+ .sort((a,b)=>a.reviewedAt-b.reviewedAt||(a.runId<b.runId?-1:a.runId>b.runId?1:0)||a.index-b.index);
48
+ }
49
+ function unexplainedError(paths){
50
+ const error=new Error(`fix_current_code_unexplained: ${paths.slice(0,20).join(', ')}${paths.length>20?` (+${paths.length-20} more)`:''}`);
51
+ error.code='fix_current_code_unexplained';error.paths=paths;return error;
52
+ }
53
+ // The root CM workflow config outside the run's scope is user-editable policy,
54
+ // not delivered code, and is the one tolerated unreviewed difference.
55
+ const toleratedConfig=ownScope=>{const scope=new Set(ownScope);return p=>CONFIG_FILENAMES.includes(p)&&!scope.has(p);};
56
+ // Apply one later delivery strictly: its reviewed before-state must be the
57
+ // running composition on every path it touches (tolerated config aside). None
58
+ // is ever skipped; a mismatch names the paths.
59
+ function applyDelivery(state,pkg,tolerated){
60
+ const stale=pkg.changes.filter(change=>!tolerated(change.path)&&!sameFile(state.get(change.path)??null,change.before))
61
+ .map(change=>change.path).sort();
62
+ if(stale.length)throw unexplainedError(stale);
63
+ applyMeta(state,pkg);
64
+ }
65
+ const strict=()=>false;
66
+ // The composition must be the current tree exactly, content and mode.
67
+ function compareCurrent({root,base,state,tolerated}){
68
+ const original=new Map(base.files.map(file=>[file.path,inventoryFile(file)]));
69
+ const actual=new Map(compareReviewInventoryToBaseline(root,base,{withMode:true})
70
+ .map(row=>[row.path,row.sha256===null?null:`${row.sha256}:${row.mode}`]));
71
+ const wanted=new Map([...new Set([...original.keys(),...state.keys()])]
72
+ .filter(p=>key(original.get(p))!==key(state.get(p))).map(p=>[p,key(state.get(p))]));
73
+ const unexplained=[...new Set([...wanted.keys(),...actual.keys()])]
74
+ .filter(p=>!tolerated(p)&&wanted.get(p)!==actual.get(p)).sort();
75
+ if(unexplained.length)throw unexplainedError(unexplained);
76
+ }
77
+
78
+ function bindChain({baseline,parentPackage,fixPackages}){
10
79
  const base=readReviewBaseline(baseline),parent=readReviewPackage(parentPackage);
11
80
  need(Array.isArray(fixPackages)&&fixPackages.length>0&&fixPackages.length<=2,'fix_chain_invalid');
12
81
  const fixes=fixPackages.map(readReviewPackage);
@@ -15,29 +84,113 @@ export function composeFixCode({baseline,parentPackage,fixPackages}){
15
84
  for(const fix of fixes)need(fix.rootDigest===parent.rootDigest&&fix.identity.repositoryId===parent.identity.repositoryId
16
85
  &&fix.identity.runId!==parent.identity.runId,'fix_parent_binding_mismatch');
17
86
  need(new Set(fixes.map(fix=>fix.identity.runId)).size===fixes.length,'fix_chain_invalid');
18
- const expected=new Map(base.files.map(file=>[file.path,file]));
19
- const apply=pkg=>{
20
- for(const change of pkg.changes){
21
- need(sameFile(expected.get(change.path)??null,change.before),'fix_before_mismatch');
22
- if(change.after===null)expected.delete(change.path);else expected.set(change.path,change.after);
23
- }
24
- };
25
- apply(parent);fixes.forEach(apply);
26
- const files=[...expected.values()].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
87
+ return {base,parent,fixes};
88
+ }
89
+ const applyTo=expected=>pkg=>{
90
+ for(const change of pkg.changes){
91
+ need(sameFile(expected.get(change.path)??null,change.before),'fix_before_mismatch');
92
+ if(change.after===null)expected.delete(change.path);else expected.set(change.path,change.after);
93
+ }
94
+ };
95
+ // Strict order: parent, then for each fix its recorded preceding steps and the
96
+ // fix. Steps are resolved: each carries the real reviewed package (pkg).
97
+ function composeState({base,parent,fixes},steps){
98
+ const expected=new Map(base.files.map(file=>[file.path,file])),apply=applyTo(expected);
99
+ apply(parent);
100
+ for(const [index,fix] of fixes.entries()){
101
+ for(const step of steps.filter(step=>step.beforeFix===index))applyDelivery(expected,step.pkg,strict);
102
+ apply(fix);
103
+ }
104
+ return expected;
105
+ }
106
+
107
+ // steps: resolved steps [{beforeFix,runId,packageDigest,pkg}] whose packages were
108
+ // read from the named runs' verified stores.
109
+ export function composeFixCode({baseline,parentPackage,fixPackages,steps=[]}){
110
+ const chain=bindChain({baseline,parentPackage,fixPackages}),{base,parent,fixes}=chain;
111
+ readSteps(json(compact(steps)),fixes.length);
112
+ const resolved=steps.map(step=>{const pkg=readReviewPackage(step.pkg);
113
+ need(pkg.packageDigest===step.packageDigest&&pkg.rootDigest===base.rootDigest,'fix_association_unverified');return {...step,pkg};});
114
+ // Metadata-only transitions cannot rebuild legacy full-content inventories.
115
+ need(!resolved.length||base.version===2,'fix_before_mismatch');
116
+ const files=[...composeState(chain,resolved).values()].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
27
117
  // Use the same canonical inventory for live association and journal replay.
28
118
  return {base,parent,fixes,files:base.version===1?files:files.map(inventoryFile)};
29
119
  }
30
120
 
31
- export function inspectFixCodeAssociation({root,specsRoot,baseline,parentPackage,fixPackage,fixPackages}){
32
- const {base,parent,fixes,files}=composeFixCode({baseline,parentPackage,fixPackages:fixPackages??[fixPackage]});
121
+ // A completed run's reviewed package is history: other task runs deliver later,
122
+ // separately reviewed changes on top of it (their AGENTS.md learning lines, their
123
+ // own files, even this run's files). Apply every one of them, in durable review
124
+ // order and strictly; the result must be the current tree exactly.
125
+ export function explainReviewedDrift({root,baseline,composed,ownScope,deliveries,after}){
126
+ const base=readReviewBaseline(baseline);
127
+ const state=new Map(composed.map(file=>[file.path,inventoryFile(file)])),tolerated=toleratedConfig(ownScope);
128
+ for(const entry of laterSequence(deliveries,after,base.rootDigest))applyDelivery(state,entry.pkg,tolerated);
129
+ compareCurrent({root,base,state,tolerated});
130
+ }
131
+
132
+ // Completed run without accepted fixes: its own reviewed composition, then drift.
133
+ export function explainCompletedDelivery({root,baseline,parentPackage,deliveries,after}){
134
+ const base=readReviewBaseline(baseline),parent=readReviewPackage(parentPackage);
135
+ need(parent.baseIdentity===base.baselineDigest&&parent.rootDigest===base.rootDigest
136
+ &&digest(parent.identity)===digest(base.identity),'fix_parent_binding_mismatch');
137
+ if(base.specification)verifySpecificationMaterial(base);
138
+ const expected=new Map(base.files.map(file=>[file.path,inventoryFile(file)]));
139
+ for(const change of parent.changes){
140
+ need(sameFile(expected.get(change.path)??null,change.before),'fix_before_mismatch');
141
+ if(change.after===null)expected.delete(change.path);else expected.set(change.path,inventoryFile(change.after));
142
+ }
143
+ explainReviewedDrift({root,baseline:base,composed:[...expected.values()],ownScope:parent.scope,deliveries,after});
144
+ }
145
+
146
+ // One deterministic order for a run with QA fixes, from facts fixed at
147
+ // acceptance. The accepted record's ordered list stays exactly as it is; every
148
+ // other qualifying delivery is applied after the last fix, in review order. A new
149
+ // fix (extend) takes, before itself, every qualifying delivery not yet recorded
150
+ // whose review preceded its own final review (fixTime), all in review order. So a
151
+ // delivery that was reviewed before a fix but committed only after its acceptance
152
+ // is simply applied after that fix. Every step and every later delivery applies
153
+ // strictly; the result must be the current tree exactly.
154
+ export function inspectFixCodeAssociation({root,specsRoot,baseline,parentPackage,fixPackage,fixPackages,steps=[],extend=false,
155
+ deliveries=null,after=null,fixTime=null}){
156
+ const chainPackages=fixPackages??[fixPackage];
157
+ const chain=bindChain({baseline,parentPackage,fixPackages:chainPackages}),{base,parent,fixes}=chain,last=fixes.length-1;
158
+ const prior=readSteps(json(steps),extend?last:fixes.length),ownScope=[...parent.scope,...fixes.flatMap(fix=>fix.scope)];
159
+ const tolerated=toleratedConfig(ownScope);
160
+ const later=typeof deliveries==='function'?laterSequence(deliveries(),after,base.rootDigest):[];
161
+ const slot=(runId,packageDigest)=>`${runId}\0${packageDigest}`;
162
+ const found=new Map(later.map(entry=>[slot(entry.runId,entry.pkg.packageDigest),entry]));
163
+ // Each recorded step must still be a completed, later reviewed delivery.
164
+ const recorded=prior.map(step=>{const entry=found.get(slot(step.runId,step.packageDigest));
165
+ need(entry,'fix_association_unverified');return {...step,pkg:entry.pkg};});
166
+ const used=new Set(recorded.map(step=>slot(step.runId,step.packageDigest)));
167
+ let rest=later.filter(entry=>!used.has(slot(entry.runId,entry.pkg.packageDigest)));
168
+ if(extend&&rest.length){
169
+ const time=typeof fixTime==='function'?fixTime(fixes[last]):null;
170
+ need(Number.isSafeInteger(time),'fix_association_unverified');
171
+ recorded.push(...rest.filter(entry=>entry.reviewedAt<time).map(entry=>({...deliveryStep(entry.runId,entry.pkg,last),pkg:entry.pkg})));
172
+ rest=rest.filter(entry=>entry.reviewedAt>=time);
173
+ }
174
+ const {files}=composeFixCode({baseline,parentPackage,fixPackages:chainPackages,steps:recorded});
33
175
  if(base.specification)verifySpecificationMaterial(base);
34
176
  const current=captureReviewBaseline({root,
35
177
  ...(base.specification?{specification:{specsRoot:base.specificationRoot,feature:base.specification.feature}}:{}),...(specsRoot===undefined?{}:{specsRoot}),identity:parent.identity,version:base.version,
36
178
  ...(base.codeProjectPaths?{codeProjectPaths:base.codeProjectPaths}:{}),
37
- scope:[...new Set([...parent.scope,...fixes.flatMap(fix=>fix.scope)])],requirements:base.requirements});
179
+ scope:[...new Set(ownScope)],requirements:base.requirements});
38
180
  need(current.rootDigest===base.rootDigest,'fix_parent_binding_mismatch');
39
181
  const compared=base.version===1?current.files:current.files.map(inventoryFile);
40
- need(digest(compared)===digest(files),'fix_current_code_unexplained');
41
- return json({version:1,kind:'cm-fix-code-association',parentPackageDigest:parent.packageDigest,
42
- fixPackageDigest:fixes.at(-1).packageDigest,currentFilesDigest:digest(compared)});
182
+ if(rest.length||digest(compared)!==digest(files)){
183
+ // Without a way to read other runs' deliveries the historical exact match holds.
184
+ need(typeof deliveries==='function','fix_current_code_unexplained');
185
+ // Metadata-only transitions cannot rebuild legacy full-content inventories.
186
+ need(!rest.length||base.version===2,'fix_before_mismatch');
187
+ const state=new Map(files.map(file=>[file.path,inventoryFile(file)]));
188
+ for(const entry of rest)applyDelivery(state,entry.pkg,tolerated);
189
+ compareCurrent({root,base,state,tolerated});
190
+ }
191
+ return associationRecord({parent,fixes,files,steps:compact(recorded)});
192
+ }
193
+ export function associationRecord({parent,fixes,files,steps}){
194
+ return json({version:steps.length?2:1,kind:'cm-fix-code-association',parentPackageDigest:parent.packageDigest,
195
+ fixPackageDigest:fixes.at(-1).packageDigest,currentFilesDigest:digest(files),...(steps.length?{laterDeliveries:steps}:{})});
43
196
  }
@@ -1,4 +1,4 @@
1
- // Approved 0.bootstrap instruction task, inside the original develop effect.
1
+ // Approved bootstrap instruction task, inside the original develop effect.
2
2
  // A factory capability owns only init's fixed paths; never a developer grant.
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
@@ -7,18 +7,48 @@ import {cmInitRuleTargets,generateCmInitDraft,validateCmInitSelection} from '../
7
7
  import {inspectCmInitDraft,readCmInitSource} from '../cm-init/draft-inspection.mjs';
8
8
  import {replaceSessionFile} from '../cm-prd/session.mjs';
9
9
  import {readReviewSourceFiles,readReviewBaseline} from './review-package.mjs';
10
- import {inspectCmAiBootstrapTask} from './cm-ai-admission.mjs';
10
+ import {inspectCmAiBootstrapTask,identifyApprovedBootstrapFeature,parseFeatureTaskText} from './cm-ai-admission.mjs';
11
+ import {approvedTaskGrammar} from '../spec-task-line.mjs';
12
+ import {readCommittedRuleBasis} from './committed-rule-basis.mjs';
11
13
  import {readProjectInstructionContext,createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective} from './cm-ai-context-refresh.mjs';
12
14
  import {validateDeveloperScope,readDeveloperRequest} from './developer-adapter.mjs';
13
- import {digest,json,shape,need,freeze,validIdentity,hex,requestFor,terminalFor} from './effect-contract.mjs';
15
+ import {digest,json,shape,need,freeze,validIdentity,hex,requestFor,terminalFor,boundedReason} from './effect-contract.mjs';
14
16
 
15
17
  const capabilities=new WeakMap();
16
18
  const categories=['commands','globs','file_references','constraint_preservation','rule_applicability'];
17
19
  const sha=bytes=>bytes===null?null:createHash('sha256').update(bytes).digest('hex');
18
20
  const same=(a,b)=>need(digest(a)===digest(b),'bootstrap_binding_changed');
21
+ const learningSection=source=>/^## 项目教训[ \t]*\r?$/gmu.test(source);
19
22
  const canonical=root=>need(typeof root==='string'&&path.isAbsolute(root)&&fs.realpathSync(root)===root
20
23
  &&fs.lstatSync(root).isDirectory(),'bootstrap_root_invalid');
21
24
 
25
+ export function committedBootstrapBasis({specsDir,codeProject,feature,taskId,instructionPaths,requireCleanIndex=true}){
26
+ const parsed=parseFeatureTaskText(fs.readFileSync(path.join(specsDir,feature,'tasks.md'),'utf8'),
27
+ {allowDependencyPunctuation:true,grammar:approvedTaskGrammar(specsDir)});
28
+ need(!parsed.error,'bootstrap_task_required');
29
+ const index=parsed.tasks.findIndex(task=>task.id===taskId);
30
+ const priorRules=index>0&&parsed.tasks.slice(0,index).some(task=>task.completed&&!task.dropped
31
+ &&/(?:cm-init|\.claude\/|AGENTS\.md)/i.test(task.description)
32
+ &&/(?:生成|规范|规则|instruction|rules|generate)/i.test(task.description));
33
+ return priorRules?readCommittedRuleBasis(codeProject,instructionPaths,{requireCleanIndex}):undefined;
34
+ }
35
+
36
+ export function mergeBootstrapAgents(existing,generated,{refresh=false}={}){
37
+ need(typeof existing==='string'&&typeof generated==='string','bootstrap_instruction_conflict');
38
+ if(!existing)return generated;
39
+ const heading=/^## 项目教训[ \t]*\r?$/gmu.exec(existing);
40
+ if(!heading){need(refresh||generated.includes(existing),'bootstrap_instruction_conflict');return generated;}
41
+ const next=/^## [^\r\n]+\r?$/gmu;
42
+ next.lastIndex=heading.index+heading[0].length;
43
+ const end=next.exec(existing)?.index??existing.length;
44
+ const section=existing.slice(heading.index,end);
45
+ const before=existing.slice(0,heading.index),after=existing.slice(end);
46
+ need(refresh||(!before||generated.includes(before))&&(!after||generated.includes(after)),'bootstrap_instruction_conflict');
47
+ if(generated.includes(section))return generated;
48
+ need(!/^## 项目教训[ \t]*\r?$/gmu.test(generated),'bootstrap_instruction_conflict');
49
+ return generated+(generated.endsWith('\n')?'':'\n')+'\n'+section;
50
+ }
51
+
22
52
  export function readBootstrapEvidence(raw,configuration,identity){
23
53
  const value=json(raw);
24
54
  shape(value,['version','workflow','phase','identity','invocationId','configurationDigest','files','contextFiles','evidenceDigest']);
@@ -42,7 +72,15 @@ export function validateBootstrapReviewPackage(pkg,evidence,configuration,identi
42
72
  for(const file of value.files){
43
73
  const change=pkg.changes.find(item=>item.path===file.path);
44
74
  const expected=file.path==='AGENTS.md'&&writeback.outcome==='written'?writeback.agentsFile.sha256:file.afterSha256;
45
- need(change?.after?.sha256===expected&&pkg.scope.includes(file.path),'bootstrap_review_mismatch');
75
+ need(pkg.scope.includes(file.path),'bootstrap_review_mismatch');
76
+ if(change!==undefined){
77
+ // The package covers the whole delivery against the run's original
78
+ // baseline. Both a new attempt and a same-attempt retry may start from
79
+ // already-written rules. Write admission checks that starting content;
80
+ // package validation binds the final bytes, not this effect's before hash.
81
+ need(change.after?.sha256===expected,'bootstrap_review_mismatch');
82
+ }else need(pkg.unchangedScope?.some(item=>item.path===file.path&&item.sha256===expected),
83
+ 'bootstrap_review_mismatch');
46
84
  }
47
85
  return value;
48
86
  }
@@ -50,11 +88,13 @@ export function validateBootstrapReviewPackage(pkg,evidence,configuration,identi
50
88
  export function bootstrapConfiguration(capability,{root,identity,scope,feature}){
51
89
  const configuration=capabilities.get(capability);need(configuration,'bootstrap_capability_required');
52
90
  same(configuration.codeProject,root);same(configuration.identity, {...identity,attempt:1});
53
- same(configuration.scope,scope);need(feature==='0.bootstrap','bootstrap_task_required');return configuration;
91
+ same(configuration.scope,scope);need(feature===configuration.feature
92
+ &&feature===identifyApprovedBootstrapFeature([configuration.feature]),'bootstrap_task_required');return configuration;
54
93
  }
55
94
 
56
95
  export function createHostBootstrap({definition,workflowRoot,selection,bridge,allowWrite}){
57
- const data=json(definition);validIdentity(data.identity);need(data.identity.attempt===1&&data.feature==='0.bootstrap','bootstrap_task_required');
96
+ const data=json(definition);validIdentity(data.identity);need(data.identity.attempt===1
97
+ &&data.feature===identifyApprovedBootstrapFeature(data.specsDir),'bootstrap_task_required');
58
98
  canonical(data.codeProject);canonical(data.specsDir);canonical(workflowRoot);
59
99
  need(typeof bridge?.call==='function'&&typeof allowWrite==='boolean','bootstrap_configuration_invalid');
60
100
  // Construction is non-writing and may occur during resume. Only the runner's
@@ -62,6 +102,9 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
62
102
  const selected=inspectCmAiBootstrapTask({specsDir:data.specsDir,codeProject:data.codeProject,taskId:data.identity.taskId},true);
63
103
  const mode=selected.mode,choice=mode==='scaffold'?null:validateCmInitSelection(selection);
64
104
  const instructionPaths=mode==='scaffold'?[]:cmInitRuleTargets(choice);
105
+ const committedBasis=mode==='instructions'?committedBootstrapBasis({specsDir:data.specsDir,
106
+ codeProject:data.codeProject,feature:data.feature,taskId:data.identity.taskId,instructionPaths,
107
+ requireCleanIndex:false}):undefined;
65
108
  need(Array.isArray(data.scope)&&new Set(data.scope).size===data.scope.length
66
109
  &&instructionPaths.every(file=>data.scope.includes(file)),'bootstrap_scope_required');
67
110
  const businessScope=data.scope.filter(file=>!instructionPaths.includes(file));
@@ -69,11 +112,12 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
69
112
  for(const file of instructionPaths){const target=path.join(data.codeProject,file);
70
113
  need(target!==data.specsDir&&!target.startsWith(data.specsDir+path.sep),'bootstrap_specs_overlap');}
71
114
  const bootstrapRequirements={specsRoot:data.specsDir,feature:data.feature,
72
- files:readReviewSourceFiles(data.specsDir,['0.bootstrap/requirements.md','0.bootstrap/design.md'])};
115
+ files:readReviewSourceFiles(data.specsDir,[`${data.feature}/requirements.md`,`${data.feature}/design.md`])};
73
116
  const policyDigest=digest(instructionPaths.slice(2).map(file=>{
74
117
  const relative='templates/rules/'+path.basename(file);return [relative,sha(readCmInitSource(workflowRoot,relative))];}));
75
118
  const configuration=json({version:1,mode,codeProject:data.codeProject,specsDir:data.specsDir,feature:data.feature,
76
- identity:data.identity,scope:data.scope,businessScope,instructionPaths,workflowRoot,selection:choice,policyDigest,bootstrapRequirements});
119
+ identity:data.identity,scope:data.scope,businessScope,instructionPaths,workflowRoot,selection:choice,policyDigest,bootstrapRequirements,
120
+ ...(committedBasis!==undefined?{committedBasisRequired:true,committedBasis}:{})});
77
121
  const used=new Set();
78
122
  const admission=baseline=>{
79
123
  const original=readReviewBaseline(baseline);
@@ -81,26 +125,57 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
81
125
  if(mode==='scaffold')need(original.files.length===0,'bootstrap_original_not_empty');
82
126
  return inspectCmAiBootstrapTask({specsDir:data.specsDir,codeProject:data.codeProject,taskId:data.identity.taskId},mode==='scaffold').admission;
83
127
  };
84
- const capability={configuration,inspectAdmission:admission,
128
+ const instructionBaseline=({identity,previous=null,previousWriteback=null})=>{
129
+ need(mode==='instructions','bootstrap_task_required');
130
+ if(committedBasis===null){
131
+ const error=new Error('bootstrap_instruction_conflict');error.code='bootstrap_instruction_conflict';
132
+ error.paths=instructionPaths;throw error;
133
+ }
134
+ if(committedBasis!==undefined){
135
+ const current=readCommittedRuleBasis(data.codeProject,instructionPaths);
136
+ if(digest(current)!==digest(committedBasis)){
137
+ const error=new Error('bootstrap_instruction_conflict');error.code='bootstrap_instruction_conflict';
138
+ error.paths=instructionPaths;throw error;
139
+ }
140
+ }
141
+ const retry=previous!==null&&previous.identity?.attempt===identity.attempt;
142
+ const prior=previous===null?null:readBootstrapEvidence(previous,configuration,
143
+ {...identity,attempt:retry?identity.attempt:identity.attempt-1});
144
+ need(identity.attempt===1?prior===null||retry:prior!==null,'bootstrap_prior_evidence_required');
145
+ const originals=instructionPaths.map(file=>({path:file,bytes:readCmInitSource(data.codeProject,file)}));
146
+ const conflicts=[];
147
+ for(const file of originals){
148
+ const initial=configuration.committedBasisRequired
149
+ ?configuration.committedBasis.files.find(item=>item.path===file.path).sha256
150
+ :file.path==='AGENTS.md'&&file.bytes!==null
151
+ &&learningSection(new TextDecoder('utf8',{fatal:true}).decode(file.bytes))?sha(file.bytes):null;
152
+ const expected=file.path==='AGENTS.md'&&prior!==null&&previousWriteback?.outcome==='written'
153
+ ?previousWriteback.agentsFile.sha256:prior?.files.find(item=>item.path===file.path).afterSha256??initial;
154
+ if(sha(file.bytes)!==expected)conflicts.push(file.path);
155
+ }
156
+ if(conflicts.length){const error=new Error('bootstrap_instruction_conflict');error.code='bootstrap_instruction_conflict';
157
+ error.paths=conflicts;throw error;}
158
+ return {originals,prior};
159
+ };
160
+ const capability={configuration,inspectAdmission:admission,assertInstructionBaseline:instructionBaseline,
85
161
  assertWriteAuthorized(){need(allowWrite,'bootstrap_write_authorization_required');},
86
- async run(request,control,develop,{previous=null,previousWriteback=null,baseline}={}){
162
+ async run(request,control,develop,{previous=null,previousWriteback=null,baseline,verificationFailed=null}={}){
87
163
  need(allowWrite,'bootstrap_write_authorization_required');
88
164
  need(!control.signal.aborted,'cancelled');
89
165
  same({...request.identity,attempt:1},data.identity);same(request.payload.scope,data.scope);
90
166
  need(!used.has(request.invocationId),'bootstrap_dispatch_unknown');
91
167
  const currentAdmission=admission(baseline);
92
168
  need(currentAdmission.nextTask?.feature===data.feature&&currentAdmission.nextTask.id===request.identity.taskId,'bootstrap_task_required');
93
- const prior=previous===null?null:readBootstrapEvidence(previous,configuration,{...request.identity,attempt:request.identity.attempt-1});
94
- if(mode==='instructions')need(request.identity.attempt===1?prior===null:prior!==null,'bootstrap_prior_evidence_required');
95
- const originals=instructionPaths.map(file=>({path:file,bytes:readCmInitSource(data.codeProject,file)}));
96
- for(const file of originals){
97
- const expected=file.path==='AGENTS.md'&&prior!==null&&previousWriteback?.outcome==='written'
98
- ?previousWriteback.agentsFile.sha256:prior?.files.find(item=>item.path===file.path).afterSha256??null;
99
- need(sha(file.bytes)===expected,'bootstrap_instruction_conflict');
100
- }
169
+ // A revision binds to the previous attempt's evidence. A retryable develop
170
+ // block after this effect wrote the rules (develop_checks_not_passed) retries
171
+ // the same attempt, so it binds to that attempt's own recorded evidence.
172
+ const {originals}=mode==='instructions'?instructionBaseline({identity:request.identity,previous,previousWriteback})
173
+ :{originals:instructionPaths.map(file=>({path:file,bytes:readCmInitSource(data.codeProject,file)}))};
101
174
  used.add(request.invocationId);
102
175
  const current=()=>{
103
176
  canonical(data.codeProject);
177
+ if(committedBasis!==undefined)need(digest(readCommittedRuleBasis(data.codeProject,instructionPaths))
178
+ ===digest(committedBasis),'bootstrap_instruction_conflict');
104
179
  for(const file of originals)need(sha(readCmInitSource(data.codeProject,file.path))===sha(file.bytes),'bootstrap_instruction_conflict');
105
180
  };
106
181
  let response=null;
@@ -120,29 +195,51 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
120
195
  return terminalFor(response,request);
121
196
  }
122
197
  current();need(!control.signal.aborted,'cancelled');
123
- const draft=await generateCmInitDraft({project:data.codeProject,workflowRoot,selection:choice},{signal:control.signal,
198
+ const generated=await generateCmInitDraft({project:data.codeProject,workflowRoot,selection:choice},{signal:control.signal,
124
199
  generate:(payload,signal)=>bridge.call('init_generate',{...payload,bootstrap:{identity:request.identity,
125
200
  invocationId:request.invocationId,requirements:[...request.payload.requirements,...bootstrapRequirements.files],
126
201
  priorReview:request.payload.priorReview}},signal)});
127
- need(draft.status==='draft_generated'&&draft.inspection.status==='structurally_checked','bootstrap_generation_blocked');
128
- const verified=json(await bridge.call('init_verify',{project:data.codeProject,selection:choice,documents:draft.documents,
129
- inspection:draft.inspection,categories,learningInput:request.payload.learningInput,
202
+ need(generated.status==='draft_generated'&&generated.inspection.status==='structurally_checked','bootstrap_generation_blocked');
203
+ const agentsBefore=originals.find(file=>file.path==='AGENTS.md').bytes;
204
+ const documents=generated.documents.map(document=>document.path==='AGENTS.md'
205
+ ?{path:document.path,content:mergeBootstrapAgents(agentsBefore?.toString('utf8')??'',document.content,
206
+ {refresh:committedBasis!==undefined})}:document);
207
+ const inspection=inspectCmInitDraft({project:data.codeProject,documents,selection:choice});
208
+ need(inspection.status==='structurally_checked','bootstrap_generation_blocked');
209
+ const verified=json(await bridge.call('init_verify',{project:data.codeProject,selection:choice,documents,
210
+ inspection,categories,learningInput:request.payload.learningInput,
130
211
  instructions:'Verify every generated instruction against the approved bootstrap selection and current project. Do not write files, install or dispatch providers. Return {checks,constraintChanges,application,retrospective}; checks use status/evidence. Application and retrospective use the original developer Learning response fields. Unverified assertions block. This is host verification, not independent Review.'},control.signal));
131
212
  shape(verified,['checks','constraintChanges','application','retrospective']);shape(verified.checks,categories);
132
- for(const check of Object.values(verified.checks)){shape(check,['status','evidence']);
133
- need(['verified','not_applicable'].includes(check.status)&&typeof check.evidence==='string'&&check.evidence.trim(),'bootstrap_verification_blocked');}
213
+ const unverified=[];
214
+ for(const name of categories){const check=verified.checks[name];shape(check,['status','evidence']);
215
+ need(typeof check.status==='string'&&typeof check.evidence==='string','bootstrap_verification_blocked');
216
+ if(!['verified','not_applicable'].includes(check.status)||!check.evidence.trim())
217
+ unverified.push(`${name}: ${check.status}; ${check.evidence.trim()||'(no evidence)'}`);}
218
+ // A well-formed verify that does not pass is a determinate answer, not an
219
+ // unknown effect: nothing has been written yet (writes follow below), so the
220
+ // same attempt redoes generation and verification against the evidence it
221
+ // started from. Only the runner's callback may carry the bounded reason.
222
+ if(unverified.length){
223
+ need(typeof verificationFailed==='function','bootstrap_verification_blocked');
224
+ current();verificationFailed(boundedReason('bootstrap_verification_failed: init_verify 未通过的核验组:',unverified,
225
+ '。规范尚未写入;按证据修正项目或生成内容后恢复运行,本轮重新生成并核验'));
226
+ return terminalFor({version:1,invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
227
+ effectiveModel:response?.effectiveModel??'host-bootstrap',status:'failed',accepted:true,
228
+ ...(response?.providerThreadId?{providerThreadId:response.providerThreadId}:{}),
229
+ result:{code:'bootstrap_verification_failed',reason:'bootstrap_verification_failed'}},request);
230
+ }
134
231
  need(Array.isArray(verified.constraintChanges)&&verified.constraintChanges.length===0,'bootstrap_constraint_confirmation_required');
135
232
  const learning=request.payload.learningInput;
136
- need(learning?.feature==='0.bootstrap','bootstrap_learning_required');
233
+ need(learning?.feature===data.feature,'bootstrap_learning_required');
137
234
  shape(verified.application,['status','note']);shape(verified.retrospective,['status','candidates','reason']);
138
235
  const binding={feature:learning.feature,identity:request.identity,learningDigest:learning.learningDigest};
139
236
  const application=createCmAiTaskLearningApplication({...binding,...verified.application});
140
237
  const retrospective=createCmAiTaskLearningRetrospective({...binding,...verified.retrospective});
141
238
  current();need(!control.signal.aborted,'cancelled');
142
- same(inspectCmInitDraft({project:data.codeProject,documents:draft.documents}).changes,draft.inspection.changes);
239
+ same(inspectCmInitDraft({project:data.codeProject,documents}).changes,inspection.changes);
143
240
  // All targets are prechecked before the first write. Interruption stays in
144
241
  // the runner's original unknown develop effect, never an automatic retry.
145
- for(const document of draft.documents){
242
+ for(const document of documents){
146
243
  need(!control.signal.aborted,'cancelled');canonical(data.codeProject);
147
244
  let parent=data.codeProject;
148
245
  for(const part of document.path.split('/').slice(0,-1)){
@@ -152,13 +249,13 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
152
249
  const before=originals.find(file=>file.path===document.path).bytes;
153
250
  replaceSessionFile(data.codeProject,document.path,before===null?null:new TextDecoder('utf8',{fatal:true}).decode(before),document.content);
154
251
  }
155
- const after=inspectCmInitDraft({project:data.codeProject,documents:draft.documents});
252
+ const after=inspectCmInitDraft({project:data.codeProject,documents});
156
253
  need(after.status==='structurally_checked'&&after.changes.every(file=>file.action==='unchanged'),'bootstrap_write_unknown');
157
254
  const contextFiles=readProjectInstructionContext(data.codeProject).map(({content,...file})=>file);
158
255
  // Optional module rules must be reachable through the generated entry.
159
256
  const evidenceBody={version:1,workflow:'cm-ai',phase:'bootstrap_instructions',identity:request.identity,
160
257
  invocationId:request.invocationId,configurationDigest:digest(configuration),
161
- files:instructionPaths.map(file=>{const change=draft.inspection.changes.find(item=>item.path===file);
258
+ files:instructionPaths.map(file=>{const change=inspection.changes.find(item=>item.path===file);
162
259
  return {path:file,beforeSha256:change.beforeSha256,afterSha256:change.afterSha256};}),contextFiles};
163
260
  const bootstrap=readBootstrapEvidence({...evidenceBody,evidenceDigest:digest(evidenceBody)},configuration,request.identity);
164
261
  return terminalFor({version:1,invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
@@ -9,18 +9,35 @@ import {StringDecoder} from 'node:string_decoder';
9
9
  import {cleanEnvironment,specsPermissionArgs} from './codex-config.mjs';
10
10
  import {json,shape,need,id,text,validCallTimeout,validIdentity} from './effect-contract.mjs';
11
11
 
12
- export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,outputIncludes=null,onOutput=null}){
12
+ export function reportHostCheckProgress(event){
13
+ const message=event.phase==='start'?`开始检查 ${event.id}`:
14
+ `检查结束 ${event.id}: ${event.outcome} (exit ${event.exitCode??'unavailable'})`;
15
+ try{process.stderr.write(`[check] ${message}\n`);}catch{/* display is not a check verdict */}
16
+ }
17
+ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,outputIncludes=null,onOutput=null,onProgress=null,reuseDeclared=false}){
18
+ need(typeof reuseDeclared==='boolean','invalid_check_config');
13
19
  need(path.isAbsolute(cwd)&&fs.realpathSync(cwd)===cwd&&fs.statSync(cwd).isDirectory());
14
20
  validCallTimeout(timeoutMs);
15
21
  need(onOutput===null||typeof onOutput==='function');
22
+ need(onProgress===null||typeof onProgress==='function');
23
+ const notify=event=>{
24
+ try{
25
+ const returned=onProgress?.(Object.freeze(event));
26
+ if(types.isPromise(returned))Promise.prototype.then.call(returned,()=>{},()=>{});
27
+ }catch{/* observers cannot change results or prevent cleanup */}
28
+ };
16
29
  if(outputIncludes!==null){text(outputIncludes);need(Buffer.byteLength(outputIncludes)<=1000&&!outputIncludes.includes('\0'));}
17
30
  const signature=outputIncludes===null?null:Buffer.from(outputIncludes);
18
31
  const selected=json(commands,32*1024),ids=new Set();
19
32
  need(Array.isArray(selected)&&selected.length>0&&selected.length<=32);
20
- for(const item of selected){
21
- shape(item,['id','command']);id(item.id);need(!ids.has(item.id));ids.add(item.id);
33
+ for(const [index,item] of selected.entries()){
34
+ shape(item,['id','command',...(reuseDeclared&&Object.hasOwn(item,'sameExecutionAs')?['sameExecutionAs']:[])]);id(item.id);need(!ids.has(item.id));ids.add(item.id);
22
35
  need(Array.isArray(item.command)&&item.command.length>0);
23
36
  for(const arg of item.command){text(arg);need(!arg.includes('\0'));}
37
+ if(Object.hasOwn(item,'sameExecutionAs')){
38
+ const previous=selected[index-1];
39
+ need(previous&&item.sameExecutionAs===previous.id&&JSON.stringify(item.command)===JSON.stringify(previous.command),'check_reuse_binding');
40
+ }
24
41
  }
25
42
  return async(raw,{signal})=>{
26
43
  shape(raw,['identity']);validIdentity(raw.identity);
@@ -29,6 +46,14 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
29
46
  for(const item of selected){
30
47
  let signatureMatched=false;
31
48
  need(!signal.aborted,'cancelled');
49
+ if(Object.hasOwn(item,'sameExecutionAs')){
50
+ const original=results[results.length-1];need(original?.outcome==='passed','check_reuse_binding');
51
+ const evidence=`same execution as ${original.id}; ${original.evidence}`.slice(0,200);
52
+ notify({phase:'complete',id:item.id,outcome:original.outcome,exitCode:original.exitCode,sameExecutionAs:original.id});
53
+ results.push({id:item.id,command:item.command,outcome:original.outcome,exitCode:original.exitCode,evidence,
54
+ ...(signature?{signatureMatched:original.signatureMatched}:{})});continue;
55
+ }
56
+ notify({phase:'start',id:item.id});
32
57
  const result=await new Promise(resolve=>{
33
58
  let child;
34
59
  try{
@@ -99,8 +124,9 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
99
124
  }
100
125
  });
101
126
  });
127
+ notify({phase:'complete',id:item.id,outcome:result.outcome,exitCode:result.exitCode});
102
128
  need(!signal.aborted,'cancelled');
103
- results.push({...item,...result,...(signature?{signatureMatched}:{})});
129
+ results.push({id:item.id,command:item.command,...result,...(signature?{signatureMatched}:{})});
104
130
  if(result.outcome!=='passed')break;
105
131
  }
106
132
  return json(results);