@aibyzero/cm-workflow 0.21.7 → 0.25.0

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 (200) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +52 -0
  3. package/README.md +10 -1
  4. package/VERSION +1 -1
  5. package/docs/architecture.md +9 -0
  6. package/docs/cm-acceptance-completion.md +3 -1
  7. package/docs/cm-control-policy-v2.md +35 -3
  8. package/docs/execution-optimizations.md +1 -1
  9. package/docs/external-models.md +1 -0
  10. package/docs/human-correction.md +1 -1
  11. package/docs/installation.md +36 -10
  12. package/docs/js-workflow-control.md +65 -30
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +2 -2
  15. package/docs/user-guide.md +1 -1
  16. package/package.json +1 -1
  17. package/runtime/js/cm-ai/batch-location.mjs +14 -0
  18. package/runtime/js/cm-ai/batch-plan.mjs +6 -2
  19. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  20. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  21. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  22. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  23. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  24. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  25. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  26. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  27. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  28. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  29. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  30. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  31. package/runtime/js/cm-ai/host-check.mjs +4 -2
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +23 -2
  33. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  34. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  42. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  44. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  45. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  46. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  47. package/runtime/js/cm-ai/review-package.mjs +25 -4
  48. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  49. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  50. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  52. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  53. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  54. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  56. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  57. package/runtime/js/cm-fix/execution.mjs +47 -9
  58. package/runtime/js/cm-fix/finish.mjs +9 -1
  59. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  60. package/runtime/js/cm-idea/session.mjs +22 -3
  61. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  62. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  63. package/runtime/js/cm-prd/analysis.mjs +27 -9
  64. package/runtime/js/cm-prd/change.mjs +29 -8
  65. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  66. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  67. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  68. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  69. package/runtime/js/cm-prd/self-check.mjs +121 -9
  70. package/runtime/js/cm-prd/session.mjs +55 -13
  71. package/runtime/js/cm-prd/summary.mjs +34 -6
  72. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  73. package/runtime/js/cm-refactor/records.mjs +82 -11
  74. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  75. package/runtime/js/executor-version.mjs +81 -0
  76. package/runtime/js/python-log-writer.mjs +15 -0
  77. package/runtime/js/run-analysis.mjs +136 -11
  78. package/runtime/logging.md +6 -0
  79. package/runtime/review.md +2 -1
  80. package/scripts/ci-test-weights.json +1 -0
  81. package/scripts/cm-ai-admission.mjs +27 -1
  82. package/scripts/cm-ai-admission.test.mjs +34 -2
  83. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  84. package/scripts/cm-ai-batch-drive.mjs +54 -17
  85. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  86. package/scripts/cm-ai-batch-host.mjs +55 -9
  87. package/scripts/cm-ai-batch-host.test.mjs +22 -3
  88. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  89. package/scripts/cm-ai-batch-merge.mjs +102 -0
  90. package/scripts/cm-ai-batch-plan.mjs +55 -2
  91. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  92. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  93. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  94. package/scripts/cm-ai-batch-run.mjs +435 -33
  95. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  96. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  97. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  98. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  99. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  100. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  101. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  102. package/scripts/cm-ai-drive.mjs +66 -14
  103. package/scripts/cm-ai-drive.test.mjs +13 -3
  104. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  105. package/scripts/cm-ai-host.mjs +16 -8
  106. package/scripts/cm-ai-host.test.mjs +12 -0
  107. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  108. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  109. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  110. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  111. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  112. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  113. package/scripts/cm-ai-run.mjs +42 -11
  114. package/scripts/cm-ai-run.test.mjs +26 -0
  115. package/scripts/cm-ai-supersede.test.mjs +10 -2
  116. package/scripts/cm-capability-gate.test.mjs +1 -1
  117. package/scripts/cm-check-runtime.sh +9 -0
  118. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  119. package/scripts/cm-developer-self-review.test.mjs +27 -0
  120. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  121. package/scripts/cm-efficiency-response.test.mjs +2 -1
  122. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  123. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  124. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  125. package/scripts/cm-executor-version-records.test.mjs +256 -0
  126. package/scripts/cm-executor-version.test.mjs +250 -0
  127. package/scripts/cm-external-model-host.test.mjs +6 -1
  128. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  129. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  130. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  131. package/scripts/cm-fix-drive.mjs +7 -2
  132. package/scripts/cm-fix-drive.test.mjs +45 -0
  133. package/scripts/cm-fix-entry.mjs +5 -2
  134. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  135. package/scripts/cm-fix-host.mjs +9 -2
  136. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  137. package/scripts/cm-host-check.test.mjs +12 -0
  138. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  139. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  140. package/scripts/cm-idea-drive.mjs +5 -2
  141. package/scripts/cm-idea-entry.mjs +5 -2
  142. package/scripts/cm-idea-host.mjs +3 -1
  143. package/scripts/cm-init-drive.mjs +8 -5
  144. package/scripts/cm-init-entry.mjs +5 -2
  145. package/scripts/cm-init-host.mjs +6 -2
  146. package/scripts/cm-log-event.mjs +10 -2
  147. package/scripts/cm-log-event.test.mjs +29 -0
  148. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  149. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  150. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  151. package/scripts/cm-prd-completion.test.mjs +67 -4
  152. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  153. package/scripts/cm-prd-drive.mjs +89 -20
  154. package/scripts/cm-prd-drive.test.mjs +109 -4
  155. package/scripts/cm-prd-entry.mjs +5 -2
  156. package/scripts/cm-prd-host.mjs +89 -20
  157. package/scripts/cm-prd-host.test.mjs +17 -8
  158. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  159. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  160. package/scripts/cm-prd-review-gate.mjs +11 -4
  161. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  162. package/scripts/cm-prd-self-check.test.mjs +1 -1
  163. package/scripts/cm-refactor-drive.mjs +10 -4
  164. package/scripts/cm-refactor-entry.mjs +5 -2
  165. package/scripts/cm-refactor-host.mjs +3 -1
  166. package/scripts/cm-run-analysis.test.mjs +373 -1
  167. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  168. package/scripts/cm-skill-hints-exam.mjs +3 -1
  169. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  170. package/scripts/cm-skill-hints.mjs +106 -10
  171. package/scripts/cm-skill-hints.test.mjs +162 -6
  172. package/scripts/cm-skill-judge.mjs +2 -1
  173. package/scripts/cm-task-gate.mjs +88 -18
  174. package/scripts/cm-task-scope.test.mjs +1 -1
  175. package/scripts/cm-test-drive.mjs +13 -8
  176. package/scripts/cm-test-entry.mjs +5 -2
  177. package/scripts/cm-test-host.mjs +3 -1
  178. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  179. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  180. package/scripts/fixtures/prd-review-gate-python-oracle.py +9 -0
  181. package/scripts/policy-binding-compat.test.mjs +3 -2
  182. package/scripts/test-cm-prd-review-gate.py +25 -0
  183. package/skills/cm-ai/SKILL.md +1 -1
  184. package/skills/cm-ai/references/N1-init.md +1 -1
  185. package/skills/cm-ai/references/N4-review.md +2 -2
  186. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  187. package/skills/cm-ai/references/js-host-recovery.md +4 -1
  188. package/skills/cm-ai/references/js-host.md +17 -8
  189. package/skills/cm-fix/references/js-host.md +20 -0
  190. package/skills/cm-fix/references/test-extension.md +1 -1
  191. package/skills/cm-prd/SKILL.md +8 -6
  192. package/skills/cm-prd/references/ai-draft.md +81 -0
  193. package/skills/cm-prd/references/change-mode.md +2 -0
  194. package/skills/cm-prd/references/greenfield.md +2 -0
  195. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  196. package/skills/cm-prd/references/js-host.md +9 -6
  197. package/skills/cm-prd/references/light-mode.md +19 -0
  198. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  199. package/skills/cm-prd/references/spec-self-check.md +1 -0
  200. package/skills/cm-prd/references/summary-card.md +1 -0
@@ -17,7 +17,10 @@ import path from 'node:path';
17
17
  import {createHash} from 'node:crypto';
18
18
  import {need} from '../cm-ai/effect-contract.mjs';
19
19
  import {parseFeatureTaskText} from '../cm-ai/cm-ai-admission.mjs';
20
- import {checkPrdDraftMechanics,PRD_SELF_CHECK_RULE_VERSIONS,ruleReadsGrammar3,ruleExemptsInapplicable} from './self-check.mjs';
20
+ import {checkPrdDraftMechanics,PRD_SELF_CHECK_RULE_VERSIONS,ruleReadsGrammar3,ruleExemptsInapplicable,
21
+ ruleChecksSessionEvidence,ruleChecksFirstSessionEvidence,sessionTaskDigest,validTaskDigests} from './self-check.mjs';
22
+ import {parseTaskScopes} from '../task-scope.mjs';
23
+ import {TASK_GRAMMAR} from '../spec-task-line.mjs';
21
24
  import {readPrdSessionFile,replaceSessionFile} from './session.mjs';
22
25
  import {normalizeRuntimeMarkBytes} from '../../../scripts/cm-spec-manifest.mjs';
23
26
 
@@ -29,14 +32,19 @@ function taskIds(text,grammar){
29
32
  const parsed=parseFeatureTaskText(text,{grammar});
30
33
  return parsed.error?[]:parsed.tasks.map(task=>task.id).sort();
31
34
  }
32
- // Only rules that add something to re-checks are written: grammar-3 session tasks (4, 5) or the exemption (5, 6).
35
+ // Only rules that add something to re-checks are written: grammar-3 session tasks (4, 5, 7, 8),
36
+ // the exemption (5, 6, 7, 8) or a session-task evidence check (7 first version, 8).
33
37
  const recordedRule=rules=>ruleReadsGrammar3(rules)||ruleExemptsInapplicable(rules);
34
38
  function parseRecord(raw){
35
39
  let value;try{value=JSON.parse(raw);}catch{value=null;}
36
40
  need(value!==null&&typeof value==='object'&&value.version===1&&typeof value.enforced==='boolean'
37
41
  &&Array.isArray(value.exempt)&&value.exempt.every(id=>typeof id==='string')
38
42
  &&(!Object.hasOwn(value,'selfCheckRules')||PRD_SELF_CHECK_RULE_VERSIONS.includes(value.selfCheckRules)&&recordedRule(value.selfCheckRules))
39
- &&Object.keys(value).length===(Object.hasOwn(value,'selfCheckRules')?4:3),'prd_task_scope_record_invalid');
43
+ // sessionEvidenceExempt only with rule 8, and only when non-empty.
44
+ &&(!Object.hasOwn(value,'sessionEvidenceExempt')||ruleChecksSessionEvidence(value.selfCheckRules)
45
+ &&validTaskDigests(value.sessionEvidenceExempt)&&Object.keys(value.sessionEvidenceExempt).length>0)
46
+ &&Object.keys(value).length===3+Number(Object.hasOwn(value,'selfCheckRules'))+Number(Object.hasOwn(value,'sessionEvidenceExempt')),
47
+ 'prd_task_scope_record_invalid');
40
48
  return value;
41
49
  }
42
50
  // The record texts a change snapshot binds (only features that have one).
@@ -45,10 +53,18 @@ export function prdTaskScopeRecords(specs,directories){
45
53
  for(const directory of directories){const raw=readPrdSessionFile(specs,recordPath(directory));if(raw!==null)records[directory]=raw;}
46
54
  return records;
47
55
  }
48
- // {directory: {exempt}} for a change. A feature whose tasks.md is exactly the
49
- // approved bytes exempts the tasks of that approval, read with its grammar. An
50
- // unapproved state (a draft, or a change awaiting review) keeps what its own save
51
- // recorded, which traces back to an approval or is empty.
56
+ // Session tasks of an approved grammar-3 tasks.md, each with the digest of its own block: rule 8
57
+ // exempts such a task from the evidence check only while that block is unchanged (review r1 B4).
58
+ function approvedSessionTasks(text,grammar){
59
+ if(grammar!==TASK_GRAMMAR||typeof text!=='string'||parseFeatureTaskText(text,{grammar}).error)return {};
60
+ return Object.fromEntries([...parseTaskScopes(text,{grammar}).sessions].sort().map(id=>[id,sessionTaskDigest(text,id)]));
61
+ }
62
+ const withEvidence=(exempt,evidence)=>({exempt,...(evidence&&Object.keys(evidence).length?{evidence}:{})});
63
+ // {directory: {exempt, evidence?}} for a change. A feature whose tasks.md is exactly the
64
+ // approved bytes exempts the tasks of that approval, read with its grammar, and (evidence)
65
+ // its session tasks as they stand. An unapproved state (a draft, or a change awaiting
66
+ // review) keeps what its own save recorded, which traces back to an approval or is empty;
67
+ // the digests come from that validated record, not from re-reading any file.
52
68
  export function approvedScopeExemptions(before,directories,grammar){
53
69
  let status=null;try{status=JSON.parse(before.status??'null');}catch{status=null;}
54
70
  const approved=status?.status==='approved'&&Array.isArray(status.specFiles)?status.specFiles:[];
@@ -58,16 +74,18 @@ export function approvedScopeExemptions(before,directories,grammar){
58
74
  return Object.fromEntries(directories.map(directory=>{
59
75
  const file=`${directory}/tasks.md`,text=before.files[file];
60
76
  if(typeof text==='string'&&approved.some(item=>item?.path===file&&digests(text).includes(item.sha256)))
61
- return [directory,{exempt:taskIds(text,grammar)}];
62
- const record=before.scopeRecords?.[directory];
63
- return [directory,{exempt:record===undefined?[]:parseRecord(record).exempt}];
77
+ return [directory,withEvidence(taskIds(text,grammar),approvedSessionTasks(text,grammar))];
78
+ const record=before.scopeRecords?.[directory]===undefined?null:parseRecord(before.scopeRecords[directory]);
79
+ return [directory,withEvidence(record?.exempt??[],record?.sessionEvidenceExempt)];
64
80
  }));
65
81
  }
66
82
 
67
- // `exemptions` maps a directory to {exempt} (a change) or is empty (a new draft).
83
+ // `exemptions` maps a directory to {exempt, evidence?} (a change) or is empty (a new draft).
68
84
  // `selfCheckRules` is the rule of the saving operation (session.mjs); only rule 4
69
85
  // and later are written, since earlier rules add nothing beyond the scope record
70
- // (4: session tasks; 5: also the NOT_APPLICABLE coverage exemption; 6: the exemption only).
86
+ // (4: session tasks; 5: also the NOT_APPLICABLE coverage exemption; 6: the exemption only;
87
+ // 7: rule 5 plus the first evidence check; 8: rule 5 plus the evidence check, with the
88
+ // unchanged approved session tasks as sessionEvidenceExempt).
71
89
  export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules=1}={}){
72
90
  need(PRD_SELF_CHECK_RULE_VERSIONS.includes(selfCheckRules),'prd_self_check_rules_invalid');
73
91
  const reviews=path.join(specs,'.reviews');
@@ -76,11 +94,13 @@ export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules
76
94
  for(const feature of features){
77
95
  if(!feature.documents.some(doc=>doc.path==='tasks.md'))continue;
78
96
  const exempt=[...(exemptions[feature.directory]?.exempt??[])].sort();
97
+ const evidence=ruleChecksSessionEvidence(selfCheckRules)?exemptions[feature.directory]?.evidence??{}:{};
98
+ need(validTaskDigests(evidence),'prd_task_scope_record_invalid');
79
99
  const report=checkPrdDraftMechanics({draftDigest:'task-scope-record',features:[feature]},
80
100
  {scopes:{[feature.directory]:{exempt}}});
81
101
  const enforced=!report.findings.some(item=>SCOPE_CODES.has(item.code));
82
102
  const relative=recordPath(feature.directory),bytes=JSON.stringify({version:1,enforced,exempt,
83
- ...(recordedRule(selfCheckRules)?{selfCheckRules}:{})})+'\n';
103
+ ...(recordedRule(selfCheckRules)?{selfCheckRules}:{}),...(Object.keys(evidence).length?{sessionEvidenceExempt:evidence}:{})})+'\n';
84
104
  const prior=readPrdSessionFile(specs,relative);
85
105
  if(prior!==bytes)replaceSessionFile(specs,relative,prior,bytes);
86
106
  }
@@ -88,7 +108,7 @@ export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules
88
108
 
89
109
  // The checkPrdDraftMechanics options a re-check of saved features must use.
90
110
  export function prdTaskScopeOptions(specs,directories){
91
- const scopes={},sessionTasks=[],inapplicableAcceptance=[];
111
+ const scopes={},sessionTasks=[],inapplicableAcceptance=[],sessionEvidence=[],firstSessionEvidence=[],sessionEvidenceExempt={};
92
112
  for(const directory of typeof directories==='string'?[directories]:directories){
93
113
  const raw=readPrdSessionFile(specs,recordPath(directory));
94
114
  if(raw===null)continue;
@@ -97,7 +117,12 @@ export function prdTaskScopeOptions(specs,directories){
97
117
  if(ruleReadsGrammar3(value.selfCheckRules))sessionTasks.push(directory);
98
118
  // Saved under rule 5 or 6: re-checks keep the NOT_APPLICABLE coverage exemption, as rule 4 keeps session tasks.
99
119
  if(ruleExemptsInapplicable(value.selfCheckRules))inapplicableAcceptance.push(directory);
120
+ // Saved under rule 8 (or the first version, rule 7): a correction cannot drop a new session task's evidence check.
121
+ if(ruleChecksSessionEvidence(value.selfCheckRules))sessionEvidence.push(directory);
122
+ if(ruleChecksFirstSessionEvidence(value.selfCheckRules))firstSessionEvidence.push(directory);
123
+ if(value.sessionEvidenceExempt)sessionEvidenceExempt[directory]=value.sessionEvidenceExempt;
100
124
  }
101
125
  return {...(Object.keys(scopes).length?{scopes}:{}),...(sessionTasks.length?{sessionTasks}:{}),
102
- ...(inapplicableAcceptance.length?{inapplicableAcceptance}:{})};
126
+ ...(inapplicableAcceptance.length?{inapplicableAcceptance}:{}),...(sessionEvidence.length?{sessionEvidence}:{}),
127
+ ...(firstSessionEvidence.length?{firstSessionEvidence}:{}),...(Object.keys(sessionEvidenceExempt).length?{sessionEvidenceExempt}:{})};
103
128
  }
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import {randomUUID,createHash} from 'node:crypto';
5
5
  import {need,digest,json} from '../cm-ai/effect-contract.mjs';
6
6
  import {canonicalFuture} from '../cm-test/source-snapshot.mjs';
7
+ import {assertResumable,checkCreatedBy,createdByRecord,executorRelease} from '../executor-version.mjs';
7
8
  export const sha=value=>createHash('sha256').update(value).digest('hex');
8
9
  export function readText(target){
9
10
  need(canonicalFuture(target)===target,'refactor_path_changed');
@@ -63,16 +64,65 @@ function checkDiscard(row,entry,lastIntent,discards,policy){
63
64
  &&(allowed.release?row.released?.source==='operator_confirmed'&&/^[a-f0-9]{64}$/.test(row.released.evidence??''):row.released===null),
64
65
  'refactor_journal_invalid');
65
66
  }
67
+ // Journal format 2 (cm-test, cm-refactor): the first line is a format row that
68
+ // records the creating release (createdBy). Its `previous` is FORMAT_SEED, not
69
+ // null, so an executor that predates it (0.21.7 and earlier) fails its own hash
70
+ // chain check (`previous===null` on the first row) while reading, before it takes
71
+ // the writer lock or writes anything. Adding only a row type or a context field
72
+ // would not stop it: old replay ignores unknown rows and extra context keys.
73
+ // A journal whose first row has previous null is format 1 and resumes unchanged.
74
+ export const JOURNAL_FORMAT_SEED='cm-records-format-2';
75
+ const FORMAT_KEYS=['type','version','createdBy','previous','hash'];
76
+ function readFormatRow(row){
77
+ // Hash already checked by the caller: a damaged but re-hashed row is a bad createdBy, not a legacy journal.
78
+ if(row.type!=='format'||row.version!==2||Object.keys(row).length!==FORMAT_KEYS.length
79
+ ||!FORMAT_KEYS.every(name=>Object.hasOwn(row,name)))checkCreatedBy(null);// throws run_created_by_invalid with its reason
80
+ return checkCreatedBy(row.createdBy);
81
+ }
82
+ // For readers that parse the journal rows themselves (driver preflight): the
83
+ // creating release of a format-2 journal, null for format 1. Never compares releases.
84
+ export function journalCreatedBy(rows){
85
+ const first=rows[0];if(!first||first.previous!==JOURNAL_FORMAT_SEED)return null;
86
+ const {hash,...body}=first;need(hash===digest(body),'refactor_journal_invalid');return readFormatRow(first);
87
+ }
88
+ // Opens an existing journal only as a plain single-link file within the size limit.
89
+ // The opened handle must be the file lstat saw, compared by exact (bigint) device and
90
+ // file id, and the path must still name it after the read, so a swap in between, or a
91
+ // link followed where O_NOFOLLOW is unavailable (Windows), is refused. The read goes to
92
+ // end of file, so a row appended after the check is still seen, and it stops with a
93
+ // refusal past the limit. O_NONBLOCK keeps a FIFO from stalling the host.
94
+ const JOURNAL_LIMIT=32*1024*1024;
95
+ function readJournalText(target){
96
+ const link=fs.lstatSync(target,{bigint:true});need(link.isFile()&&!link.isSymbolicLink(),'refactor_journal_invalid');
97
+ const same=stat=>stat.dev===link.dev&&stat.ino===link.ino;
98
+ let fd;try{fd=fs.openSync(target,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);}
99
+ catch(error){if(error.code==='ELOOP')need(false,'refactor_journal_invalid');throw error;}
100
+ try{const stat=fs.fstatSync(fd,{bigint:true});
101
+ need(stat.isFile()&&same(stat)&&stat.nlink===1n&&stat.size<=BigInt(JOURNAL_LIMIT),'refactor_journal_invalid');
102
+ const chunks=[],chunk=Buffer.alloc(64*1024);let total=0;
103
+ for(let count;(count=fs.readSync(fd,chunk,0,chunk.length,total))>0;){
104
+ total+=count;need(total<=JOURNAL_LIMIT,'refactor_journal_invalid');chunks.push(Buffer.from(chunk.subarray(0,count)));}
105
+ const after=fs.lstatSync(target,{bigint:true});need(after.isFile()&&!after.isSymbolicLink()&&same(after),'refactor_journal_invalid');
106
+ // Grown since the read ended: another writer is active, so the caller reopens.
107
+ need(after.size===BigInt(total),'refactor_reopen_required');
108
+ return Buffer.concat(chunks).toString('utf8');}finally{fs.closeSync(fd);}
109
+ }
110
+ // A journal another process created after construction: refuse with the upgrade reason when its creator is newer.
111
+ function assertForeignJournal(source){
112
+ let first=null;try{first=JSON.parse(source.split('\n',1)[0]);}catch{}
113
+ const found=first?journalCreatedBy([first]):null;if(found)assertResumable(found);
114
+ }
66
115
  export function openRefactorRecords(directory,{discardable=null}={}){
67
116
  need(canonicalFuture(directory)===directory,'refactor_archive_changed');
68
117
  const target=path.join(directory,'execution.jsonl'),lock=path.join(directory,'.writer.json');
69
- let events=[],last=null,locked=false,lastIntent=null;const effects=new Map(),discards=[];
118
+ let events=[],last=null,locked=false,lastIntent=null,createdBy=null,newCreatedBy=null;const effects=new Map(),discards=[];
70
119
  const nextAttempt=key=>discards.filter(item=>item.key===key).length+1;
71
120
  if(fs.existsSync(target)){
72
- const stat=fs.lstatSync(target);need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&stat.size<=32*1024*1024,'refactor_journal_invalid');
73
- const source=fs.readFileSync(target,'utf8');need(source.endsWith('\n'),'refactor_journal_incomplete');
121
+ const source=readJournalText(target);need(source.endsWith('\n'),'refactor_journal_incomplete');
74
122
  events=source.trimEnd().split('\n').map(line=>JSON.parse(line));
75
- for(const row of events){const {hash,...body}=row;need(hash===digest(body)&&body.previous===last,'refactor_journal_invalid');last=hash;
123
+ for(const [index,row] of events.entries()){const {hash,...body}=row;
124
+ if(index===0&&body.previous===JOURNAL_FORMAT_SEED){need(hash===digest(body),'refactor_journal_invalid');createdBy=readFormatRow(row);last=hash;continue;}
125
+ need(hash===digest(body)&&body.previous===last&&row.type!=='format','refactor_journal_invalid');last=hash;
76
126
  if(row.type==='intent'){need(!effects.has(row.key),'refactor_journal_invalid');
77
127
  // A key asked again after a discard must carry exactly the next attempt.
78
128
  const attempt=nextAttempt(row.key);
@@ -84,13 +134,19 @@ export function openRefactorRecords(directory,{discardable=null}={}){
84
134
  }
85
135
  }
86
136
  function append(body){
87
- need(locked,'refactor_lock_required');const row={...json(body,4*1024*1024),previous:last},hash=digest(row);
137
+ need(locked,'refactor_lock_required');const rows=[];let previous=last;
138
+ // The first row of every new journal, whatever writes it, is the format row (one write with it).
139
+ if(!events.length){need(newCreatedBy!==null,'refactor_lock_required');
140
+ const head={type:'format',version:2,createdBy:newCreatedBy,previous:JOURNAL_FORMAT_SEED};rows.push({...head,hash:digest(head)});previous=rows[0].hash;}
141
+ const row={...json(body,4*1024*1024),previous};rows.push({...row,hash:digest(row)});
88
142
  const fd=fs.openSync(target,fs.constants.O_WRONLY|fs.constants.O_APPEND|fs.constants.O_CREAT|fs.constants.O_NOFOLLOW,0o600);
89
- try{need(fs.fstatSync(fd).nlink===1,'refactor_journal_invalid');fs.writeFileSync(fd,JSON.stringify({...row,hash})+'\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
90
- events.push({...row,hash});last=hash;
143
+ try{need(fs.fstatSync(fd).nlink===1,'refactor_journal_invalid');fs.writeFileSync(fd,rows.map(item=>JSON.stringify(item)+'\n').join(''));fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
144
+ events.push(...rows);last=rows.at(-1).hash;if(rows.length>1)createdBy=rows[0].createdBy;
91
145
  }
92
146
  return {
93
147
  get context(){return events.find(row=>row.type==='context')?.value??null;},
148
+ // Release that created this journal; null for a format-1 (older) journal.
149
+ get createdBy(){return createdBy?{...createdBy}:null;},
94
150
  get discards(){return discards.map(row=>({...row}));},
95
151
  get recovery(){return discardSummary(effects,discards,lastIntent);},
96
152
  // True when key/requestDigest name an attempt that was discarded: its late
@@ -131,16 +187,31 @@ export function openRefactorRecords(directory,{discardable=null}={}){
131
187
  get progress(){return events.findLast(row=>row.type==='progress')?.value??null;},
132
188
  effects,
133
189
  acquire(){
134
- need(!locked,'refactor_busy');fs.mkdirSync(directory,{recursive:true,mode:0o700});
190
+ need(!locked,'refactor_busy');
191
+ // Version gate before any write (directory, lock, first row): an older executor
192
+ // never advances a newer journal, and a new journal needs a readable release.
193
+ if(createdBy)assertResumable(createdBy);
194
+ else if(!events.length){
195
+ // A journal written after construction (a long-lived host): judge its creator
196
+ // and ask for a reopen here, before the lock is written, never after it.
197
+ if(fs.existsSync(target)){assertForeignJournal(readJournalText(target));need(false,'refactor_reopen_required');}
198
+ newCreatedBy=createdByRecord(executorRelease());
199
+ }
200
+ fs.mkdirSync(directory,{recursive:true,mode:0o700});
135
201
  if(fs.existsSync(lock)){
136
202
  const old=JSON.parse(readText(lock));need(Number.isSafeInteger(old.pid)&&old.pid>0,'refactor_lock_invalid');
137
203
  try{process.kill(old.pid,0);need(false,'refactor_busy');}catch(error){if(error.code!=='ESRCH')throw error;}
138
204
  need(readText(lock)===JSON.stringify(old),'refactor_lock_changed');fs.unlinkSync(lock);
139
205
  }
140
206
  const fd=fs.openSync(lock,'wx',0o600);try{fs.writeFileSync(fd,JSON.stringify({pid:process.pid}));}finally{fs.closeSync(fd);}locked=true;
141
- // Another process may have advanced the journal between construction and lock.
142
- if(fs.existsSync(target)){const lines=fs.readFileSync(target,'utf8').trimEnd().split('\n');
143
- need(lines.length===events.length&&JSON.parse(lines.at(-1)).hash===last,'refactor_reopen_required');}
207
+ // Another process may have advanced the journal between construction and lock;
208
+ // the hash chain makes equal length and last hash mean the same format row too.
209
+ // A refused recheck gives the lock back, so a stopped caller leaves no writer file.
210
+ // A journal that appeared in the gap before the lock still gets its upgrade reason.
211
+ try{if(fs.existsSync(target)){const source=readJournalText(target);if(!events.length)assertForeignJournal(source);
212
+ const lines=source.trimEnd().split('\n');
213
+ need(lines.length===events.length&&JSON.parse(lines.at(-1)).hash===last,'refactor_reopen_required');}}
214
+ catch(error){fs.unlinkSync(lock);locked=false;throw error;}
144
215
  },
145
216
  release(){if(locked){fs.unlinkSync(lock);locked=false;}},
146
217
  initialize(value){need(!this.context,'refactor_already_started');append({type:'context',value});},
@@ -15,6 +15,7 @@ import {need,shape,json,digest} from '../cm-ai/effect-contract.mjs';
15
15
  import {METRICS_HEADER,hasMetricsHeader} from '../cm-ai/metrics-table.mjs';
16
16
  import {inside,canonicalFuture,snapshotSource} from '../cm-test/source-snapshot.mjs';
17
17
  import {openRefactorRecords,readText,replaceText,sha} from './records.mjs';
18
+ import {diagnosticReason} from '../cm-ai/diagnostic-reason.mjs';
18
19
  const nonempty=value=>typeof value==='string'&&value.trim().length>0;
19
20
  const normalizedRulebook=value=>value.replace(/\r\n?/g,'\n').split('\n').map(line=>line.trimEnd()).join('\n').replace(/^\n+|\n+$/g,'');
20
21
  const markdown=value=>'```json\n'+JSON.stringify(value,null,2)+'\n```\n';
@@ -623,7 +624,8 @@ export function createCmRefactorHost(raw,{call}){
623
624
  projectStatus();
624
625
  return status();
625
626
  }catch(error){const {reasonDetail:_,...rest}=view;view={...rest,stage:controller.signal.aborted?'cancelled':'blocked',reason:error.code??error.message,
626
- ...(typeof error.detail==='string'?{reasonDetail:error.detail.slice(0,500)}:{})};
627
+ ...(typeof error.detail==='string'?{reasonDetail:error.detail.slice(0,500)}
628
+ :diagnosticReason(error)?{reasonDetail:diagnosticReason(error).slice(0,500)}:{})};
627
629
  try{records.progressWrite(view);projectStatus();}catch{}return status();
628
630
  }finally{records.release();active=false;}
629
631
  }});
@@ -0,0 +1,81 @@
1
+ // The CM release that is executing this code, read from the workflow root this
2
+ // module was loaded from: VERSION (source tree, npm package, Codex plugin) or
3
+ // templates/cm-VERSION (Claude compatibility install). Runs record it once at
4
+ // creation as createdBy; a resume never rewrites it. It identifies who created a
5
+ // run. Whether a run can resume is still decided by its own stored formats.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {tagDiagnosticReason} from './cm-ai/diagnostic-reason.mjs';
10
+
11
+ const RELEASE=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
12
+ const ROOT=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..','..');
13
+ export const CREATED_BY_VERSION=1;
14
+ export const EXECUTOR_VERSION_UNAVAILABLE='executor_version_unavailable';
15
+ export const CREATED_BY_NEWER='run_created_by_newer_executor';
16
+ export const CREATED_BY_INVALID='run_created_by_invalid';
17
+
18
+ // Every code here carries a one-line reason the entry points may show as is.
19
+ export const EXECUTOR_REASON_CODES=new Set([EXECUTOR_VERSION_UNAVAILABLE,CREATED_BY_NEWER,CREATED_BY_INVALID]);
20
+ const REASONS={
21
+ [EXECUTOR_VERSION_UNAVAILABLE]:()=>'CM 安装缺少或损坏版本文件(VERSION 或 templates/cm-VERSION),无法确定执行器版本,不能新建或继续运行。请重新安装 CM:npx @aibyzero/cm-workflow@latest install(Claude 安装重新运行 install.sh)。',
22
+ [CREATED_BY_NEWER]:({created,current})=>`此运行由 CM ${created} 创建,当前是 ${current}。旧版本不能继续新版本开的运行,原记录未改动。请把 CM 升级到 ${created} 或更新版本(npx @aibyzero/cm-workflow@${created} install),再用原运行定义恢复。`,
23
+ [CREATED_BY_INVALID]:()=>'运行记录里的创建版本(createdBy)格式不对,不能当作旧运行继续,原记录未改动。请检查运行记录是否被手动改过;要重做就新建一个运行。'};
24
+ // Tagged so a host that folds a request failure into host_request_failed still prints the reason.
25
+ const fail=(code,detail={})=>{const error=new Error(code);error.code=code;throw tagDiagnosticReason(error,REASONS[code](detail));};
26
+ export const validRelease=value=>typeof value==='string'&&RELEASE.test(value);
27
+ export function compareReleases(a,b){
28
+ if(!validRelease(a)||!validRelease(b))fail(CREATED_BY_INVALID);
29
+ const left=a.split('.').map(BigInt),right=b.split('.').map(BigInt);
30
+ for(let i=0;i<3;i++)if(left[i]!==right[i])return left[i]>right[i]?1:-1;
31
+ return 0;
32
+ }
33
+
34
+ function readMarker(file){
35
+ let stat,text;
36
+ try{stat=fs.lstatSync(file);}catch(error){if(error.code==='ENOENT')return null;fail(EXECUTOR_VERSION_UNAVAILABLE);}
37
+ if(!stat.isFile()||stat.size>64)fail(EXECUTOR_VERSION_UNAVAILABLE);
38
+ try{text=fs.readFileSync(file,'utf8');}catch{fail(EXECUTOR_VERSION_UNAVAILABLE);}
39
+ // A Codex cachebuster (+codex.*) only names the install, never a different release.
40
+ const value=text.trim().replace(/\+[0-9A-Za-z.-]+$/,'');
41
+ if(!validRelease(value))fail(EXECUTOR_VERSION_UNAVAILABLE);
42
+ return value;
43
+ }
44
+
45
+ let cached=null;
46
+ // Missing, malformed or conflicting markers stop the caller: a run created with
47
+ // an unknown release could never be classified later.
48
+ export function executorRelease(root=ROOT){
49
+ if(root===ROOT&&cached)return cached;
50
+ const found=[readMarker(path.join(root,'VERSION')),readMarker(path.join(root,'templates','cm-VERSION'))].filter(Boolean);
51
+ if(!found.length||found.some(value=>value!==found[0]))fail(EXECUTOR_VERSION_UNAVAILABLE);
52
+ if(root===ROOT)cached=found[0];
53
+ return found[0];
54
+ }
55
+
56
+ export const createdByRecord=(release=executorRelease())=>({version:CREATED_BY_VERSION,release});
57
+
58
+ // A stored createdBy: exact shape, a stable release. Anything else is damage,
59
+ // never treated as an unversioned (legacy) run.
60
+ export function checkCreatedBy(value){
61
+ if(value===null||typeof value!=='object'||Array.isArray(value)
62
+ ||Object.keys(value).length!==2||value.version!==CREATED_BY_VERSION||!validRelease(value.release))fail(CREATED_BY_INVALID);
63
+ return value;
64
+ }
65
+
66
+ // Top-level keys of an execution store state. v1 predates createdBy; a v2 state
67
+ // without it is damage (run_created_by_invalid), never read as v1.
68
+ const STATE_KEYS=['version','identity','fingerprints','records','revision'];
69
+ export function storeStateKeys(state,extra=[]){
70
+ if(state?.version!==2)return [...STATE_KEYS,...extra];
71
+ if(!Object.hasOwn(state,'createdBy'))fail(CREATED_BY_INVALID);
72
+ checkCreatedBy(state.createdBy);
73
+ return ['version','identity','fingerprints','createdBy','records','revision',...extra];
74
+ }
75
+
76
+ // Resume guard: an older executor must not advance a run a newer one created,
77
+ // because it cannot know what that release may have written.
78
+ export function assertResumable(createdBy,current=executorRelease()){
79
+ checkCreatedBy(createdBy);
80
+ if(compareReleases(createdBy.release,current)>0)fail(CREATED_BY_NEWER,{created:createdBy.release,current});
81
+ }
@@ -0,0 +1,15 @@
1
+ // Runs scripts/cm-log-event.py with the first available Python, as the shell
2
+ // entries do: CM_PYTHON_BIN when set, otherwise python3 then python. A platform
3
+ // that exposes only `python` (python3 missing or a stub that exits 127) still logs.
4
+ import {spawnSync} from 'node:child_process';
5
+
6
+ export function spawnPythonLogWriter(args,options={}){
7
+ const candidates=process.env.CM_PYTHON_BIN?[process.env.CM_PYTHON_BIN]:['python3','python'];
8
+ let result=null;
9
+ for(const python of candidates){
10
+ result=spawnSync(python,args,options);
11
+ if(result.error?.code==='ENOENT'||result.status===127)continue;
12
+ return result;
13
+ }
14
+ return result;
15
+ }
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import {spawnSync} from 'node:child_process';
4
4
  import {fileURLToPath} from 'node:url';
5
5
  import {readStableLogRows} from './cm-ai/log-rows.mjs';
6
+ import {readFixStepTimingFiles} from './cm-fix/step-timing.mjs';
6
7
 
7
8
  const MAX_BYTES=32*1024*1024,MAX_ROWS=100000;
8
9
  const label=value=>typeof value==='string'&&value.length>0&&value.length<=128
@@ -69,15 +70,25 @@ function timingReport(rows){
69
70
  if(!groups.has(id))groups.set(id,{runId:row.run_id,workflow:row.workflow,stage:row.phase_name,protocol,start:[],complete:[]});
70
71
  groups.get(id)[row.phase].push({row,index});
71
72
  });
72
- const stages=new Map(),intervalsByRun=new Map();let incomplete=0,pauses=0,paired=0,combined=0;
73
+ const stages=new Map(),intervalsByRun=new Map(),reviews=[];let incomplete=0,pauses=0,paired=0,combined=0;
73
74
  for(const group of groups.values()){
74
75
  const {start,complete}=group;
75
- if(start.length!==1||complete.length!==1){incomplete++;continue;}
76
+ // One entry per review invocation: start = review began, complete = the reviewer's result returned.
77
+ const review=group.protocol==='cm-ai-host-operation'&&group.stage==='review_starting'
78
+ ?(()=>{const row=(start[0]??complete[0]).row;const item={runId:row.run_id,feature:row.feature,task:row.task,attempt:row.attempt,
79
+ operationId:row.operation_id,order:(start[0]??complete[0]).index,durationMs:null,outcome:complete.length===1?complete[0].row.outcome??null:null,reason:null};
80
+ reviews.push(item);return item;})():null;
81
+ if(start.length!==1||complete.length!==1){
82
+ incomplete++;
83
+ if(review)review.reason=start.length>1||complete.length>1?'duplicate_events':start.length?'end_event_missing':'start_event_missing';
84
+ continue;
85
+ }
76
86
  const first=start[0],last=complete[0],a=timestamp(first.row.at),b=timestamp(last.row.at);
77
87
  const allowed=group.protocol==='cm-ai-host-operation'?['returned','failed','aborted']:['completed','awaiting_input','blocked'];
78
88
  if(a===null||b===null||b<a||first.index>=last.index||!allowed.includes(last.row.outcome)){
79
- incomplete++;continue;
89
+ incomplete++;if(review)review.reason='pair_invalid';continue;
80
90
  }
91
+ if(review)review.durationMs=b-a;
81
92
  paired++;if(last.row.outcome==='awaiting_input')pauses++;
82
93
  const isCombined=first.row.timing_scope==='combined_host_call'||last.row.timing_scope==='combined_host_call';
83
94
  if(isCombined)combined++;
@@ -85,13 +96,22 @@ function timingReport(rows){
85
96
  if(!stages.has(id))stages.set(id,{runId:group.runId,workflow:group.workflow,stage:group.stage,durationMs:0,pairedSegments:0,combinedSegments:0,outcomes:{}});
86
97
  const stage=stages.get(id);stage.durationMs+=b-a;stage.pairedSegments++;stage.combinedSegments+=Number(isCombined);
87
98
  stage.outcomes[last.row.outcome]=(stage.outcomes[last.row.outcome]??0)+1;
88
- if(!intervalsByRun.has(group.runId))intervalsByRun.set(group.runId,[]);
89
- intervalsByRun.get(group.runId).push([a,b]);
99
+ if(!intervalsByRun.has(group.runId))intervalsByRun.set(group.runId,{workflow:group.workflow,intervals:[]});
100
+ intervalsByRun.get(group.runId).intervals.push([a,b]);
90
101
  }
102
+ const runs=[...intervalsByRun.values()],spec=runs.filter(run=>run.workflow==='cm-prd');
103
+ reviews.sort((a,b)=>a.order-b.order);const rounds=new Map();
104
+ const reviewItems=reviews.map(({order,...item})=>{const id=key([item.runId,item.feature,item.task]);
105
+ rounds.set(id,(rounds.get(id)??0)+1);return {...item,round:rounds.get(id)};});
106
+ const reviewObserved=reviewItems.filter(x=>x.durationMs!==null).length;
91
107
  return {status:paired?(incomplete||unrecognized?'partial':'observed'):'unavailable',
92
108
  pairedSegments:paired,incompleteSegments:incomplete,unrecognizedEvents:unrecognized,closedForInput:pauses,combinedSegments:combined,
93
- activeIntervalUnionMs:paired?[...intervalsByRun.values()].reduce((n,v)=>n+unionDuration(v),0):null,
109
+ activeIntervalUnionMs:paired?runs.reduce((n,v)=>n+unionDuration(v.intervals),0):null,
110
+ specActiveMs:spec.length?spec.reduce((n,v)=>n+unionDuration(v.intervals),0):null,specRuns:spec.length,
94
111
  waitingMs:null,waitingStatus:'unavailable',stages:[...stages.values()],
112
+ reviews:{status:!reviewItems.length?'unavailable':reviewObserved===reviewItems.length?'observed':'partial',
113
+ observed:reviewObserved,unavailable:reviewItems.length-reviewObserved,items:reviewItems,
114
+ scope:'Review start to the reviewer result returning; a missing end event stays unavailable and is never estimated.'},
95
115
  scope:'Only matched progress segments; overlapping stages are not additive; gaps and unpaired time are unknown.'};
96
116
  }
97
117
  function repetitionReport(rows){
@@ -113,7 +133,85 @@ function repetitionReport(rows){
113
133
  return {status:groups.size?'observed':'unavailable',groups:repeated,unrecognizedEvents:unrecognized,
114
134
  commandReexecution:'unavailable',interpretation:'Repeated recorded starts/claims only; necessity, command equality and waste are not inferred.'};
115
135
  }
116
- export function analyzeRunRows(input,{runId=null}={}){
136
+ // cm-fix step timing: rows the cm-fix driver writes after each host call has
137
+ // closed, into {specs}/.reviews/cm-fix-step-timing/{runId}.jsonl (since 2026-12-01),
138
+ // never into the run log. Per operation: the step's own time (host work: tests,
139
+ // reviews, applying answers) and the gap before it (the session preparing
140
+ // answers between driver calls, or waiting for a person).
141
+ const FIX_TOKEN=/^[a-z0-9_]{1,80}$/,FIX_RUN=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
142
+ // Exactly what the writer emits (toISOString), so impossible dates never pass.
143
+ const fixInstant=value=>typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
144
+ &&Number.isFinite(Date.parse(value))&&new Date(Date.parse(value)).toISOString()===value?Date.parse(value):null;
145
+ const fixToken=value=>value===null||typeof value==='string'&&FIX_TOKEN.test(value);
146
+ function validFixStep(row){
147
+ const start=fixInstant(row.started_at),end=fixInstant(row.ended_at);
148
+ if(row.diagnostic!==true||row.schema!==2||row.phase!=='complete'||typeof row.run_id!=='string'||!FIX_RUN.test(row.run_id)
149
+ ||typeof row.operation!=='string'||!FIX_TOKEN.test(row.operation)||!['returned','error','failed'].includes(row.outcome)
150
+ ||!fixToken(row.failure)||!fixToken(row.stage_after)||!fixToken(row.state_after)||start===null||end===null||end<start||row.duration_ms!==end-start
151
+ ||!Array.isArray(row.answered)||row.answered.length>20||row.answered.some(kind=>typeof kind!=='string'||!FIX_TOKEN.test(kind)))return null;
152
+ return {runId:row.run_id,operation:row.operation,outcome:row.outcome,start,end};
153
+ }
154
+ // One timing row as a small step, or null; used while reading, so invalid rows are never kept.
155
+ const fixStepFromRow=row=>row&&typeof row==='object'&&!Array.isArray(row)&&row.workflow==='cm-fix'&&row.event==='step_timing'?validFixStep(row):null;
156
+ // fixTiming: {steps, invalid} as read from the files (already checked), or raw {rows}.
157
+ function fixStepReport(fixTiming,runIds){
158
+ const runs=new Map();let invalid=fixTiming?.invalid??0;const unreadable=fixTiming?.unreadable??0;
159
+ const steps=[...(fixTiming?.steps??[])];
160
+ for(const row of fixTiming?.rows??[]){const step=fixStepFromRow(row);if(step)steps.push(step);else invalid++;}
161
+ for(const step of steps){
162
+ if(!runIds.has(step.runId))continue; // timing of a run not in this analysis (or never started)
163
+ if(!runs.has(step.runId))runs.set(step.runId,[]);runs.get(step.runId).push(step);
164
+ }
165
+ const operations=new Map();let stepMs=0,gapMs=0,overlaps=0;
166
+ for(const [runId,steps] of runs){
167
+ steps.sort((a,b)=>a.start-b.start);let previousEnd=null;
168
+ for(const step of steps){
169
+ const id=key([runId,step.operation]);
170
+ if(!operations.has(id))operations.set(id,{runId,operation:step.operation,stepMs:0,gapMs:0,calls:0,errors:0});
171
+ const entry=operations.get(id);entry.stepMs+=step.end-step.start;entry.calls++;entry.errors+=Number(step.outcome!=='returned');
172
+ stepMs+=step.end-step.start;
173
+ // Overlapping calls leave the gap unknown, never negative.
174
+ if(previousEnd!==null){if(step.start>=previousEnd){entry.gapMs+=step.start-previousEnd;gapMs+=step.start-previousEnd;}else overlaps++;}
175
+ previousEnd=Math.max(previousEnd??step.end,step.end);
176
+ }
177
+ }
178
+ const flawed=invalid||overlaps||unreadable;
179
+ return {status:runs.size?(flawed?'partial':'observed'):invalid||unreadable?'invalid':'unavailable',runs:runs.size,invalidRows:invalid,unreadableFiles:unreadable,
180
+ overlappingCalls:overlaps,stepMs:runs.size?stepMs:null,gapMs:runs.size?gapMs:null,operations:[...operations.values()],
181
+ scope:'Only steps run through the cm-fix driver; before the first timed step and after the last are not covered; a gap may include waiting for a person.'};
182
+ }
183
+ // Process facts recorded since 2026-11-28; older logs simply have none of them.
184
+ function processReport(rows){
185
+ const waits=[],kinds={};let approvals=0;
186
+ const returned=new Set();let reused=0;
187
+ const reopens={},causeRecords=new Set();let reopenRows=0;
188
+ for(const row of rows){
189
+ if(row.event==='spec_approval'&&row.phase==='written'){
190
+ approvals++;if(label(row.approval_kind))kinds[row.approval_kind]=(kinds[row.approval_kind]??0)+1;
191
+ if(Number.isSafeInteger(row.wait_ms)&&row.wait_ms>=0)waits.push(row.wait_ms);
192
+ }else if(row.event==='progress'&&row.phase==='complete'&&row.workflow==='cm-ai'&&row.phase_name==='checking'
193
+ &&row.outcome==='returned'&&label(row.operation_id)){
194
+ returned.add(key([row.run_id,row.operation_id]));
195
+ }else if(row.event==='check_reuse'&&row.phase==='reused'){
196
+ reused++;
197
+ }else if(row.event==='supersede'){
198
+ reopenRows++;
199
+ }else if(row.event==='supersede_cause'&&label(row.record_digest)&&row.causes&&typeof row.causes==='object'&&!Array.isArray(row.causes)){
200
+ const id=key([row.run_id,row.record_digest]);if(causeRecords.has(id))continue;causeRecords.add(id);
201
+ for(const [cause,count] of Object.entries(row.causes))
202
+ if(label(cause)&&Number.isSafeInteger(count)&&count>0)reopens[cause]=(reopens[cause]??0)+count;
203
+ }
204
+ }
205
+ waits.sort((a,b)=>a-b);
206
+ return {
207
+ approvals:{status:approvals?'observed':'unavailable',count:approvals,kinds,observedWaits:waits.length,
208
+ totalWaitMs:waits.length?waits.reduce((n,v)=>n+v,0):null,medianWaitMs:waits.length?waits[Math.floor((waits.length-1)/2)]:null,
209
+ maxWaitMs:waits.length?waits.at(-1):null},
210
+ checks:{status:returned.size||reused?'observed':'unavailable',returnedCheckCalls:returned.size,reusedBatches:reused},
211
+ reopens:{status:reopenRows?'observed':'unavailable',count:reopenRows,recordedCauses:causeRecords.size,causes:reopens},
212
+ };
213
+ }
214
+ export function analyzeRunRows(input,{runId=null,fixTiming=null}={}){
117
215
  if(!Array.isArray(input)||input.length>MAX_ROWS||runId!==null&&!label(runId))fail();
118
216
  const seen=new Map(),rows=[];let historicalRows=0,duplicates=0;
119
217
  for(const row of input){
@@ -127,26 +225,53 @@ export function analyzeRunRows(input,{runId=null}={}){
127
225
  if(runId===null||row.run_id===runId)rows.push(row);
128
226
  }
129
227
  if(runId!==null&&!rows.length)throw Object.assign(new Error('run_analysis_run_not_found'),{code:'run_analysis_run_not_found'});
130
- const usage=usageReport(rows),timing=timingReport(rows),repetitions=repetitionReport(rows);
228
+ const usage=usageReport(rows),timing=timingReport(rows),repetitions=repetitionReport(rows),process=processReport(rows),fixSteps=fixStepReport(fixTiming,new Set(rows.map(x=>x.run_id)));
131
229
  return {schemaVersion:1,source:'specs-local-log',readOnly:true,runs:[...new Set(rows.map(x=>x.run_id))],
132
230
  rows:rows.length,ignoredHistoricalRows:historicalRows,deduplicatedEvents:duplicates,
133
- usage,timing,repetitions,
231
+ usage,timing,repetitions,process,fixSteps,
134
232
  authority:'Diagnostic observations only; no acceptance, completion, deployment or permission decision.'};
135
233
  }
136
234
  export function inspectRunAnalysis({specs,runId=null}){
137
235
  let count=0;
138
236
  const rows=readStableLogRows(path.join(specs,'运行日志.jsonl'),()=>{if(++count>MAX_ROWS)fail();return true;},'run_analysis_log_unavailable',{maxBytes:MAX_BYTES});
139
- return analyzeRunRows(rows,{runId});
237
+ // Timing files are separate and optional: an unsafe or changing one is counted, never fatal.
238
+ const fixTiming=readFixStepTimingFiles(specs,runId===null?null:[runId],{toStep:fixStepFromRow,
239
+ readRows:(file,{maxBytes,select})=>readStableLogRows(file,select,'run_analysis_timing_unavailable',{maxBytes})});
240
+ return analyzeRunRows(rows,{runId,fixTiming});
140
241
  }
141
242
  export function runAnalysisLines(report){
142
243
  const lines=[`CM 运行分析:${report.runs.length} 个运行,${report.rows} 条记录(只读)`];
143
244
  const u=report.usage,s=u.summary;
144
245
  lines.push(`Token:${u.status}${s?`;已观测调用 ${s.observed_calls},缺失 ${s.unavailable_calls},未闭合 ${s.unresolved_claims},无效 ${s.invalid_calls+s.invalid_claims}`:''}`);
145
246
  if(s?.observed_calls)lines.push(`已观测 Token 小计:input ${s.input_tokens},output ${s.output_tokens};不是缺失调用的估算。`);
247
+ if(s&&!s.observed_calls&&!s.unavailable_calls&&!s.unresolved_claims&&!s.invalid_calls&&!s.invalid_claims)
248
+ lines.push('Token 说明:日志里没有模型用量记录,原因未知(可能是当前会话模式不上报用量,或还没有模型调用);不估算。');
146
249
  const t=report.timing;
147
250
  lines.push(`阶段耗时:${t.status};完整配对 ${t.pairedSegments},未配对/无效 ${t.incompleteSegments+t.unrecognizedEvents}`);
148
251
  if(t.activeIntervalUnionMs!==null)lines.push(`已观测活动区间并集:${t.activeIntervalUnionMs} ms;等待时长未知,重叠阶段不相加。`);
149
- for(const stage of t.stages)lines.push(`${stage.runId} / ${stage.stage}:${stage.durationMs} ms${stage.combinedSegments?'(含共享调用区间)':''};结束事件 ${Object.entries(stage.outcomes).map(([outcome,count])=>`${outcome}=${count}`).join(', ')}`);
252
+ const stageName=stage=>stage==='review_starting'?'审查(review_starting)':stage;
253
+ for(const stage of t.stages)lines.push(`${stage.runId} / ${stageName(stage.stage)}:${stage.durationMs} ms${stage.combinedSegments?'(含共享调用区间)':''};结束事件 ${Object.entries(stage.outcomes).map(([outcome,count])=>`${outcome}=${count}`).join(', ')}`);
254
+ const r=t.reviews;
255
+ lines.push(r.items.length?`审查耗时(审查调用从开始到结束,含失败或中断):已配对 ${r.observed} 次,不可用 ${r.unavailable} 次`:'审查耗时:未记录');
256
+ const missing={end_event_missing:'日志缺结束事件',start_event_missing:'日志缺开始事件',duplicate_events:'同一次审查有重复事件',pair_invalid:'开始与结束无法配对'};
257
+ for(const item of r.items)lines.push(`${item.runId} / ${item.task} 第 ${item.round} 次审查:`
258
+ +(item.durationMs!==null?`${item.durationMs} ms(结束事件 ${item.outcome})`:`unavailable(${missing[item.reason]},不估算)`));
259
+ if(t.specActiveMs!==null)lines.push(`规格阶段已观测活动时长:${t.specActiveMs} ms(${t.specRuns} 个规格运行)`);
260
+ const f=report.fixSteps;
261
+ if(f.status!=='unavailable'){
262
+ const min=value=>`${(value/60000).toFixed(1)} 分钟`;
263
+ lines.push(f.runs?`cm-fix 步骤耗时:${f.status};各调用耗时合计 ${min(f.stepMs)},步骤之间(会话准备答案或等人)${min(f.gapMs)}`
264
+ :`cm-fix 步骤耗时:${f.status}`);
265
+ if(f.invalidRows||f.overlappingCalls||f.unreadableFiles)lines.push(`cm-fix 计时:无效记录 ${f.invalidRows} 条,读不了的计时文件 ${f.unreadableFiles} 个,重叠调用 ${f.overlappingCalls} 次(重叠处不计间隔,耗时合计会重复计重叠部分)`);
266
+ for(const step of f.operations)lines.push(`${step.runId} / ${step.operation}:调用耗时 ${min(step.stepMs)},之前 ${min(step.gapMs)};${step.calls} 次${step.errors?`,出错或中断 ${step.errors} 次`:''}`);
267
+ if(f.runs)lines.push('只统计经 cm-fix 驾驶员执行的步骤;第一步之前、最后一步之后不在统计内。');
268
+ }
269
+ const p=report.process;
270
+ lines.push(p.approvals.count?`规格审批:${p.approvals.count} 次;已记录等待 ${p.approvals.observedWaits} 次,合计 ${p.approvals.totalWaitMs??'未知'} ms,中位 ${p.approvals.medianWaitMs??'未知'} ms,最长 ${p.approvals.maxWaitMs??'未知'} ms`
271
+ :'规格审批:未记录');
272
+ lines.push(p.checks.status==='unavailable'?'检查:未记录'
273
+ :`检查:调用正常返回 ${p.checks.returnedCheckCalls} 次(不等于命令全部执行),完成前复用 ${p.checks.reusedBatches} 批`);
274
+ lines.push(p.reopens.count?`重开:${p.reopens.count} 次;记录了原因的 ${p.reopens.recordedCauses} 次${p.reopens.recordedCauses?`,旧运行结束原因 ${Object.entries(p.reopens.causes).map(([cause,count])=>`${cause}=${count}`).join(', ')}`:''}`:'重开:未记录');
150
275
  lines.push(`重复启动/调用声明组:${report.repetitions.groups.length};未判断必要性,测试命令重复执行次数未知。`);
151
276
  for(const group of report.repetitions.groups)lines.push(`${group.runId} / ${group.kind} / ${group.identity.join(' / ')}:${group.count} 次`);
152
277
  lines.push('分析不改变验收、检查、重试或完成门禁。');return lines;
@@ -83,6 +83,12 @@ and may not replace envelope fields.
83
83
  | each workflow run | `run_start` / `run_done` | start once; terminal result in detail/data |
84
84
  | PRD and approval | `spec_lifecycle` | `generated`, `awaiting_review`, `approved`, `changed` |
85
85
  | PRD phase timing | `progress` | paired `start`/`complete`; operation_id, phase_name, segment |
86
+ | spec approval written (JS admission) | `spec_approval` | `written`; diagnostic row on the cm-prd run whose awaiting_review matches the publication second; wait_ms, approval_kind |
87
+ | completion reused reviewed checks | `check_reuse` | `reused`; diagnostic row; feature, task, attempt, check_count |
88
+ | restart causes | `supersede_cause` | diagnostic row beside `supersede`; record_digest, causes (state/code or qa/RESULT → count, at most 16) |
89
+
90
+ A row with data `diagnostic: true` must name its run with `--run-id`; it never
91
+ opens, ends or re-points a run, and default run selection ignores it.
86
92
  | N1–N8 | existing node/task/review/degrade/pause/resume/decision/error/qa/done events | preserve existing semantics |
87
93
  | long external, desktop, or browser step | `progress` | `start`, `checkpoint`, `complete`; operation id and observable milestone |
88
94
  | any QA invocation | `test_run` | `start`, `case_start`, `case_complete`, `case_blocked`, `complete`; case counts, result, report |
package/runtime/review.md CHANGED
@@ -55,6 +55,7 @@ New cm-ai runs additionally bind `specification` into the baseline, developer re
55
55
  0. Project declares `roles.reviewer.adapter: claude-cli` (including `claude-only`): go straight to item 3; do not try Codex first. This governs the compatibility flow; the ordinary JS host reviews with the current tool unless `--review-runtime` is passed (see `skills/cm-ai/references/js-host.md`).
56
56
  1. `codex-subagent`: spawn a fresh reviewer/subagent with the runtime's no-history/fresh-context option (for example `fork_turns: none`) and provide only the review package. Ask for concrete failure scenarios, ordered by severity, and require an explicit zero-findings result when applicable.
57
57
  2. `codex-cli`: if subagents are unavailable, run `codex review` only when the task changes are isolated from unrelated dirty work (clean pre-task tree or isolated worktree/commit).
58
+ For `codex exec` reviews, pass `-C {the root under review}`; when that root (often a separate specs directory) is not a git repository, add `--skip-git-repo-check`, otherwise Codex refuses to start (dogfood 2026-11-30: PRD review in a non-git specs root).
58
59
  3. `claude-cli`: when selected by the project declaration, the protected host must actually spawn a fresh Claude reviewer and recover its registered V3 receipt before recording `independent: true`. A two-provider declaration requires coder and reviewer on different providers; a single-provider declaration uses a fresh context on that provider.
59
60
  4. The selected independent path is unavailable: pause new implementation or leave existing work pending review. `self-degraded` is diagnostic only; it cannot authorize N5 or successful completion, even if its legacy verdict says `approved`.
60
61
 
@@ -99,7 +100,7 @@ or a mismatched model must not be converted into a passing diagnostic.
99
100
 
100
101
  Review correctness, edge cases, error handling, security, performance regressions, contract compliance, and the tests themselves. Reject placebo tests, implementation-detail assertions that miss behavior, and tests whose inputs share the same hidden premise as the implementation. The `scope` list must include every project-relative path in the handoff's `changed_files`; the review body must contain the actual findings or an explicit zero-findings conclusion.
101
102
 
102
- Only report findings with a plausible input/state and an incorrect outcome. Style-only preferences do not block completion unless they conceal a defect or violate an explicit project rule.
103
+ Only report blocking findings (P0/P1/P2) with a concrete reachable input/state and an incorrect outcome. Style-only preferences, naming/wording/doc polish, out-of-scope redesign requests, and speculative edge cases without a reachable failure path must be downgraded to P3 (record-only) and never block completion unless they conceal a real defect or violate an explicit project rule.
103
104
 
104
105
  ## Rounds and disposition
105
106