@aibyzero/cm-workflow 0.16.4 → 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 (167) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +50 -0
  4. package/README.md +12 -1
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/runtime-failover.md +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  11. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  14. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  16. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  17. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  19. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  20. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  21. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  22. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  24. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  26. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  27. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  28. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  29. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  30. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  31. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  33. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  34. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  35. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  36. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  37. package/runtime/js/cm-ai/host-session.mjs +12 -4
  38. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  42. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  45. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  46. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  47. package/runtime/js/cm-ai/review-package.mjs +427 -31
  48. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  49. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  50. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  51. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  52. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  53. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  54. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  55. package/runtime/js/cm-fix/execution.mjs +109 -25
  56. package/runtime/js/cm-fix/host-review.mjs +7 -3
  57. package/runtime/js/cm-fix/host.mjs +3 -1
  58. package/runtime/js/cm-fix/progress.mjs +1 -0
  59. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  60. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  61. package/runtime/js/cm-prd/analysis.mjs +2 -1
  62. package/runtime/js/cm-prd/change.mjs +28 -10
  63. package/runtime/js/cm-prd/draft.mjs +5 -2
  64. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  65. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  66. package/runtime/js/cm-prd/self-check.mjs +6 -3
  67. package/runtime/js/cm-prd/summary.mjs +3 -1
  68. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  69. package/runtime/js/spec-task-line.mjs +117 -0
  70. package/runtime/js/specs-status.mjs +10 -3
  71. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  72. package/scripts/cm-ai-admission.mjs +18 -11
  73. package/scripts/cm-ai-admission.test.mjs +65 -1
  74. package/scripts/cm-ai-batch-drive.mjs +92 -20
  75. package/scripts/cm-ai-batch-drive.test.mjs +164 -3
  76. package/scripts/cm-ai-batch-host.mjs +27 -11
  77. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  78. package/scripts/cm-ai-batch-run.mjs +33 -10
  79. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  80. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  81. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  82. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  84. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  85. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  86. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  87. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  88. package/scripts/cm-ai-drive.mjs +479 -47
  89. package/scripts/cm-ai-drive.test.mjs +240 -10
  90. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  91. package/scripts/cm-ai-host.mjs +84 -25
  92. package/scripts/cm-ai-host.test.mjs +232 -12
  93. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  94. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  95. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  96. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  97. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  98. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  99. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  100. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  101. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  102. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  103. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  104. package/scripts/cm-ai-run.mjs +160 -60
  105. package/scripts/cm-ai-run.test.mjs +4 -3
  106. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  107. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  108. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  109. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  110. package/scripts/cm-ai-supersede.test.mjs +571 -17
  111. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  112. package/scripts/cm-capability-gate.test.mjs +21 -2
  113. package/scripts/cm-check-drive.test.mjs +1 -1
  114. package/scripts/cm-check-host.test.mjs +1 -1
  115. package/scripts/cm-check-runtime.sh +1 -1
  116. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  117. package/scripts/cm-claude-probe.test.mjs +9 -1
  118. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  119. package/scripts/cm-claude-worker.test.mjs +11 -4
  120. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  121. package/scripts/cm-failover.mjs +8 -8
  122. package/scripts/cm-fix-abandon.test.mjs +123 -5
  123. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  124. package/scripts/cm-fix-drive.mjs +45 -13
  125. package/scripts/cm-fix-drive.test.mjs +36 -1
  126. package/scripts/cm-fix-host.mjs +9 -6
  127. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  128. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  129. package/scripts/cm-host-check.test.mjs +6 -3
  130. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  131. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  132. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  133. package/scripts/cm-log-event.mjs +17 -0
  134. package/scripts/cm-log-event.test.mjs +31 -0
  135. package/scripts/cm-prd-completion.test.mjs +75 -0
  136. package/scripts/cm-prd-draft.test.mjs +14 -0
  137. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  138. package/scripts/cm-prd-review-gate.mjs +126 -81
  139. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  140. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  141. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  142. package/scripts/cm-prd-self-check.test.mjs +6 -0
  143. package/scripts/cm-prd-summary.test.mjs +9 -0
  144. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  145. package/scripts/cm-review-inventory.test.mjs +253 -1
  146. package/scripts/cm-spec-manifest.mjs +28 -10
  147. package/scripts/cm-spec-manifest.test.mjs +8 -4
  148. package/scripts/cm-spec-task-line.test.mjs +138 -0
  149. package/scripts/cm-specs-status.test.mjs +12 -1
  150. package/scripts/cm-task-gate.mjs +18 -10
  151. package/scripts/cm-task-gate.py +1 -1
  152. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  153. package/scripts/fixtures/claude-review-process.mjs +1 -0
  154. package/scripts/fixtures/process-cleanup.mjs +99 -0
  155. package/scripts/test-cm-log-event.py +2 -0
  156. package/scripts/test-cm-prd-review-gate.py +2 -1
  157. package/scripts/test-npm-install.py +1 -1
  158. package/scripts/test-scan-public-safety.py +1 -1
  159. package/scripts/test-spec-manifest.py +16 -8
  160. package/scripts/test-task-gate.py +2 -2
  161. package/scripts/test-workflow-config.py +1 -0
  162. package/scripts/validate-public-repo.py +1 -0
  163. package/skills/cm-ai/references/N1-init.md +1 -1
  164. package/skills/cm-ai/references/js-host.md +261 -42
  165. package/skills/cm-fix/references/js-host.md +22 -1
  166. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  167. package/skills/cm-prd/references/js-host.md +6 -0
@@ -21,6 +21,12 @@ function fixture(t){
21
21
  return {specs,prepared,response,claim:()=>claimPrdReview({...prepared.paths,package_sha256:prepared.packageDigest}),
22
22
  publish:()=>publishPrdReview({specs,reviewPackage:prepared.reviewPackage,packageDigest:prepared.packageDigest,authorContextId:'author-context',response})};
23
23
  }
24
+ test('review timestamp identifies at and exact JavaScript ISO form',t=>{
25
+ const {response,claim,publish}=fixture(t);claim();response.at='2026-09-08T00:00:00Z';
26
+ assert.throws(publish,error=>error.code==='prd_review_timestamp_invalid'
27
+ &&error.reason?.field==='response.at'
28
+ &&error.reason.expected.includes('new Date().toISOString()'));
29
+ });
24
30
  test('claimed result publishes r1 once, readback resumes original gate and conflict preserves bytes',t=>{
25
31
  const {prepared,response,claim,publish}=fixture(t);claim();
26
32
  const result=publish();assert.equal(result.gate.outcome,'resume_disposition');assert.equal(result.completionAuthorized,false);
@@ -21,3 +21,9 @@ test('cycles, task budget, false declarations and missing AC/task references fai
21
21
  const codes=checkPrdDraftMechanics(draft(undefined,wrong)).findings.map(x=>x.code);
22
22
  assert.ok(codes.includes('test_reference_invalid'));assert.ok(codes.includes('acceptance_test_coverage_missing'));
23
23
  });
24
+ test('malformed dependency finding names tasks.md and one-line comma format',()=>{
25
+ const report=checkPrdDraftMechanics(draft('- [ ] T-001: A\n- [ ] T-002: B\n- T-002 依赖 T-001。T-003'));
26
+ const finding=report.findings.find(item=>item.code==='dependencies_invalid');
27
+ assert.equal(finding.reason.field,'1.sample/tasks.md');
28
+ assert.match(finding.reason.expected,/- T-003 依赖 T-001, T-002/);
29
+ });
@@ -108,7 +108,14 @@ test('change digest survives later summary publication, recovery, approval, and
108
108
  assert.equal(JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'))).revisionDigest,proposal.proposalDigest);
109
109
  const nextBefore=inspectPrdChangeSnapshot(specs),nextProposal=inspectPrdChangeProposal(nextBefore,{status:'draft',summary:'Extend notes again',removed:[],
110
110
  features:[{directory,documents:revise(revise(original,2),3),testCasesReason:'no_observable_behavior'}]},selected,config);
111
+ assert.equal(JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'))).taskGrammar,2,'approval binds the shared grammar');
111
112
  assert.equal(applyPrdChange({specs,before:nextBefore,proposal:nextProposal,selected}).status,'awaiting_review');
113
+ // The last approval's grammar travels through cm-prd change and publication.
114
+ const status=()=>JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status')));
115
+ assert.equal(status().taskGrammar,2);
116
+ const nextSummary=await summaryOwner()(specs,{currentFeatures:['2.appendix']});
117
+ assert.equal(publishPrdAwaitingReview({specs,summary:nextSummary,writeEnabled:true}).status,'awaiting_review');
118
+ assert.equal(status().status,'awaiting_review');assert.equal(status().taskGrammar,2);
112
119
  });
113
120
  function legacy(specs){
114
121
  const prefix=path.join(specs,'.reviews/prd-guide-split');
@@ -134,6 +141,8 @@ test('legacy completed history registers notes; current summary publishes the fu
134
141
  assert.equal(result.status,'awaiting_review');
135
142
  const status=JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'),'utf8'));
136
143
  assert.deepEqual(status.features,['1.guide','2.appendix']);assert.deepEqual(status.specFiles,evidence.specFiles);
144
+ // First publication: no earlier approval to reinterpret, so it carries the shared grammar.
145
+ assert.equal(status.taskGrammar,2);
137
146
  assert.equal(publishPrdAwaitingReview({specs,summary,writeEnabled:true,recover:true}).status,'awaiting_review');
138
147
  });
139
148
  test('current missing disposition remains a blocker',async t=>{
@@ -33,6 +33,20 @@ test('dependency directories and nested Python caches do not enter business snap
33
33
  assert.throws(()=>createReviewPackage({root,baseline,checks}),{code:'out_of_scope'});
34
34
  });
35
35
 
36
+ test('out of scope reports bounded relative paths without exposing the root',t=>{
37
+ const {root,options}=fixture(t),baseline=captureReviewBaseline(options);
38
+ fs.mkdirSync(path.join(root,'build'));
39
+ for(let i=0;i<22;i++)fs.writeFileSync(path.join(root,'build',`output-${String(i).padStart(2,'0')}`),'x');
40
+ assert.throws(()=>createReviewPackage({root,baseline,checks}),error=>{
41
+ assert.equal(error.code,'out_of_scope');
42
+ assert.match(error.message,/build\/output-00/);
43
+ assert.match(error.message,/\(\+2 more\)/);
44
+ assert(!error.message.includes('build/output-20'));
45
+ assert(!error.message.includes(root));
46
+ return true;
47
+ });
48
+ });
49
+
36
50
  test('excluded directories cannot be selected as business edits or requirements',t=>{
37
51
  const {root,options}=fixture(t);
38
52
  fs.mkdirSync(path.join(root,'.venv'));
@@ -58,6 +72,7 @@ test('legacy baselines retain already-recorded dependency files and their drift
58
72
  fs.mkdirSync(path.join(root,'.venv'));
59
73
  fs.writeFileSync(path.join(root,'.venv','recorded.txt'),'legacy snapshot material');
60
74
  const {baselineDigest,...body}=base;
75
+ delete body.ignorePolicy;
61
76
  body.files=[...body.files,...readReviewSourceFiles(root,['.venv/recorded.txt'])].sort((a,b)=>a.path.localeCompare(b.path));
62
77
  const baseline={...body,baselineDigest:digest(body)};
63
78
  fs.writeFileSync(path.join(root,'src/main.py'),'after');
@@ -4,7 +4,8 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {createHash} from 'node:crypto';
7
- import {captureReviewBaseline,createReviewPackage,readReviewBaseline,readReviewPackage,verifyReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
7
+ import {spawnSync} from 'node:child_process';
8
+ import {captureReviewBaseline,compareReviewBaseline,compareReviewInventoryToBaseline,createReviewPackage,readReviewBaseline,readReviewPackage,verifyReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
8
9
  import {digest} from '../runtime/js/cm-ai/contracts.mjs';
9
10
  import {buildReviewPrompt} from '../runtime/js/cm-ai/codex-review-adapter.mjs';
10
11
 
@@ -19,6 +20,257 @@ function fixture(fn){
19
20
  finally{fs.rmSync(root,{recursive:true,force:true});}
20
21
  }
21
22
 
23
+ test('Git ignored SwiftPM and DerivedData trees and fixed IDE junk stay outside every snapshot',()=>fixture(root=>{
24
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
25
+ write(root,'.gitignore','custom-cache/\n');
26
+ fs.mkdirSync(path.join(root,'.build'),{recursive:true});
27
+ fs.symlinkSync('missing',path.join(root,'.build','linked'));
28
+ fs.mkdirSync(path.join(root,'custom-cache'));fs.symlinkSync('missing',path.join(root,'custom-cache','linked'));
29
+ fs.mkdirSync(path.join(root,'DerivedData','Build'),{recursive:true});
30
+ for(let i=0;i<10005;i++)write(root,`DerivedData/Build/${i}`,'');
31
+ fs.mkdirSync(path.join(root,'App.xcodeproj','xcuserdata'),{recursive:true});
32
+ write(root,'App.xcodeproj/xcuserdata/UserInterfaceState.xcuserstate','old');
33
+ write(root,'.DS_Store','old');write(root,'._asset','old');write(root,'Thumbs.db','old');
34
+ const baseline=capture(root);write(root,'code.js','after');
35
+ const pkg=createReviewPackage({root,baseline,checks});
36
+ write(root,'.DS_Store','new');write(root,'App.xcodeproj/xcuserdata/UserInterfaceState.xcuserstate','new');
37
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
38
+ assert(!baseline.files.some(file=>/DerivedData|xcuserdata|custom-cache|\.build|DS_Store/.test(file.path)));
39
+ }));
40
+
41
+ test('a parent worktree ignore rule can change while review retains the baseline decision',()=>fixture(repo=>{
42
+ assert.equal(spawnSync('git',['init','-q',repo]).status,0);
43
+ const app=path.join(repo,'app');fs.mkdirSync(app);
44
+ write(app,'code.js','before');write(app,'requirements.md','fixture');
45
+ write(repo,'.gitignore','app/generated/\n');
46
+ const baseline=capture(app);write(app,'code.js','after');
47
+ const pkg=createReviewPackage({root:app,baseline,checks});
48
+ write(repo,'.gitignore','app/generated/\napp/other-generated/\n');
49
+ fs.mkdirSync(path.join(app,'other-generated'));write(app,'other-generated/check.log','generated');
50
+ assert.equal(verifyReviewPackage({root:app,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
51
+ }));
52
+
53
+ test('an ignored same-root specs directory is still reached as a protected boundary',()=>fixture(root=>{
54
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
55
+ write(root,'.gitignore','generated/\n');
56
+ const specsRoot=path.join(root,'generated','specs');fs.mkdirSync(specsRoot,{recursive:true});
57
+ write(specsRoot,'tasks.md','- [ ] T-001: fixture\n');
58
+ const baseline=capture(root,{specsRoot});
59
+ assert.equal(baseline.specsPath,'generated/specs');
60
+ assert(!baseline.files.some(file=>file.path.startsWith('generated/specs/')));
61
+ }));
62
+
63
+ test('a gitignored approved scope and AGENTS.md remain checked',()=>fixture(root=>{
64
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
65
+ write(root,'.gitignore','code.js\nAGENTS.md\n');write(root,'AGENTS.md','rules');
66
+ const baseline=capture(root);assert(baseline.files.some(file=>file.path==='AGENTS.md'));
67
+ write(root,'code.js','after');const pkg=createReviewPackage({root,baseline,checks});
68
+ write(root,'AGENTS.md','changed');
69
+ assert.throws(()=>verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}),
70
+ error=>error.code==='out_of_scope'&&error.message.includes('AGENTS.md'));
71
+ }));
72
+
73
+ test('a selected file and AGENTS inside a Git-ignored directory remain checked without reading siblings',()=>fixture(root=>{
74
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
75
+ write(root,'.gitignore','custom-cache/\n');
76
+ fs.mkdirSync(path.join(root,'custom-cache'));
77
+ write(root,'custom-cache/selected.swift','before');write(root,'custom-cache/AGENTS.md','rules');
78
+ fs.symlinkSync('missing',path.join(root,'custom-cache','linked'));
79
+ const baseline=capture(root,{scope:['custom-cache/selected.swift']});
80
+ assert(baseline.files.some(file=>file.path==='custom-cache/AGENTS.md'));
81
+ write(root,'custom-cache/selected.swift','after');
82
+ const pkg=createReviewPackage({root,baseline,checks});
83
+ write(root,'custom-cache/AGENTS.md','changed');
84
+ assert.throws(()=>verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}),
85
+ error=>error.code==='out_of_scope'&&error.message.includes('custom-cache/AGENTS.md'));
86
+ }));
87
+
88
+ test('a nested AGENTS file inside built-in ignored output remains checked',()=>fixture(root=>{
89
+ fs.mkdirSync(path.join(root,'.build','subdir'),{recursive:true});
90
+ write(root,'.build/subdir/AGENTS.md','rules');fs.symlinkSync('missing',path.join(root,'.build','linked'));
91
+ const baseline=capture(root);assert(baseline.files.some(file=>file.path==='.build/subdir/AGENTS.md'));
92
+ write(root,'code.js','after');const pkg=createReviewPackage({root,baseline,checks});
93
+ write(root,'.build/subdir/AGENTS.md','changed');
94
+ assert.throws(()=>verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}),
95
+ error=>error.code==='out_of_scope'&&error.message.includes('.build/subdir/AGENTS.md'));
96
+ }));
97
+
98
+ test('Git-active built-in junk still retains nested AGENTS instructions',()=>fixture(root=>{
99
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
100
+ fs.mkdirSync(path.join(root,'.build','nested'),{recursive:true});
101
+ write(root,'.build/nested/AGENTS.md','rules');fs.symlinkSync('missing',path.join(root,'.build','linked'));
102
+ const baseline=capture(root);assert(baseline.files.some(file=>file.path==='.build/nested/AGENTS.md'));
103
+ write(root,'code.js','after');const pkg=createReviewPackage({root,baseline,checks});
104
+ write(root,'.build/nested/AGENTS.md','changed');
105
+ assert.throws(()=>verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}),
106
+ error=>error.code==='out_of_scope'&&error.message.includes('.build/nested/AGENTS.md'));
107
+ }));
108
+
109
+ test('snapshot failures and package mismatch identify the affected paths',()=>fixture(root=>{
110
+ fs.symlinkSync('missing',path.join(root,'linked'));
111
+ assert.throws(()=>capture(root),error=>error.code==='unsupported_file'&&error.message.includes('linked'));
112
+ fs.unlinkSync(path.join(root,'linked'));
113
+ const baseline=capture(root);write(root,'code.js','after');const pkg=createReviewPackage({root,baseline,checks});
114
+ write(root,'stray.txt','x');
115
+ assert.throws(()=>verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}),
116
+ error=>error.message.includes('stray.txt'));
117
+ }));
118
+
119
+ test('an out-of-scope .gitignore edit is a content violation, not policy drift',()=>fixture(root=>{
120
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
121
+ write(root,'.gitignore','cache/\n');fs.mkdirSync(path.join(root,'cache'));write(root,'cache/temp','ignored');
122
+ const baseline=capture(root);write(root,'code.js','after');
123
+ write(root,'.gitignore','different/\n');
124
+ assert.throws(()=>createReviewPackage({root,baseline,checks}),
125
+ error=>error.code==='out_of_scope'&&error.message.includes('.gitignore'));
126
+ }));
127
+
128
+ test('an ignored out-of-scope .gitignore may change without altering saved decisions',()=>fixture(root=>{
129
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
130
+ write(root,'.gitignore','.gitignore\ncache/\n');fs.mkdirSync(path.join(root,'cache'));write(root,'cache/temp','ignored');
131
+ const baseline=capture(root);write(root,'code.js','after');
132
+ write(root,'.gitignore','.gitignore\nother/\n');
133
+ const pkg=createReviewPackage({root,baseline,checks});
134
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
135
+ }));
136
+
137
+ test('core.excludesFile value and bytes are recorded while later rule edits use the union',()=>fixture(root=>{
138
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
139
+ const exclude=path.join(root,'.git','info','extra-excludes');write(root,'.git/info/extra-excludes','cache/\n');
140
+ assert.equal(spawnSync('git',['-C',root,'config','core.excludesFile',exclude]).status,0);
141
+ fs.mkdirSync(path.join(root,'cache'));write(root,'cache/temp','ignored');
142
+ const baseline=capture(root);write(root,'code.js','after');
143
+ assert.equal(baseline.ignorePolicy.coreExcludesFile.valueDigest,sha(exclude));
144
+ assert.equal(baseline.ignorePolicy.coreExcludesFile.sha256,sha('cache/\n'));
145
+ write(root,'.git/info/extra-excludes','other/\n');
146
+ const pkg=createReviewPackage({root,baseline,checks});
147
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
148
+ }));
149
+
150
+ test('effective worktree core.excludesFile is recorded instead of the local fallback',()=>fixture(root=>{
151
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
152
+ const local=path.join(root,'.git','info','local-excludes');
153
+ const worktree=path.join(root,'.git','info','worktree-excludes');
154
+ write(root,'.git/info/local-excludes','local/\n');
155
+ write(root,'.git/info/worktree-excludes','cache/\n');
156
+ assert.equal(spawnSync('git',['-C',root,'config','core.excludesFile',local]).status,0);
157
+ assert.equal(spawnSync('git',['-C',root,'config','extensions.worktreeConfig','true']).status,0);
158
+ assert.equal(spawnSync('git',['-C',root,'config','--worktree','core.excludesFile',worktree]).status,0);
159
+ fs.mkdirSync(path.join(root,'cache'));write(root,'cache/generated','ignored');
160
+ const baseline=capture(root);
161
+ assert.equal(baseline.ignorePolicy.coreExcludesFile.valueDigest,sha(worktree));
162
+ assert.equal(baseline.ignorePolicy.coreExcludesFile.sha256,sha('cache/\n'));
163
+ assert(baseline.ignorePolicy.ignoredDirectories.includes('cache'));
164
+ }));
165
+
166
+ test('Git info/exclude edits preserve baseline ignored paths',()=>fixture(root=>{
167
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
168
+ const exclude=path.join(root,'.git','info','exclude');
169
+ write(root,'.git/info/exclude','cache/\n');fs.mkdirSync(path.join(root,'cache'));write(root,'cache/temp','ignored');
170
+ const baseline=capture(root);write(root,'code.js','after');
171
+ write(root,'.git/info/exclude','other/\n');
172
+ const pkg=createReviewPackage({root,baseline,checks});
173
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
174
+ }));
175
+
176
+ test('unrelated local Git config changes do not affect review identity',()=>fixture(root=>{
177
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
178
+ const baseline=capture(root);write(root,'code.js','after');
179
+ assert.equal(spawnSync('git',['-C',root,'config','user.name','Reviewer']).status,0);
180
+ assert.equal(spawnSync('git',['-C',root,'remote','add','origin','https://example.invalid/repo.git']).status,0);
181
+ const pkg=createReviewPackage({root,baseline,checks});
182
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
183
+ }));
184
+
185
+ test('saved and current ignored directories form a two-sided union for package and verification',()=>fixture(root=>{
186
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
187
+ write(root,'.gitignore','old/\n');
188
+ fs.mkdirSync(path.join(root,'old'));write(root,'old/generated','before');
189
+ fs.mkdirSync(path.join(root,'new'));write(root,'new/authored','before');
190
+ const baseline=capture(root,{scope:['.gitignore','code.js']});
191
+ assert(baseline.ignorePolicy.ignoredDirectories.includes('old'));
192
+ assert(baseline.files.some(file=>file.path==='new/authored'));
193
+ write(root,'code.js','after');write(root,'.gitignore','new/\n');
194
+ write(root,'old/generated','after');write(root,'new/authored','after');
195
+ const pkg=createReviewPackage({root,baseline,checks});
196
+ assert.deepEqual(pkg.changes.map(change=>change.path),['.gitignore','code.js']);
197
+ assert.deepEqual(compareReviewInventoryToBaseline(root,baseline).map(change=>change.path),['.gitignore','code.js']);
198
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
199
+ write(root,'old/generated','later');write(root,'new/authored','later');
200
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
201
+ write(root,'requirements.md','real change');
202
+ assert.throws(()=>verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}),
203
+ error=>error.code==='out_of_scope'&&error.message.includes('requirements.md'));
204
+ }));
205
+
206
+ test('ready-state baseline comparison applies old and current ignore decisions to both inventories',()=>fixture(root=>{
207
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
208
+ write(root,'.git/info/exclude','old/\n');
209
+ fs.mkdirSync(path.join(root,'old'));write(root,'old/generated','before');
210
+ fs.mkdirSync(path.join(root,'new'));write(root,'new/authored','before');
211
+ const baseline=capture(root);
212
+ write(root,'.git/info/exclude','new/\n');
213
+ write(root,'old/generated','after');write(root,'new/authored','after');
214
+ const recaptured=capture(root);
215
+ assert.equal(compareReviewBaseline(recaptured,baseline),true);
216
+ assert.throws(()=>compareReviewBaseline({...recaptured,rootDigest:'0'.repeat(64)},baseline),
217
+ error=>error.code==='package_mismatch'&&error.message.includes('baseline metadata'));
218
+ write(root,'requirements.md','real change');
219
+ assert.throws(()=>compareReviewBaseline(capture(root),baseline),
220
+ error=>error.code==='package_mismatch'&&error.message.includes('requirements.md'));
221
+ }));
222
+
223
+ test('a newly created scoped .gitignore is reviewed and its generated directory is excluded',()=>fixture(root=>{
224
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
225
+ const baseline=capture(root,{scope:['.gitignore','code.js']});
226
+ assert(!baseline.files.some(file=>file.path==='.gitignore'));
227
+ write(root,'.gitignore','build/\n');fs.mkdirSync(path.join(root,'build'));
228
+ write(root,'build/check.log','generated');write(root,'code.js','after');
229
+ const pkg=createReviewPackage({root,baseline,checks});
230
+ assert.deepEqual(pkg.changes.map(change=>change.path),['.gitignore','code.js']);
231
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
232
+ }));
233
+
234
+ test('git init after baseline does not turn repository metadata into review content',()=>fixture(root=>{
235
+ const baseline=capture(root);assert.equal(baseline.ignorePolicy.mode,'builtin');
236
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
237
+ write(root,'.git/info/exclude','build/\n');fs.mkdirSync(path.join(root,'build'));
238
+ write(root,'build/check.log','generated');write(root,'code.js','after');
239
+ const pkg=createReviewPackage({root,baseline,checks});
240
+ assert.deepEqual(pkg.changes.map(change=>change.path),['code.js']);
241
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
242
+ }));
243
+
244
+ test('an oversized Git ignored set records built-in fallback and stays replayable',()=>fixture(root=>{
245
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
246
+ write(root,'.git/info/exclude','*.xcuserstate\n');
247
+ write(root,'authored.txt','before');
248
+ for(let i=0;i<10001;i++)write(root,`state-${i}.xcuserstate`,'generated');
249
+ const baseline=capture(root);
250
+ assert.equal(baseline.ignorePolicy.mode,'builtin_limit');
251
+ assert.deepEqual(baseline.ignorePolicy.ignoredPaths,[]);
252
+ for(let i=0;i<10001;i++)fs.unlinkSync(path.join(root,`state-${i}.xcuserstate`));
253
+ write(root,'.git/info/exclude','authored.txt\n');
254
+ write(root,'code.js','after');
255
+ write(root,'authored.txt','changed');
256
+ assert.throws(()=>createReviewPackage({root,baseline,checks}),
257
+ error=>error.code==='out_of_scope'&&error.message.includes('authored.txt'));
258
+ write(root,'authored.txt','before');
259
+ const pkg=createReviewPackage({root,baseline,checks});
260
+ assert.equal(verifyReviewPackage({root,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
261
+ }));
262
+
263
+ test('missing Git uses only built-in junk rules and still rejects unsupported ignored paths',()=>fixture(root=>{
264
+ assert.equal(spawnSync('git',['init','-q',root]).status,0);
265
+ write(root,'.gitignore','custom-cache/\n');
266
+ fs.mkdirSync(path.join(root,'.build'));fs.symlinkSync('missing',path.join(root,'.build','linked'));
267
+ fs.mkdirSync(path.join(root,'custom-cache'));fs.symlinkSync('missing',path.join(root,'custom-cache','linked'));
268
+ const saved=process.env.PATH;
269
+ try{process.env.PATH='';assert.throws(()=>capture(root),
270
+ error=>error.code==='unsupported_file'&&error.message.includes('custom-cache/linked'));}
271
+ finally{process.env.PATH=saved;}
272
+ }));
273
+
22
274
  test('large inventory retains hashes, emits only selected bodies, and verifies the review package',()=>fixture(root=>{
23
275
  for(let i=0;i<510;i++)write(root,`asset-${i}`,Buffer.alloc(4096,i%256));
24
276
  const media=Buffer.alloc(2*1024*1024+1,17);write(root,'media.bin',media);write(root,'AGENTS.md','fixture instructions');
@@ -6,6 +6,7 @@ import os from 'node:os';
6
6
  import {createHash} from 'node:crypto';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {TextDecoder} from 'node:util';
9
+ import {resetTaskMarks,resetTaskMarkBytes} from '../runtime/js/spec-task-line.mjs';
9
10
 
10
11
  const required=['requirements.md','design.md','tasks.md'];
11
12
  const feature=/^\p{Decimal_Number}+\.[^\n]+$(?![\s\S])/u;
@@ -16,8 +17,13 @@ const compare=(a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b));
16
17
  const exists=p=>{try{fs.statSync(p);return true;}catch(e){if(['ENOENT','ENOTDIR'].includes(e.code))return false;throw e;}};
17
18
 
18
19
  // Only actual task/AC declarations are runtime state; other files and code stay exact.
19
- export function normalizeRuntimeMarks(text,name){
20
+ // tasks.md uses the shared declaration grammar (spec-task-line.mjs) so every
21
+ // task admission can select is also a task whose N5 mark is normalized here.
22
+ // {legacy:true} is the frozen pre-grammar rule, kept only to verify manifests
23
+ // that older versions approved; it is never used to write a new manifest.
24
+ export function normalizeRuntimeMarks(text,name,{legacy=false}={}){
20
25
  if(!['tasks.md','requirements.md'].includes(name))return text;
26
+ if(name==='tasks.md'&&!legacy)return resetTaskMarks(text);
21
27
  const marker=name==='tasks.md'?/^([ ]{0,3}-[ \t]+)\[[xX]\]([ \t]+T-[A-Za-z0-9][A-Za-z0-9._-]*[ \t]*:)/
22
28
  :/^([ ]{0,3}-[ \t]+)\[[xX]\]([ \t]+\[AC-[A-Za-z0-9][A-Za-z0-9._-]*\])/;
23
29
  let fenceChar=null,width=0;
@@ -35,14 +41,17 @@ export function normalizeRuntimeMarks(text,name){
35
41
  }).join('');
36
42
  }
37
43
 
38
- export function semanticDigest(file){
39
- const bytes=fs.readFileSync(file);
44
+ export function normalizeRuntimeMarkBytes(bytes,name,{legacy=false}={}){
45
+ if(name==='tasks.md'&&!legacy)return resetTaskMarkBytes(bytes);
40
46
  // Latin-1 is a reversible byte view, including invalid UTF-8 and CRLF.
41
- const normalized=Buffer.from(normalizeRuntimeMarks(bytes.toString('latin1'),path.basename(file)),'latin1');
42
- return createHash('sha256').update(normalized).digest('hex');
47
+ return Buffer.from(normalizeRuntimeMarks(bytes.toString('latin1'),name,{legacy}),'latin1');
43
48
  }
44
49
 
45
- export function buildManifest(specsDir){
50
+ export function semanticDigest(file,options={}){
51
+ return createHash('sha256').update(normalizeRuntimeMarkBytes(fs.readFileSync(file),path.basename(file),options)).digest('hex');
52
+ }
53
+
54
+ export function buildManifest(specsDir,{legacy=false}={}){
46
55
  if(!exists(specsDir)||!fs.statSync(specsDir).isDirectory())fail(`specs directory does not exist: ${specsDir}`);
47
56
  const features=fs.readdirSync(specsDir).filter(name=>feature.test(name)).sort(compare);
48
57
  if(!features.length)fail('specs directory contains no numbered feature directories');
@@ -59,13 +68,15 @@ export function buildManifest(specsDir){
59
68
  const file=path.join(dir,filename);if(!exists(file))continue;
60
69
  if(!fs.statSync(file).isFile())fail(`approved spec path must be a file: ${file}`);
61
70
  if(fs.lstatSync(file).isSymbolicLink())fail(`approved spec file must not be a symlink: ${file}`);
62
- rows.push({path:`${name}/${filename}`,sha256:semanticDigest(file)});
71
+ rows.push({path:`${name}/${filename}`,sha256:semanticDigest(file,{legacy})});
63
72
  }
64
73
  }
65
74
  return rows.sort((a,b)=>compare(a.path,b.path));
66
75
  }
67
76
 
68
- export function verifyManifest(manifest,statusFile){
77
+ // Returns the recorded rows. A row also matches its legacy digest, so a manifest
78
+ // approved before the shared task grammar keeps matching the same bytes.
79
+ export function verifyManifest(manifest,statusFile,legacyManifest=null){
69
80
  const value=JSON.parse(new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(fs.readFileSync(statusFile)));
70
81
  if(!record(value))fail('status file root must be an object');
71
82
  if(!Array.isArray(value.specFiles)||!value.specFiles.length)fail('status file has no approved specFiles manifest');
@@ -78,7 +89,14 @@ export function verifyManifest(manifest,statusFile){
78
89
  seen.add(p);return {path:p,sha256:item.sha256};
79
90
  });
80
91
  if(value.status!=='approved')fail('status file must have status approved before manifest verification');
81
- if(JSON.stringify(rows)!==JSON.stringify(manifest))fail('approved spec manifest does not match current spec files');
92
+ const matches=rows.length===manifest.length&&rows.every((row,index)=>row.path===manifest[index].path
93
+ &&(row.sha256===manifest[index].sha256||legacyManifest?.[index]?.path===row.path&&row.sha256===legacyManifest[index].sha256));
94
+ if(!matches)fail('approved spec manifest does not match current spec files');
95
+ return rows;
96
+ }
97
+
98
+ export function verifyApprovedManifest(specsDir,statusFile){
99
+ return verifyManifest(buildManifest(specsDir),statusFile,buildManifest(specsDir,{legacy:true}));
82
100
  }
83
101
 
84
102
  // Resolve symlinks before '..', like pathlib.resolve, rather than normalizing
@@ -100,7 +118,7 @@ export function main(argv=process.argv.slice(2),{stdout=process.stdout,stderr=pr
100
118
  }
101
119
  if(specs===undefined)fail('invalid arguments');
102
120
  const specFiles=buildManifest(expand(specs));
103
- if(status!==undefined)verifyManifest(specFiles,expand(status));
121
+ if(status!==undefined)verifyManifest(specFiles,expand(status),buildManifest(expand(specs),{legacy:true}));
104
122
  stdout.write(JSON.stringify({schema_version:1,...(status!==undefined?{status:'matched'}:{}),specFiles})+'\n');return 0;
105
123
  }catch(error){stderr.write(`cm-spec-manifest: ${error.message}\n`);return 1;}
106
124
  }
@@ -1,6 +1,6 @@
1
1
  import test from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
- import {normalizeRuntimeMarks} from './cm-spec-manifest.mjs';
3
+ import {normalizeRuntimeMarks,normalizeRuntimeMarkBytes} from './cm-spec-manifest.mjs';
4
4
  test('shared normalization preserves declaration, filename, fence and byte boundaries',()=>{
5
5
  for(const [name,declaration,other] of [['tasks.md','T-A.1:','[AC-001]'],['requirements.md','[AC-A.1]','T-001:']]){
6
6
  const lines=[`- [x] ${declaration} 中文`,` -\t[X]\t${declaration} [CHANGED]`,
@@ -10,9 +10,13 @@ test('shared normalization preserves declaration, filename, fence and byte bound
10
10
  '```md',`- [x] ${declaration} fenced`,'```',
11
11
  '~~~~',`- [X] ${declaration} fenced`,'~~~~',`- [X] ${declaration} final`];
12
12
  for(const ending of ['\n','\r\n','\r']){
13
- const text=lines.join(ending),expected=[...lines];
14
- for(const i of [0,1,15])expected[i]=expected[i].replace(/\[[xX]\]/,'[ ]');
15
- assert.equal(normalizeRuntimeMarks(text,name),expected.join(ending));
13
+ const text=lines.join(ending),reset=indices=>{const expected=[...lines];
14
+ for(const i of indices)expected[i]=expected[i].replace(/\[[xX]\]/,'[ ]');return expected.join(ending);};
15
+ // tasks.md follows the shared declaration grammar: indented task lines are
16
+ // declarations (as admission always read them); requirements.md is unchanged.
17
+ assert.equal(normalizeRuntimeMarks(text,name),reset(name==='tasks.md'?[0,1,7,8,15]:[0,1,15]));
18
+ assert.equal(normalizeRuntimeMarks(text,name,{legacy:true}),reset([0,1,15]));
19
+ assert.equal(normalizeRuntimeMarkBytes(Buffer.from(text),name).toString(),normalizeRuntimeMarks(text,name));
16
20
  for(const otherName of ['design.md','test-cases.json','notes.md'])assert.equal(normalizeRuntimeMarks(text,otherName),text);
17
21
  }
18
22
  }
@@ -0,0 +1,138 @@
1
+ // #27 one tasks.md grammar for admission, cm-prd checks, N5 mark-done and the
2
+ // approval manifest; #28 one dependency rule for nextTask and --task.
3
+ import test,{after} from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {createHash} from 'node:crypto';
9
+ import {spawnSync} from 'node:child_process';
10
+ import {fileURLToPath} from 'node:url';
11
+ import {inspectCmAiAdmission,approveCmAiSpecs,parseFeatureTaskText} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
12
+ import {captureSpecificationMaterial} from '../runtime/js/cm-ai/specification-material.mjs';
13
+ import {checkPrdDraftMechanics} from '../runtime/js/cm-prd/self-check.mjs';
14
+ import {buildManifest} from './cm-spec-manifest.mjs';
15
+ import {parseTasks} from './cm-failover.mjs';
16
+
17
+ // N5 mark-done and admission may write run logs: keep them out of the invoking user's home.
18
+ const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-task-line-home-'));
19
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
20
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
21
+ after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
22
+ const scripts=fileURLToPath(new URL('.',import.meta.url));
23
+ const gate=path.join(scripts,'cm-task-gate.py'),admissionCli=path.join(scripts,'cm-ai-admission.mjs');
24
+ const oracle=path.join(scripts,'fixtures','spec-manifest-python-oracle.py');
25
+ const python=process.env.CM_PYTHON_BIN||'python3';
26
+
27
+ function fixture(tasks,run){
28
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-task-line-')));
29
+ const specs=path.join(root,'specs'),code=path.join(root,'code'),feature=path.join(specs,'1.login');
30
+ fs.mkdirSync(feature,{recursive:true});fs.mkdirSync(code);fs.writeFileSync(path.join(code,'README.md'),'existing\n');
31
+ fs.writeFileSync(path.join(feature,'requirements.md'),'# Requirements\n- [ ] [AC-001] login works\n');
32
+ fs.writeFileSync(path.join(feature,'design.md'),'# Design\n');
33
+ fs.writeFileSync(path.join(feature,'tasks.md'),tasks);
34
+ try{return run({root,specs,code,feature,tasksPath:path.join(feature,'tasks.md')});}
35
+ finally{fs.rmSync(root,{recursive:true,force:true});}
36
+ }
37
+ // The real N5 path: an approved legacy-unbound handoff/review pair, then the
38
+ // Python lock adapter's mark-done, which delegates the line edit to cm-task-gate.mjs.
39
+ function markDone({specs,tasksPath},task){
40
+ const reviews=path.join(specs,'.reviews');fs.mkdirSync(reviews,{recursive:true});
41
+ const handoff=path.join(reviews,`login-${task}-a1-handoff.json`);
42
+ fs.writeFileSync(handoff,JSON.stringify({schema_version:1,task_id:task,attempt:1,status:'ready_for_review',
43
+ changed_files:['src/login.ts'],verification:[{command:'npm test',status:'passed',evidence:'passed'}],
44
+ evidence:['src/login.ts'],blockers:[],scope_deviation:[]},null,2)+'\n');
45
+ const sha=createHash('sha256').update(fs.readFileSync(handoff)).digest('hex');
46
+ fs.writeFileSync(path.join(reviews,`login-${task}-r1.md`),`---\nat: 2026-09-28T07:00:00-07:00\nreviewer: codex-subagent\n`
47
+ +`independent: true\ntask: ${task}\nattempt: 1\nround: 1\nverdict: approved\nblocking_findings: 0\n`
48
+ +`handoff: ${path.basename(handoff)}\nhandoff_sha256: ${sha}\nscope:\n - src/login.ts\n---\n\nZero findings.\n`);
49
+ return spawnSync(python,[gate,'mark-done','--handoff',handoff,'--reviews-dir',reviews,'--feature','login',
50
+ '--task',task,'--tasks',tasksPath,'--allow-legacy-unbound'],{encoding:'utf8'});
51
+ }
52
+
53
+ for(const [label,line,description='实现登录'] of [
54
+ ['no colon','- [ ] T-001 实现登录'],
55
+ ['dash separator','- [ ] T-001 - 实现登录','- 实现登录'],
56
+ ['nested four-space item','- 阶段一\n - [ ] T-001: 实现登录'],
57
+ ['full-width colon','- [ ] T-001:实现登录'],
58
+ ])test(`${label}: a task admission selects stays approved after the real N5 mark-done`,()=>
59
+ fixture(`# tasks\n${line}\n- [ ] T-002: 退出登录\n\n- T-002 依赖 T-001\n`,f=>{
60
+ const approved=approveCmAiSpecs({specsDir:f.specs,codeProject:f.code,approvalResponse:'开始'});
61
+ assert.equal(approved.approveRefused,undefined);
62
+ const before=inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code});
63
+ assert.equal(before.state,'ready');assert.equal(before.nextTask.id,'T-001');
64
+ assert.equal(before.nextTask.description,description);
65
+ const marked=markDone(f,'T-001');
66
+ assert.equal(marked.status,0,marked.stderr);
67
+ assert.match(fs.readFileSync(f.tasksPath,'utf8'),/\[x\] T-001/);
68
+ const after=inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code});
69
+ assert.equal(after.reason,'task_selected',`admission after N5: ${after.state}/${after.reason}`);
70
+ assert.equal(after.nextTask.id,'T-002');
71
+ // The next task's material still binds the unchanged approval.
72
+ assert.equal(captureSpecificationMaterial({specsRoot:f.specs,feature:'1.login',taskId:'T-002'}).task.id,'T-002');
73
+ }));
74
+
75
+ test('a manifest approved by the pre-grammar rule keeps matching the same bytes',()=>
76
+ fixture('- [x] T-001 已完成且无冒号\n- [ ] T-002 待做\n',f=>{
77
+ // Legacy-shaped approval: the frozen pre-migration implementation wrote these rows.
78
+ const legacy=spawnSync(python,[oracle,f.specs],{encoding:'utf8'});
79
+ assert.equal(legacy.status,0,legacy.stderr);
80
+ const specFiles=JSON.parse(legacy.stdout).specFiles;
81
+ const tasksRow=row=>row.path==='1.login/tasks.md';
82
+ assert.notEqual(specFiles.find(tasksRow).sha256,buildManifest(f.specs).find(tasksRow).sha256,
83
+ 'fixture must exercise a digest the new grammar computes differently');
84
+ fs.writeFileSync(path.join(f.specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login'],specFiles}));
85
+ const admission=inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code});
86
+ assert.equal(admission.state,'ready');assert.equal(admission.nextTask.id,'T-002');
87
+ const material=captureSpecificationMaterial({specsRoot:f.specs,feature:'1.login',taskId:'T-002'});
88
+ assert.deepEqual(material.sources,specFiles,'material keeps the approved digests');
89
+ const cli=spawnSync(process.execPath,[path.join(scripts,'cm-spec-manifest.mjs'),f.specs,'--status-file',
90
+ path.join(f.specs,'.cm-specs-status')],{encoding:'utf8'});
91
+ assert.equal(cli.status,0,cli.stderr);
92
+ // Real drift still fails closed.
93
+ fs.appendFileSync(f.tasksPath,'- [ ] T-003 新增\n');
94
+ assert.equal(inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code}).reason,'spec_drift');
95
+ }));
96
+
97
+ test('fenced examples are never declarations for admission, cm-prd, failover or N5',()=>
98
+ fixture('- [ ] T-001: real\n```md\n- [ ] T-001: example copy\n- [x] T-009: example\n```\n',f=>{
99
+ const parsed=parseFeatureTaskText(fs.readFileSync(f.tasksPath,'utf8'));
100
+ assert.deepEqual(parsed.tasks.map(task=>task.id),['T-001']);
101
+ assert.deepEqual(parseTasks(fs.readFileSync(f.tasksPath,'utf8')).map(task=>task.id),['T-001']);
102
+ approveCmAiSpecs({specsDir:f.specs,codeProject:f.code,approvalResponse:'开始'});
103
+ const marked=markDone(f,'T-001');assert.equal(marked.status,0,marked.stderr);
104
+ assert.equal(fs.readFileSync(f.tasksPath,'utf8'),'- [x] T-001: real\n```md\n- [ ] T-001: example copy\n- [x] T-009: example\n```\n');
105
+ assert.equal(inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code}).state,'complete');
106
+ }));
107
+
108
+ test('cm-prd self-check reads the same declarations as admission',()=>{
109
+ const contract={schemaVersion:'1.0',feature:'sample',cases:[{id:'TC-001',origin:'user',kind:'logic',blocking:true,
110
+ acIds:['AC-001'],taskIds:['T-001'],title:'Check',preconditions:[],steps:['Do'],expected:['Works'],cleanup:[]}]};
111
+ for(const tasks of ['- [ ] T-001:全角冒号','- [ ] T-001 无冒号','- 父项\n - [ ] T-001: 嵌套']){
112
+ const report=checkPrdDraftMechanics({draftDigest:'a'.repeat(64),features:[{directory:'1.sample',name:'sample',documents:[
113
+ {path:'requirements.md',content:'- [ ] [AC-001] Works.'},{path:'tasks.md',content:tasks},
114
+ {path:'test-cases.json',content:JSON.stringify(contract)}]}]});
115
+ assert.equal(report.status,'mechanical_subset_passed',`${tasks}: ${JSON.stringify(report.findings)}`);
116
+ assert.deepEqual(parseFeatureTaskText(tasks).tasks.map(task=>task.id),['T-001']);
117
+ }
118
+ });
119
+
120
+ test('#28 --task on a task whose prerequisite was DROPPED matches nextTask semantics',()=>
121
+ fixture('- [x] T-001: a\n- [ ] ~~T-002: b~~ `[DROPPED v2]`\n- [ ] T-003: c\n- [ ] T-004: d\n\n- T-003 依赖 T-002\n- T-004 依赖 T-003\n',f=>{
122
+ approveCmAiSpecs({specsDir:f.specs,codeProject:f.code,approvalResponse:'开始'});
123
+ const admission=inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code});
124
+ assert.equal(admission.nextTask.id,'T-003');
125
+ assert.deepEqual(admission.eligibleTasks.map(task=>task.id),['T-003']);
126
+ const print=task=>spawnSync(process.execPath,[admissionCli,'--specs-dir',f.specs,'--code-project',f.code,
127
+ '--print-run-definition','--scope','src/a.js','--task',task],{encoding:'utf8'});
128
+ const selected=print('T-003');
129
+ assert.equal(selected.status,0,selected.stderr);
130
+ assert.deepEqual(JSON.parse(selected.stdout).taskSelection,{version:1,taskId:'T-003'});
131
+ // A real mismatch names why instead of a bare code.
132
+ for(const [task,reason] of [['T-004',/T-004 依赖的 T-003 尚未完成/],['T-001',/T-001 已勾选完成/],
133
+ ['T-002',/T-002 已标记 DROPPED/],['T-404',/没有任务 T-404/]]){
134
+ const refused=print(task);assert.equal(refused.status,1);
135
+ const error=JSON.parse(refused.stderr).error;
136
+ assert.equal(error.code,'task_selection_mismatch');assert.match(error.reason,reason);
137
+ }
138
+ }));
@@ -82,12 +82,23 @@ test('revision digest is optional, validated, and retained by shared status stor
82
82
  assert.equal(Object.hasOwn(f.value(),'revisionDigest'),false);
83
83
  });
84
84
 
85
+ test('task grammar is only version 2 and is carried through awaiting review',t=>{
86
+ const f=fixture(t),expected=f.initial(),approved={...expected,status:'approved',approval:{response:'开始',at:expected.at}};
87
+ assert.deepEqual(writeSpecsStatus(f.specs,{...approved,taskGrammar:2}),{...approved,taskGrammar:2});
88
+ assert.equal(readSpecsStatus(f.specs).value.taskGrammar,2);
89
+ assert.deepEqual(writeSpecsStatus(f.specs,{...expected,taskGrammar:2}),{...expected,taskGrammar:2});
90
+ for(const invalid of [{...approved,taskGrammar:1},{...approved,taskGrammar:'2'},{...expected,taskGrammar:3}])
91
+ assert.throws(()=>writeSpecsStatus(f.specs,invalid),/spec_status_invalid/);
92
+ });
93
+
85
94
  test('--approve writes only the three permitted reasons with explicit human input and reruns admission',t=>{
86
95
  const f=fixture(t),approve=['--approve','--approval-response','开始'];
87
96
  f.raw(f.initial());
88
97
  assert.equal(f.run('--approval-response','开始').result.reason,'approval_write_required');
89
98
  let result=f.run(...approve);assert.equal(result.exit,0);assert.equal(result.result.state,'ready');
90
- assert.deepEqual(Object.keys(f.value()),keys);assert.equal(f.value().approval.response,'开始');
99
+ // A new approval binds the shared tasks.md grammar (spec-task-line.mjs).
100
+ assert.deepEqual(Object.keys(f.value()),[...keys,'taskGrammar']);assert.equal(f.value().taskGrammar,2);
101
+ assert.equal(f.value().approval.response,'开始');
91
102
  assert.equal(f.value().approval.at,f.value().at);
92
103
  feature(f.specs,'2.appendix');
93
104
  assert.equal(f.run('--approval-response','开始').result.reason,'spec_features_changed');