@aibyzero/cm-workflow 0.16.3 → 0.16.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +55 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/next-steps.md +14 -24
  9. package/docs/runtime-failover.md +1 -1
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  12. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
  15. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  16. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  17. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  18. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  19. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  21. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  22. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  24. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  25. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  27. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  28. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  29. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  30. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  31. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  32. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  34. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  38. package/runtime/js/cm-ai/host-session.mjs +20 -5
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  43. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  44. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  45. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  46. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  47. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  48. package/runtime/js/cm-ai/review-package.mjs +427 -31
  49. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  50. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  52. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  53. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  54. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  56. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  57. package/runtime/js/cm-fix/execution.mjs +109 -25
  58. package/runtime/js/cm-fix/host-review.mjs +7 -3
  59. package/runtime/js/cm-fix/host.mjs +3 -1
  60. package/runtime/js/cm-fix/progress.mjs +1 -0
  61. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  62. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  63. package/runtime/js/cm-prd/analysis.mjs +2 -1
  64. package/runtime/js/cm-prd/change.mjs +28 -10
  65. package/runtime/js/cm-prd/draft.mjs +5 -2
  66. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  67. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  68. package/runtime/js/cm-prd/self-check.mjs +6 -3
  69. package/runtime/js/cm-prd/summary.mjs +6 -2
  70. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  71. package/runtime/js/spec-task-line.mjs +117 -0
  72. package/runtime/js/specs-status.mjs +14 -3
  73. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  74. package/scripts/cm-ai-admission.mjs +19 -10
  75. package/scripts/cm-ai-admission.test.mjs +65 -1
  76. package/scripts/cm-ai-batch-drive.mjs +93 -21
  77. package/scripts/cm-ai-batch-drive.test.mjs +171 -3
  78. package/scripts/cm-ai-batch-host.mjs +37 -13
  79. package/scripts/cm-ai-batch-host.test.mjs +26 -0
  80. package/scripts/cm-ai-batch-run.mjs +33 -10
  81. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  82. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  84. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  85. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  86. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  87. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  88. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  89. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  90. package/scripts/cm-ai-drive.mjs +480 -47
  91. package/scripts/cm-ai-drive.test.mjs +247 -10
  92. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  93. package/scripts/cm-ai-host.mjs +89 -25
  94. package/scripts/cm-ai-host.test.mjs +274 -12
  95. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  96. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  97. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  98. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  99. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  100. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  101. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  102. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  103. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  104. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  105. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  106. package/scripts/cm-ai-run.mjs +160 -60
  107. package/scripts/cm-ai-run.test.mjs +4 -3
  108. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  109. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  110. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  111. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  112. package/scripts/cm-ai-supersede.test.mjs +571 -17
  113. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  114. package/scripts/cm-capability-gate.test.mjs +21 -2
  115. package/scripts/cm-check-drive.mjs +4 -3
  116. package/scripts/cm-check-drive.test.mjs +17 -1
  117. package/scripts/cm-check-entry.mjs +13 -2
  118. package/scripts/cm-check-host.mjs +2 -2
  119. package/scripts/cm-check-host.test.mjs +57 -1
  120. package/scripts/cm-check-runtime.sh +16 -7
  121. package/scripts/cm-claude-developer-worker.test.mjs +43 -2
  122. package/scripts/cm-claude-probe.test.mjs +9 -1
  123. package/scripts/cm-claude-review-stream.test.mjs +68 -0
  124. package/scripts/cm-claude-worker.test.mjs +11 -4
  125. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  126. package/scripts/cm-failover.mjs +8 -8
  127. package/scripts/cm-fix-abandon.test.mjs +123 -5
  128. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  129. package/scripts/cm-fix-drive.mjs +45 -13
  130. package/scripts/cm-fix-drive.test.mjs +36 -1
  131. package/scripts/cm-fix-host.mjs +9 -6
  132. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  133. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  134. package/scripts/cm-host-check.test.mjs +6 -3
  135. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  136. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  137. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  138. package/scripts/cm-log-event.mjs +17 -0
  139. package/scripts/cm-log-event.test.mjs +31 -0
  140. package/scripts/cm-prd-completion.test.mjs +105 -2
  141. package/scripts/cm-prd-draft.test.mjs +14 -0
  142. package/scripts/cm-prd-drive.mjs +13 -7
  143. package/scripts/cm-prd-drive.test.mjs +10 -0
  144. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  145. package/scripts/cm-prd-review-gate.mjs +126 -81
  146. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  147. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  148. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  149. package/scripts/cm-prd-self-check.test.mjs +6 -0
  150. package/scripts/cm-prd-summary.test.mjs +40 -0
  151. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  152. package/scripts/cm-review-inventory.test.mjs +253 -1
  153. package/scripts/cm-spec-manifest.mjs +28 -10
  154. package/scripts/cm-spec-manifest.test.mjs +8 -4
  155. package/scripts/cm-spec-task-line.test.mjs +138 -0
  156. package/scripts/cm-specs-status.test.mjs +31 -1
  157. package/scripts/cm-task-gate.mjs +18 -10
  158. package/scripts/cm-task-gate.py +1 -1
  159. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  160. package/scripts/fixtures/claude-review-process.mjs +1 -0
  161. package/scripts/fixtures/process-cleanup.mjs +99 -0
  162. package/scripts/test-cm-log-event.py +2 -0
  163. package/scripts/test-cm-prd-review-gate.py +2 -1
  164. package/scripts/test-npm-install.py +1 -1
  165. package/scripts/test-scan-public-safety.py +1 -1
  166. package/scripts/test-shell-compat.sh +67 -0
  167. package/scripts/test-spec-manifest.py +16 -8
  168. package/scripts/test-task-gate.py +2 -2
  169. package/scripts/test-workflow-config.py +1 -0
  170. package/scripts/validate-public-repo.py +1 -0
  171. package/skills/cm-ai/references/N1-init.md +1 -1
  172. package/skills/cm-ai/references/js-host.md +264 -40
  173. package/skills/cm-check/SKILL.md +6 -1
  174. package/skills/cm-check/references/js-host.md +3 -3
  175. package/skills/cm-fix/references/js-host.md +22 -1
  176. package/skills/cm-prd/references/js-change-recovery.md +30 -0
  177. package/skills/cm-prd/references/js-host.md +6 -0
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import {need,shape,json,digest} from '../cm-ai/effect-contract.mjs';
4
4
  import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
5
+ import {needPrd,prdDraftJson} from './validation-reason.mjs';
5
6
  export function prdFeatureInventory(specs){
6
7
  return fs.readdirSync(specs).filter(name=>/^\d+\./.test(name)).sort();
7
8
  }
@@ -37,7 +38,7 @@ export function inspectPrdDesignDraft(raw,{nextIndex}){
37
38
  writeAuthorized:false,completionAuthorized:false});
38
39
  }
39
40
  export function inspectPrdDraft(raw,{nextIndex,generateCases,userCasesProvided}){
40
- const reply=json(raw,64*1024);shape(reply,['status','summary','features']);
41
+ const reply=prdDraftJson(raw);shape(reply,['status','summary','features']);
41
42
  need(reply.status==='draft'&&typeof reply.summary==='string'&&reply.summary.trim()
42
43
  &&Array.isArray(reply.features)&&reply.features.length>0,'prd_draft_invalid');
43
44
  const seen=new Set(),features=[];let userCases=0;
@@ -55,7 +56,9 @@ export function inspectPrdDraft(raw,{nextIndex,generateCases,userCasesProvided})
55
56
  need(['requirements.md','design.md','tasks.md'].every(file=>files.has(file)),'prd_draft_triad_missing');
56
57
  if(files.has('test-cases.json')){
57
58
  const cases=JSON.parse(files.get('test-cases.json'));
58
- need(validateTestCases(cases).length===0&&cases.feature===feature.name&&feature.testCasesReason===null,'prd_draft_cases_invalid');
59
+ needPrd(feature.testCasesReason===null,'prd_draft_cases_invalid',
60
+ {field:`features[${index}].testCasesReason`,expected:'testCasesReason must be null when test cases are present'});
61
+ need(validateTestCases(cases).length===0&&cases.feature===feature.name,'prd_draft_cases_invalid');
59
62
  need(generateCases||cases.cases.every(item=>item.origin!=='generated'),'prd_generated_cases_disabled');
60
63
  userCases+=cases.cases.filter(item=>item.origin==='user').length;
61
64
  }else need(['no_observable_behavior','generation_disabled'].includes(feature.testCasesReason)
@@ -9,6 +9,7 @@ import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
9
9
  import {inspectPrdFindings} from './review-findings.mjs';
10
10
  import {inspectPrdSplitDesign} from './split-design.mjs';
11
11
  import {need,json,digest} from '../cm-ai/effect-contract.mjs';
12
+ import {needPrd} from './validation-reason.mjs';
12
13
  const sha=text=>createHash('sha256').update(text).digest('hex');
13
14
  function sections(text,pattern){
14
15
  const parts=text.split(/(?=^##\s+)/m);
@@ -55,12 +56,18 @@ export function preparePrdReview({specs,draft,stage,feature}){
55
56
  }
56
57
  const files=new Map(target.documents.map(document=>[document.path,document.content]));
57
58
  const requirements=files.get('requirements.md'),design=files.get('design.md');
58
- if(stage==='split')need(sections(design,/^##\s+(方案摘要|概述|功能模块设计|架构.*|summary|design summary|overview|architecture.*)\s*$/i),
59
- 'prd_review_design_summary_missing');
59
+ if(stage==='split')needPrd(sections(design,/^##\s+(方案摘要|概述|功能模块设计|架构.*|summary|design summary|overview|architecture.*)\s*$/i),
60
+ 'prd_review_design_summary_missing',{field:`${feature}/design.md`,
61
+ expected:'Required split summary ## heading: ## 方案摘要, ## 概述, ## 功能模块设计, ## 架构…, ## Summary, ## Design Summary, ## Overview, or ## Architecture…'});
60
62
  const content=stage==='design'?{requirements,design}:{
61
63
  requirementsFunctions:sections(requirements,/^##\s+(功能需求|Functional requirements)\s*$/i),
62
64
  tasks:files.get('tasks.md'),designSummary:sections(design,/^##\s+.*(方案摘要|概述|架构|功能模块|技术|接口|数据|波及|安全|summary|overview|architecture|decision|contract|data|impact|security)/i)};
63
- need(Object.values(content).every(value=>typeof value==='string'&&value.trim()),'prd_review_sections_missing');
65
+ const missing=Object.entries(content).find(([,value])=>typeof value!=='string'||!value.trim());
66
+ const field=missing?.[0]==='requirementsFunctions'?'requirements.md':missing?.[0]==='designSummary'?'design.md':missing?.[0];
67
+ needPrd(!missing,'prd_review_sections_missing',{field:`${feature}/${field}`,
68
+ expected:field==='requirements.md'?'Required ## heading: ## 功能需求 or ## Functional requirements':
69
+ field==='design.md'?'Required ## heading containing 方案摘要, 概述, 架构, 功能模块, 技术, 接口, 数据, 波及, 安全, summary, overview, architecture, decision, contract, data, impact, or security':
70
+ 'Non-empty section content'});
64
71
  const revision=stage==='split'?readPrdSelfCheckRevision(specs,feature):null;
65
72
  const revised=revision?.features.find(f=>f.directory===feature);
66
73
  const reviewPackage=json({workflow:'cm-prd',stage,feature,draftDigest:draft.draftDigest,content,
@@ -6,6 +6,7 @@ import {inspectPrdReview} from '../../../scripts/cm-prd-review-gate.mjs';
6
6
  import {writeReviewEvidence} from '../cm-ai/review-evidence-file.mjs';
7
7
  import {reviewResultForPaths} from '../cm-ai/review-runner.mjs';
8
8
  import {need,shape,json,digest,id} from '../cm-ai/effect-contract.mjs';
9
+ import {needPrd} from './validation-reason.mjs';
9
10
 
10
11
  export function publishPrdReview({specs,reviewPackage,packageDigest,authorContextId,response,inspectOnly=false,pendingSplit=null}){
11
12
  if(!inspectOnly)assertPrdBatchActive(specs,[reviewPackage.feature]);
@@ -36,8 +37,9 @@ export function publishPrdReview({specs,reviewPackage,packageDigest,authorContex
36
37
  &&!/[\r\n\v\f\x1c-\x1e\x85\u2028\u2029\0]/.test(response.degradedReason):
37
38
  ['codex-subagent','codex-cli'].includes(response.reviewer)&&response.independent===true&&response.contextId!==authorContextId,
38
39
  'prd_review_independence_invalid');
39
- need(typeof response.at==='string'&&Number.isFinite(Date.parse(response.at))
40
- &&new Date(response.at).toISOString()===response.at,'prd_review_timestamp_invalid');
40
+ needPrd(typeof response.at==='string'&&Number.isFinite(Date.parse(response.at))
41
+ &&new Date(response.at).toISOString()===response.at,'prd_review_timestamp_invalid',
42
+ {field:'response.at',expected:'new Date().toISOString() form, e.g. 2026-09-08T00:00:00.000Z'});
41
43
  const files=stage==='design'?['requirements.md','design.md']:['requirements.md','design.md','tasks.md'];
42
44
  const examinedPaths=files.map(file=>`${reviewPackage.feature}/${file}`).sort();
43
45
  const result=reviewResultForPaths(response.result,{packageDigest},examinedPaths);
@@ -26,7 +26,8 @@ export function inspectPrdContextCheck(raw,draft){
26
26
  return json({...report,status:failed?'failed':'host_reported_passed',independentReview:false,completionAuthorized:false});
27
27
  }
28
28
 
29
- // Examples are not declarations. Leave the original N1 parser behavior unchanged.
29
+ // Examples are not declarations. Task lines go through the shared grammar,
30
+ // which already skips fences; this blanks fenced acceptance examples.
30
31
  function outsideFences(source){
31
32
  let fence=null;return source.split(/\r?\n/).map(line=>{
32
33
  const match=line.match(/^\s*(`{3,}|~{3,})/);
@@ -42,8 +43,10 @@ export function checkPrdDraftMechanics(draft,{change=false}={}){
42
43
  const findings=[],features=[];
43
44
  for(const feature of draft.features){
44
45
  const files=new Map(feature.documents.map(document=>[document.path,document.content]));
45
- const add=code=>findings.push({feature:feature.directory,code});
46
- const parsed=parseFeatureTaskText(outsideFences(files.get('tasks.md')));
46
+ const add=code=>findings.push({feature:feature.directory,code,
47
+ ...(code==='dependencies_invalid'?{reason:{field:`${feature.directory}/tasks.md`,
48
+ expected:'One line per task; comma-separated prerequisites, e.g. - T-003 依赖 T-001, T-002'}}:{})});
49
+ const parsed=parseFeatureTaskText(files.get('tasks.md'));
47
50
  const acIds=declaredAcceptanceIds(outsideFences(files.get('requirements.md')));
48
51
  if(acIds.size===0)add('acceptance_missing');
49
52
  let taskIds=new Set();
@@ -6,7 +6,7 @@ import {inspectPrdSplitDesign} from './split-design.mjs';
6
6
  import path from 'node:path';
7
7
  import {createHash} from 'node:crypto';
8
8
  import {TextDecoder} from 'node:util';
9
- import {writeSpecsStatus} from '../specs-status.mjs';
9
+ import {readSpecsStatus,writeSpecsStatus} from '../specs-status.mjs';
10
10
  import {buildManifest} from '../../../scripts/cm-spec-manifest.mjs';
11
11
  import {inspectPrdReview} from '../../../scripts/cm-prd-review-gate.mjs';
12
12
  import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
@@ -125,8 +125,12 @@ export function publishPrdAwaitingReview({specs,summary,writeEnabled,recover=fal
125
125
  }
126
126
  }
127
127
  need(digest(before)===summary.evidenceDigest,'prd_summary_inputs_changed');
128
+ const prior=readSpecsStatus(specs);
128
129
  const status={status:'awaiting_review',summaryDigest:summary.summaryDigest,at:new Date().toISOString(),features:before.features.map(item=>item.directory),
129
- specFiles:before.specFiles,testCases:before.specFiles.filter(item=>item.path.endsWith('/test-cases.json')),approval:null};
130
+ specFiles:before.specFiles,testCases:before.specFiles.filter(item=>item.path.endsWith('/test-cases.json')),approval:null,
131
+ ...(prior.kind==='valid'&&Object.hasOwn(prior.value,'revisionDigest')?{revisionDigest:prior.value.revisionDigest}:{}),
132
+ // A first publication has no earlier approval to reinterpret: bind grammar 2.
133
+ ...(prior.kind==='missing'||prior.kind==='valid'&&prior.value.taskGrammar===2?{taskGrammar:2}:{})};
130
134
  const bytes=Buffer.from(JSON.stringify(status)+'\n'),target=path.join(specs,'.cm-specs-status');
131
135
  try{
132
136
  writeSpecsStatus(specs,status,{beforeRename:()=>{
@@ -0,0 +1,20 @@
1
+ // Add operator guidance to existing fail-closed codes without changing the gate.
2
+ import {need,json} from '../cm-ai/effect-contract.mjs';
3
+ import {tagDiagnosticReason} from '../cm-ai/diagnostic-reason.mjs';
4
+
5
+ export function needPrd(ok,code,reason){
6
+ try{need(ok,code);}catch(error){throw tagDiagnosticReason(error,reason);}
7
+ }
8
+
9
+ export function prdDraftJson(raw){
10
+ try{return json(raw,64*1024);}catch(error){
11
+ if(error.code==='limit_exceeded'){
12
+ // The input is a parsed host reply. Do not include its contents in diagnostics.
13
+ let actualBytes=null;
14
+ try{actualBytes=Buffer.byteLength(JSON.stringify(raw));}catch{/* original error wins */}
15
+ tagDiagnosticReason(error,{field:'draft',expected:'one submission must be <= 65536 bytes (64 KiB)',
16
+ limitBytes:65536,actualBytes});
17
+ }
18
+ throw error;
19
+ }
20
+ }
@@ -0,0 +1,117 @@
1
+ // The one tasks.md declaration grammar. Admission, the cm-prd checks, N5
2
+ // mark-done and the approval manifest's runtime-mark normalization all read
3
+ // task lines through this file, so a task one of them accepts is a task for all.
4
+ //
5
+ // A declaration is a list item with a checkbox at any indentation, an optional
6
+ // `~~` strike, a T-id and then an ASCII colon, a full-width colon or whitespace:
7
+ // - [ ] T-003: 描述 - [x] T-003 描述 - [ ] T-003:描述 ····- [ ] T-003 - 描述
8
+ // The full-width colon is accepted rather than rejected: Chinese input methods
9
+ // produce it, cm-failover already accepted it, and rejecting it would force a
10
+ // spec revision for punctuation alone. Lines inside ``` / ~~~ fences (the
11
+ // manifest's original fence rule) are examples, never declarations.
12
+ //
13
+ // The grammar is versioned by the approval that bound the bytes: approvals
14
+ // written by this version record taskGrammar 2 in .cm-specs-status. Approvals
15
+ // recorded earlier keep the exact pre-grammar parse (grammar 1) so an existing
16
+ // approved tasks.md never changes meaning, e.g. an unfenced `- [ ] T-001:例`
17
+ // beside the real `- [ ] T-001:` stays prose instead of becoming a duplicate.
18
+ // cm-prd drafts and new approvals always use grammar 2.
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ export const TASK_GRAMMAR=2;
22
+ export const LEGACY_TASK_GRAMMAR=1;
23
+ const LEGACY_DECLARATION=/^((\s*-\s*)\[([ xX])\]\s+(?:~~)?(T-[A-Za-z0-9][A-Za-z0-9._-]*))(?=[:\s])[:\s]*(.*)$/;
24
+ const DECLARATION=/^(\s*-\s*)\[([ xX])\]\s+(?:~~)?(T-[A-Za-z0-9][A-Za-z0-9._-]*)(?=[::\s])/u;
25
+ const FENCE=/^[ ]{0,3}(`{3,}|~{3,})/;
26
+
27
+ export function matchTaskDeclaration(line){
28
+ const match=DECLARATION.exec(line);
29
+ if(!match)return null;
30
+ return {id:match[3],completed:match[2]!==' ',markOffset:match[1].length+1,
31
+ rest:line.slice(match[0].length)};
32
+ }
33
+
34
+ // Physical lines (\r\n, \r or \n) with their character offsets. Fenced lines are
35
+ // reported but flagged, so callers keep exact line numbers for diagnostics.
36
+ export function specLines(text){
37
+ const lines=[],parts=text.split(/(\r\n|\r|\n)/);let fence=null,width=0,start=0;
38
+ for(let index=0;index*2<parts.length;index++){
39
+ const body=parts[index*2],opener=FENCE.exec(body);let fenced=true;
40
+ if(fence!==null){
41
+ if(opener&&opener[1][0]===fence&&opener[1].length>=width&&/^[\t\n\v\f\r ]*$/.test(body.slice(opener[0].length))){fence=null;width=0;}
42
+ }else if(opener){fence=opener[1][0];width=opener[1].length;}
43
+ else fenced=false;
44
+ lines.push({index,start,body,fenced});
45
+ start+=body.length+(parts[index*2+1]??'').length;
46
+ }
47
+ return lines;
48
+ }
49
+
50
+ // Lines of tasks.md with their declaration (or null) under the given grammar.
51
+ // `description` is the text after the id with the grammar's own separator stripped.
52
+ export function taskLines(text,{grammar=TASK_GRAMMAR}={}){
53
+ if(grammar===TASK_GRAMMAR)return specLines(text).map(line=>{
54
+ const declaration=line.fenced?null:matchTaskDeclaration(line.body);
55
+ return {...line,declaration:declaration&&{...declaration,description:declaration.rest.replace(/^[::\s]+/u,'')}};
56
+ });
57
+ if(grammar!==LEGACY_TASK_GRAMMAR)throw Object.assign(new Error('task_grammar_invalid'),{code:'task_grammar_invalid'});
58
+ // Exactly the pre-grammar admission parser: \r?\n lines, no fence handling.
59
+ const lines=[],parts=text.split(/(\r?\n)/);let start=0;
60
+ for(let index=0;index*2<parts.length;index++){
61
+ const body=parts[index*2],match=LEGACY_DECLARATION.exec(body);
62
+ lines.push({index,start,body,fenced:false,declaration:match&&{id:match[4],completed:match[3]!==' ',
63
+ markOffset:match[2].length+1,rest:body.slice(match[1].length),description:match[5]}});
64
+ start+=body.length+(parts[index*2+1]??'').length;
65
+ }
66
+ return lines;
67
+ }
68
+
69
+ export function taskDeclarations(text,{grammar=TASK_GRAMMAR}={}){
70
+ return taskLines(text,{grammar}).flatMap(line=>line.declaration?[{...line,...line.declaration}]:[]);
71
+ }
72
+
73
+ // The grammar the current approval bound; anything but an approval written with
74
+ // taskGrammar 2 (older approvals, awaiting review, missing or unreadable status)
75
+ // is read with the pre-grammar parser, which is what approved those bytes.
76
+ export function approvedTaskGrammar(specsDir){
77
+ try{
78
+ const status=JSON.parse(fs.readFileSync(path.join(specsDir,'.cm-specs-status'),'utf8'));
79
+ return status?.status==='approved'&&status.taskGrammar===TASK_GRAMMAR?TASK_GRAMMAR:LEGACY_TASK_GRAMMAR;
80
+ }catch{return LEGACY_TASK_GRAMMAR;}
81
+ }
82
+
83
+ // Runtime completion marks are the only task-line bytes that change after approval.
84
+ export function resetTaskMarks(text){
85
+ let result='',cursor=0;
86
+ for(const item of taskDeclarations(text)){
87
+ if(!item.completed)continue;
88
+ const offset=item.start+item.markOffset;
89
+ result+=text.slice(cursor,offset)+' ';cursor=offset+1;
90
+ }
91
+ return result+text.slice(cursor);
92
+ }
93
+
94
+ // Byte-level twin of resetTaskMarks for approval digests. Invalid UTF-8 stays
95
+ // byte-exact: each line is decoded only to find the ASCII checkbox position.
96
+ export function resetTaskMarkBytes(bytes){
97
+ const out=Buffer.from(bytes),decoder=new TextDecoder('utf-8',{ignoreBOM:true});
98
+ let fence=null,width=0;
99
+ for(let start=0;start<bytes.length;){
100
+ let end=start;while(end<bytes.length&&bytes[end]!==0x0a&&bytes[end]!==0x0d)end++;
101
+ const line=decoder.decode(bytes.subarray(start,end));
102
+ const opener=FENCE.exec(line);
103
+ if(fence!==null){
104
+ if(opener&&opener[1][0]===fence&&opener[1].length>=width&&/^[\t\n\v\f\r ]*$/.test(line.slice(opener[0].length))){fence=null;width=0;}
105
+ }else if(opener){fence=opener[1][0];width=opener[1].length;}
106
+ else{
107
+ const declaration=matchTaskDeclaration(line);
108
+ if(declaration?.completed){
109
+ const offset=start+Buffer.byteLength(line.slice(0,declaration.markOffset));
110
+ if(out[offset-1]!==0x5b||(out[offset]|0x20)!==0x78)throw new Error('task checkbox byte offset mismatch');
111
+ out[offset]=0x20;
112
+ }
113
+ }
114
+ start=end+(bytes[end]===0x0d&&bytes[end+1]===0x0a?2:1);
115
+ }
116
+ return out;
117
+ }
@@ -3,9 +3,10 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {randomUUID} from 'node:crypto';
5
5
 
6
- const fields=['status','summaryDigest','at','features','specFiles','testCases','approval'];
6
+ const fields=['status','summaryDigest','at','features','specFiles','testCases','approval','revisionDigest','taskGrammar'];
7
7
  const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
8
8
  const hex=value=>typeof value==='string'&&/^[a-fA-F0-9]{64}$/.test(value);
9
+ const revisionHex=value=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);
9
10
  const iso=value=>typeof value==='string'&&/^\d{4}-\d\d-\d\dT/.test(value)&&Number.isFinite(Date.parse(value));
10
11
  const need=condition=>{if(!condition)throw new Error('spec_status_invalid');};
11
12
 
@@ -20,6 +21,7 @@ export function readSpecsStatus(specsDir){
20
21
  need(relative!==''&&relative!=='..'&&!relative.startsWith(`..${path.sep}`)&&!path.isAbsolute(relative));
21
22
  const source=JSON.parse(fs.readFileSync(real,'utf8'));
22
23
  need(record(source)&&['approved','awaiting_review'].includes(source.status));
24
+ if(Object.hasOwn(source,'revisionDigest'))need(revisionHex(source.revisionDigest));
23
25
  // Keep optional fields absent: admission distinguishes legacy omissions.
24
26
  const value=Object.fromEntries(fields.filter(key=>Object.hasOwn(source,key)).map(key=>[key,source[key]]));
25
27
  if(record(value.approval))value.approval=Object.fromEntries(['response','at']
@@ -32,6 +34,10 @@ export function writeSpecsStatus(specsDir,value,{beforeRename=()=>{}}={}){
32
34
  need(record(value)&&['approved','awaiting_review'].includes(value.status));
33
35
  const summaryDigest=value.summaryDigest===undefined?null:value.summaryDigest;
34
36
  need(summaryDigest===null||hex(summaryDigest));
37
+ if(Object.hasOwn(value,'revisionDigest'))need(revisionHex(value.revisionDigest));
38
+ // The grammar the last approval bound (spec-task-line.mjs). An awaiting_review
39
+ // status only carries it forward; parsing honours it only once approved.
40
+ if(Object.hasOwn(value,'taskGrammar'))need(value.taskGrammar===2);
35
41
  need(iso(value.at)&&Array.isArray(value.features)&&value.features.length>0
36
42
  &&value.features.every(name=>typeof name==='string'&&/^\d+\.[^/\\]+$/.test(name))
37
43
  &&new Set(value.features).size===value.features.length);
@@ -49,14 +55,19 @@ export function writeSpecsStatus(specsDir,value,{beforeRename=()=>{}}={}){
49
55
  &&typeof approval.response==='string'&&approval.response.trim()!==''&&iso(approval.at)));
50
56
  const canonical={status:value.status,summaryDigest,at:value.at,features:[...value.features],
51
57
  specFiles:manifest(value.specFiles),testCases:manifest(value.testCases),
52
- approval:approval===null?null:{response:approval.response,at:approval.at}};
58
+ approval:approval===null?null:{response:approval.response,at:approval.at},
59
+ ...(Object.hasOwn(value,'revisionDigest')?{revisionDigest:value.revisionDigest}:{}),
60
+ ...(Object.hasOwn(value,'taskGrammar')?{taskGrammar:value.taskGrammar}:{})};
53
61
  const bytes=Buffer.from(JSON.stringify(canonical)+'\n'),target=path.join(specsDir,'.cm-specs-status');
54
62
  const temporary=path.join(specsDir,`.cm-specs-status-${randomUUID()}`);let fd;
55
63
  try{
56
64
  fd=fs.openSync(temporary,'wx',0o600);fs.writeFileSync(fd,bytes);fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
57
65
  beforeRename();
58
66
  fs.renameSync(temporary,target);
59
- const dir=fs.openSync(specsDir,'r');try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
67
+ // Windows does not support fsync on directory handles. The file was synced above.
68
+ if(process.platform!=='win32'){
69
+ const dir=fs.openSync(specsDir,'r');try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
70
+ }
60
71
  need(fs.readFileSync(target).equals(bytes));
61
72
  return canonical;
62
73
  }finally{
@@ -0,0 +1,201 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {openControlRun} from './cm-ai-run.mjs';
7
+ import {buildManifest} from './cm-spec-manifest.mjs';
8
+ import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
9
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
10
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
11
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+ import {readRunnerHistory,runnerPayloadV3} from '../runtime/js/cm-ai/durable-runner-state.mjs';
13
+
14
+ function fixture(){
15
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-abandon-position-')));
16
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.work';
17
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
18
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'old\n');
19
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'fixture\n');
20
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
21
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-002: fixture\n');
22
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
23
+ return {root,codeProject,specsDir,feature,reviewsDir:path.join(specsDir,'.reviews'),
24
+ tasksPath:path.join(specsDir,feature,'tasks.md')};
25
+ }
26
+ const identity=runId=>({repositoryId:'abandon-position',runId,taskId:'T-002',attempt:1});
27
+ const definition=(f,runId)=>({version:1,specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
28
+ identity:identity(runId),scope:['a.mjs'],requirements:['requirements.md']});
29
+ const request=runId=>({version:1,operation:'abandon_effect',requestId:'abandon',identity:identity(runId),reason:'Old host and children exited'});
30
+ function execution(f,verdict='blocked'){
31
+ const reviewer={id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',
32
+ allowed:true,available:true,contexts:['review-one','review-two'],run:(value,{onEvent})=>{
33
+ onEvent({event:'thread.started',provider_thread:'review-thread'});
34
+ onEvent({event:'turn.started',item_type:null});onEvent({event:'item.completed',item_type:'agent_message'});
35
+ onEvent({event:'turn.completed',item_type:null});onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
36
+ return {status:'succeeded',value:{verdict,packageDigest:value.payload.reviewPackage.packageDigest,
37
+ examinedPaths:reviewPaths(value.payload.reviewPackage),findings:[],summary:'Fixture review'}};
38
+ }};
39
+ return {configuration:{kind:'abandon-position-v1'},timeoutMs:2000,excludedContexts:['control'],
40
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({
41
+ requestedModel:'fixture',worker:async()=>{fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'written\n');
42
+ return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
43
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
44
+ reviewers:[reviewer],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control'],
45
+ authorize:(value,{authorizationAt})=>{const body={version:1,kind:'cm-review-dispatch-grant',
46
+ grantId:'grant',adapterId:'codex-review-adapter',invocationId:value.invocationId,
47
+ requestDigest:value.requestDigest,identity:value.identity,reviewerId:'reviewer',
48
+ logicalContextId:value.contextId,packageDigest:value.payload.reviewPackage.packageDigest,
49
+ hostContextId:'control',decisionId:'approved',decision:'approved',issuedAt:authorizationAt,
50
+ expiresAt:authorizationAt+60000};return {...body,grantDigest:digest(body)};}},
51
+ hostDecision:{status:'approved'},check:createHostCheck({cwd:f.codeProject,
52
+ commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]})};
53
+ }
54
+ async function start(f,runId,verdict='blocked',options={}){
55
+ const run=await openControlRun(definition(f,runId),'create',execution(f,verdict),options);
56
+ try{return await run.host.handle({version:1,operation:'advance',requestId:'advance',identity:identity(runId)});}
57
+ finally{run.close();}
58
+ }
59
+ function statePath(f,runId){return path.join(f.reviewsDir,'.execution',runId,'state.json');}
60
+ function savePrefix(f,runId,type,kind){
61
+ const file=statePath(f,runId),state=JSON.parse(fs.readFileSync(file,'utf8'));
62
+ const index=state.records.findIndex(row=>row.payload.type===type
63
+ &&(kind===null||row.payload.effect?.kind===kind));
64
+ assert(index>=0,`missing ${type} ${kind}`);
65
+ const {revision,...body}=state;body.records=state.records.slice(0,index+1);
66
+ fs.writeFileSync(file,JSON.stringify({...body,revision:digest(body)})+'\n');
67
+ return body.records;
68
+ }
69
+ function append(f,runId,type,fields,kind=type==='control'?'cancel':'result'){
70
+ const file=statePath(f,runId),state=JSON.parse(fs.readFileSync(file,'utf8'));
71
+ const {revision,...body}=state,seq=body.records.length+1;
72
+ const record={version:1,seq,id:`runner.${String(seq).padStart(6,'0')}`,kind,
73
+ payload:runnerPayloadV3(type,fields),previousDigest:body.records.at(-1).digest};
74
+ body.records.push({...record,digest:digest(record)});
75
+ fs.writeFileSync(file,JSON.stringify({...body,revision:digest(body)})+'\n');
76
+ return body.records;
77
+ }
78
+ async function resume(f,runId,verdict='blocked'){
79
+ return openControlRun(definition(f,runId),'resume',execution(f,verdict),{allowAbandonEffect:true});
80
+ }
81
+ function mutated(records,index,change){
82
+ const result=structuredClone(records);change(result[index].payload);
83
+ for(let at=index;at<result.length;at++){
84
+ const {digest:discard,...body}=result[at];body.previousDigest=at?result[at-1].digest:null;
85
+ result[at]={...body,digest:digest(body)};
86
+ }
87
+ return result;
88
+ }
89
+
90
+ for(const [kind,event] of [['develop','cancel'],['complete','late-cancel']])
91
+ test(`${kind} intent plus ${event} control replays and abandons at the bound position`,async()=>{
92
+ const f=fixture(),runId=`control-${kind}`;
93
+ try{
94
+ await start(f,runId,kind==='complete'?'approved':'blocked');
95
+ const intentRecords=savePrefix(f,runId,'effect-intent',kind);
96
+ const intent=intentRecords.at(-1);
97
+ const first=append(f,runId,'control',{event});
98
+ assert.equal(readRunnerHistory(first,first[0].payload.config,3).state.code,'reconciliation_required');
99
+ const prefix=append(f,runId,'control',{event:'workflow-error'});
100
+ const projected=readRunnerHistory(prefix,prefix[0].payload.config,3);
101
+ assert.equal(projected.state.state,'unknown');assert.equal(projected.state.code,'reconciliation_required');
102
+ assert.equal(projected.pendingAbandonable,true);
103
+ if(kind==='complete')fs.writeFileSync(f.tasksPath,'- [ ] T-002: fixture\n');
104
+ await assert.rejects(start(f,`${runId}-next`,'blocked',
105
+ {supersedeReason:'restart',acceptSupersededCodeDrift:true}),
106
+ error=>error.code==='supersede_unavailable'&&/abandon_effect/.test(error.reason));
107
+ const run=await resume(f,runId,kind==='complete'?'approved':'blocked');
108
+ try{
109
+ const status=await run.host.handle({version:1,operation:'status',requestId:'status',identity:identity(runId)});
110
+ assert.equal(status.pendingAction,'abandon_effect');
111
+ const result=await run.host.handle(request(runId));
112
+ assert.equal(result.outcome,'abandoned');assert.equal(result.state,'cancelled');
113
+ }finally{run.close();}
114
+ const records=JSON.parse(fs.readFileSync(statePath(f,runId),'utf8')).records;
115
+ const abandoned=records.at(-1);
116
+ assert.equal(abandoned.payload.intentDigest,intent.digest);
117
+ assert.equal(abandoned.payload.lastRecordDigest,records.at(-2).digest);
118
+ assert.equal(readRunnerHistory(records,records[0].payload.config,3).state.code,'effect_abandoned');
119
+ for(const key of ['intentDigest','lastRecordDigest']){
120
+ const wrong=mutated(records,records.length-1,p=>{p[key]='0'.repeat(64);});
121
+ assert.throws(()=>readRunnerHistory(wrong,wrong[0].payload.config,3),{code:'runner_abandon'});
122
+ }
123
+ const oldShape=mutated(records,records.length-1,p=>{delete p.lastRecordDigest;});
124
+ assert.throws(()=>readRunnerHistory(oldShape,oldShape[0].payload.config,3),{code:'runner_abandon'});
125
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
126
+ });
127
+
128
+ test('review intent before any join or registration uses abandon_effect; registration keeps abandon_review',async()=>{
129
+ const f=fixture(),runId='review-before-dispatch';
130
+ try{
131
+ await start(f,runId);
132
+ const prefix=savePrefix(f,runId,'effect-intent','review');
133
+ const config=prefix[0].payload.config;
134
+ const controlled=append(f,runId,'control',{event:'cancel'});
135
+ assert.equal(readRunnerHistory(controlled,config,3).pendingAbandonable,true);
136
+ await assert.rejects(start(f,'review-next','blocked',
137
+ {supersedeReason:'restart',acceptSupersededCodeDrift:true}),
138
+ error=>error.code==='supersede_unavailable'&&/abandon_effect/.test(error.reason));
139
+ const run=await resume(f,runId);
140
+ try{
141
+ const status=await run.host.handle({version:1,operation:'status',requestId:'status',identity:identity(runId)});
142
+ assert.equal(status.pendingAction,'abandon_effect');
143
+ assert.equal((await run.host.handle(request(runId))).code,'effect_abandoned');
144
+ }finally{run.close();}
145
+ const records=JSON.parse(fs.readFileSync(statePath(f,runId),'utf8')).records;
146
+ assert.equal(readRunnerHistory(records,config,3).state.state,'cancelled');
147
+ const events=fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
148
+ assert.equal(events.findLast(row=>row.event==='effect_abandoned')?.node,'N4');
149
+ savePrefix(f,runId,'effect-intent','review');
150
+ append(f,runId,'host-joined',{hostContextId:'fresh-host'},'result');
151
+ const joined=JSON.parse(fs.readFileSync(statePath(f,runId),'utf8')).records;
152
+ assert.equal(readRunnerHistory(joined,config,3).pendingAbandonable,false);
153
+ const forged=append(f,runId,'effect-abandoned',{effectId:prefix.at(-1).payload.effect.id,
154
+ effectKind:'review',intentDigest:prefix.at(-1).digest,lastRecordDigest:joined.at(-1).digest,
155
+ reason:'old host exited',at:new Date().toISOString()},'result');
156
+ assert.throws(()=>readRunnerHistory(forged,config,3),{code:'runner_abandon'});
157
+ savePrefix(f,runId,'host-joined',null);
158
+ const joinedRun=await resume(f,runId);
159
+ try{assert.equal((await joinedRun.host.handle(request(runId))).code,'effect_abandon_review_pending');}
160
+ finally{joinedRun.close();}
161
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
162
+ });
163
+
164
+ test('legacy direct effect-abandoned record replays without the last-record field',async()=>{
165
+ const f=fixture(),runId='legacy-direct';
166
+ try{
167
+ await start(f,runId);
168
+ const records=savePrefix(f,runId,'effect-intent','develop');
169
+ const intent=records.at(-1);
170
+ const old=append(f,runId,'effect-abandoned',{effectId:intent.payload.effect.id,
171
+ effectKind:'develop',intentDigest:intent.digest,reason:'old host exited',
172
+ at:new Date().toISOString()},'result');
173
+ assert.equal(readRunnerHistory(old,old[0].payload.config,3).state.code,'effect_abandoned');
174
+ const extra=mutated(old,old.length-1,p=>{p.intentDigest='0'.repeat(64);});
175
+ assert.throws(()=>readRunnerHistory(extra,extra[0].payload.config,3),{code:'runner_abandon'});
176
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
177
+ });
178
+
179
+ test('registered review stays on abandon_review and cannot replay effect-abandoned',async()=>{
180
+ const f=fixture(),runId='review-registered';
181
+ try{
182
+ await start(f,runId);
183
+ const records=savePrefix(f,runId,'review-invocation-registered',null);
184
+ const config=records[0].payload.config,intent=records.findLast(row=>row.payload.type==='effect-intent');
185
+ const projected=readRunnerHistory(records,config,3);
186
+ assert.equal(projected.pendingAbandonable,false);
187
+ await assert.rejects(start(f,'registered-next','blocked',
188
+ {supersedeReason:'restart',acceptSupersededCodeDrift:true}),
189
+ error=>error.code==='supersede_unavailable'&&/abandon_review/.test(error.reason));
190
+ const run=await resume(f,runId);
191
+ try{
192
+ const status=await run.host.handle({version:1,operation:'status',requestId:'status',identity:identity(runId)});
193
+ assert.equal(status.pendingAction,'abandon_review');
194
+ assert.equal((await run.host.handle(request(runId))).code,'effect_abandon_review_pending');
195
+ }finally{run.close();}
196
+ const forged=append(f,runId,'effect-abandoned',{effectId:intent.payload.effect.id,
197
+ effectKind:'review',intentDigest:intent.digest,lastRecordDigest:records.at(-1).digest,
198
+ reason:'old host exited',at:new Date().toISOString()},'result');
199
+ assert.throws(()=>readRunnerHistory(forged,config,3),{code:'runner_abandon'});
200
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
201
+ });
@@ -3,10 +3,10 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {fileURLToPath} from 'node:url';
6
- import {inspectCmAiAdmission,approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
6
+ import {inspectCmAiAdmission,approveCmAiSpecs,matchesCmAiTaskSelection,explainCmAiTaskSelection} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
7
7
  import {validateRunDefinition} from './cm-ai-run.mjs';
8
8
 
9
- const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve --approval-response TEXT (no --yes)] [--print-run-definition --scope a,b [--requirements c,d] [--run-id X] [--repository-id Y]]';
9
+ const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve --approval-response TEXT (no --yes)] [--print-run-definition --scope a,b [--task T-xxx] [--requirements c,d] [--run-id X] [--repository-id Y]]';
10
10
 
11
11
  function parse(argv){
12
12
  const result={codeProjects:[]};
@@ -27,19 +27,23 @@ function parse(argv){
27
27
  result.codeProjects.push(argv[++index]);continue;
28
28
  }
29
29
  const key={'--specs-dir':'specsDir','--approval-response':'approvalResponse',
30
- '--scope':'scope','--requirements':'requirements','--run-id':'runId','--repository-id':'repositoryId'}[flag];
30
+ '--scope':'scope','--task':'task','--requirements':'requirements','--run-id':'runId','--repository-id':'repositoryId'}[flag];
31
31
  if(!key||index+1>=argv.length||Object.hasOwn(result,key))throw new Error('invalid arguments');
32
32
  result[key]=argv[++index];
33
33
  }
34
34
  if(!result.specsDir||result.codeProjects.length===0)throw new Error('specs and code project paths are required');
35
35
  if(result.assumeYes&&Object.hasOwn(result,'approvalResponse'))throw new Error('approval input is duplicated');
36
- if(!result.printRunDefinition&&['scope','requirements','runId','repositoryId'].some(key=>Object.hasOwn(result,key)))
36
+ if(!result.printRunDefinition&&['scope','task','requirements','runId','repositoryId'].some(key=>Object.hasOwn(result,key)))
37
37
  throw new Error('run definition options require --print-run-definition');
38
38
  return result;
39
39
  }
40
40
 
41
41
  function buildRunDefinition(admission,input){
42
42
  if(!admission.codeProject)throw new Error('--print-run-definition requires one --code-project');
43
+ const selected=input.task===undefined?admission.nextTask:{feature:admission.nextTask.feature,id:input.task};
44
+ if(input.task!==undefined&&!matchesCmAiTaskSelection(admission,selected.feature,selected.id,{version:1,taskId:input.task}))
45
+ throw Object.assign(new Error('task_selection_mismatch'),{code:'task_selection_mismatch',
46
+ reason:explainCmAiTaskSelection(admission,{feature:selected.feature,taskId:input.task,selection:{version:1,taskId:input.task}})});
43
47
  let repositoryId=input.repositoryId;
44
48
  if(repositoryId===undefined){
45
49
  let name;
@@ -49,10 +53,11 @@ function buildRunDefinition(admission,input){
49
53
  }
50
54
  const list=value=>value===undefined||value===''?[]:value.split(',').map(item=>item.trim());
51
55
  const definition={version:1,specsDir:admission.specsDir,codeProject:admission.codeProject,
52
- feature:admission.nextTask.feature,
53
- identity:{repositoryId,runId:input.runId??`${admission.nextTask.feature.replace(/^\d+\./,'')}-${admission.nextTask.id}`,
54
- taskId:admission.nextTask.id,attempt:1},
55
- scope:list(input.scope),requirements:list(input.requirements)};
56
+ feature:selected.feature,
57
+ identity:{repositoryId,runId:input.runId??`${selected.feature.replace(/^\d+\./,'')}-${selected.id}`,
58
+ taskId:selected.id,attempt:1},
59
+ scope:list(input.scope),requirements:list(input.requirements),
60
+ ...(input.task===undefined?{}:{taskSelection:{version:1,taskId:selected.id}})};
56
61
  return validateRunDefinition(definition);
57
62
  }
58
63
 
@@ -71,12 +76,16 @@ export function main(argv=process.argv.slice(2)){
71
76
  const decision=JSON.stringify({state:reference.state,reason:reference.reason,features:reference.features,nextTask:reference.nextTask});
72
77
  const mismatch=!firstBlocked&&projectResults.some(item=>JSON.stringify({state:item.state,reason:item.reason,features:item.features,nextTask:item.nextTask})!==decision);
73
78
  const selected=mismatch?{...reference,state:'blocked',reason:'project_admission_mismatch',nextTask:null}:reference;
74
- const result={...selected,...(approval?.approveRefused?{approveRefused:approval.approveRefused}:{}),codeProject:input.codeProjects.length===1?selected.codeProject:null,
79
+ const result={...selected,...(approval?.approveRefused?{approveRefused:approval.approveRefused}:{}),
80
+ ...(approval?.approveReason?{approveReason:approval.approveReason}:{}),codeProject:input.codeProjects.length===1?selected.codeProject:null,
75
81
  codeProjects:projectResults.map(item=>item.codeProject),
76
82
  projectAdmissions:projectResults.map(item=>({codeProject:item.codeProject,state:item.state,reason:item.reason}))};
83
+ if(result.state==='awaiting_spec_approval'&&(result.approvalIntent!=='explicit'||input.assumeYes))
84
+ result.message='确认规格摘要后,用 --approval-response 传入用户原话,并明确回复“开始”。';
77
85
  if(input.printRunDefinition&&!result.approveRefused&&result.state==='ready'){
78
86
  try{process.stdout.write(`${JSON.stringify(buildRunDefinition(result,input))}\n`);return 0;}
79
- catch(error){process.stderr.write(`${JSON.stringify({error:{code:error.code??error.message}})}\n`);return 1;}
87
+ catch(error){process.stderr.write(`${JSON.stringify({error:{code:error.code??error.message,
88
+ ...(typeof error.reason==='string'?{reason:error.reason}:{})}})}\n`);return 1;}
80
89
  }
81
90
  process.stdout.write(`${JSON.stringify(result)}\n`);
82
91
  return result.state==='blocked'||result.approveRefused?1:0;