@aibyzero/cm-workflow 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +38 -0
  4. package/README.md +15 -1
  5. package/VERSION +1 -1
  6. package/docs/architecture.md +3 -0
  7. package/docs/cm-acceptance-completion.md +185 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +1 -1
  10. package/docs/proposals/spec-amendment-tiers.md +100 -0
  11. package/package.json +1 -1
  12. package/runtime/js/acceptance-language.mjs +32 -0
  13. package/runtime/js/autonomy.mjs +168 -3
  14. package/runtime/js/check-coverage.mjs +130 -0
  15. package/runtime/js/cm-ai/acceptance-contract.mjs +257 -0
  16. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +49 -8
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  21. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  22. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  24. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  25. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  27. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  28. package/runtime/js/cm-ai/drive-core.mjs +15 -4
  29. package/runtime/js/cm-ai/durable-runner-state.mjs +10 -6
  30. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  32. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  33. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  34. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  35. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  36. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  37. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  38. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  39. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  40. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  41. package/runtime/js/cm-ai/review-package.mjs +22 -8
  42. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  43. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  44. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  45. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  46. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  47. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  48. package/runtime/js/cm-ai/task-runner.mjs +64 -22
  49. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  50. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  51. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  52. package/runtime/js/cm-prd/change.mjs +52 -5
  53. package/runtime/js/cm-prd/self-check.mjs +36 -6
  54. package/runtime/js/cm-prd/session.mjs +8 -3
  55. package/runtime/js/cm-prd/summary.mjs +5 -0
  56. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  57. package/runtime/js/node-test-selection.mjs +38 -0
  58. package/runtime/js/run-analysis.mjs +153 -0
  59. package/runtime/js/session-boundary.mjs +17 -5
  60. package/runtime/js/session-handoff.mjs +5 -2
  61. package/runtime/js/task-scope.mjs +4 -1
  62. package/runtime/test-contract.md +1 -0
  63. package/scripts/cm-acceptance-preview.mjs +26 -0
  64. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  65. package/scripts/cm-ai-acceptance-contract.test.mjs +195 -0
  66. package/scripts/cm-ai-admission.mjs +8 -2
  67. package/scripts/cm-ai-admission.test.mjs +20 -4
  68. package/scripts/cm-ai-blockage.test.mjs +120 -0
  69. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  70. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  71. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  72. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  73. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  74. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  75. package/scripts/cm-ai-drive.mjs +18 -11
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  77. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  78. package/scripts/cm-ai-progress.test.mjs +7 -0
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  80. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  81. package/scripts/cm-ai-run.test.mjs +23 -1
  82. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  83. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  84. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  85. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  86. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  87. package/scripts/cm-autonomy-review-r1.test.mjs +142 -0
  88. package/scripts/cm-autonomy.mjs +3 -1
  89. package/scripts/cm-autonomy.test.mjs +10 -9
  90. package/scripts/cm-check-runtime.sh +5 -2
  91. package/scripts/cm-delivery-evidence.mjs +59 -0
  92. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  93. package/scripts/cm-drive-liveness.test.mjs +14 -0
  94. package/scripts/cm-driver-light-import.test.mjs +32 -0
  95. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  96. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  97. package/scripts/cm-journal-limit.test.mjs +69 -0
  98. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  99. package/scripts/cm-node-test-selection.test.mjs +108 -0
  100. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  101. package/scripts/cm-prd-completion.test.mjs +49 -0
  102. package/scripts/cm-prd-drive.mjs +1 -1
  103. package/scripts/cm-prd-host.mjs +3 -1
  104. package/scripts/cm-prd-host.test.mjs +19 -2
  105. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  106. package/scripts/cm-prd-self-check.test.mjs +24 -1
  107. package/scripts/cm-prd-summary.test.mjs +25 -4
  108. package/scripts/cm-review-inventory.test.mjs +25 -6
  109. package/scripts/cm-run-analysis.mjs +21 -0
  110. package/scripts/cm-run-analysis.test.mjs +120 -0
  111. package/scripts/cm-spec-amend.mjs +68 -0
  112. package/scripts/cm-spec-amend.test.mjs +510 -0
  113. package/scripts/cm-specs-status.test.mjs +6 -0
  114. package/scripts/cm-start-check.mjs +140 -53
  115. package/scripts/cm-start-check.test.mjs +139 -1
  116. package/scripts/cm-task-scope.test.mjs +3 -2
  117. package/scripts/cm-usage-report.py +8 -3
  118. package/scripts/cm019-r1-contract.test.mjs +137 -0
  119. package/scripts/cm019-review-gates.test.mjs +97 -0
  120. package/scripts/test-journal-limit-1mib.mjs +4 -0
  121. package/scripts/validate-public-repo.py +4 -0
  122. package/skills/cm-ai/references/N1-init.md +23 -1
  123. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  124. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  125. package/skills/cm-ai/references/js-host.md +7 -2
  126. package/skills/cm-prd/references/js-change-recovery.md +2 -1
  127. package/skills/cm-prd/references/js-host.md +1 -0
@@ -0,0 +1,203 @@
1
+ // Read-only preview of the exact contract a new run would freeze. Not approval.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {TextDecoder} from 'node:util';
5
+ import {createHash} from 'node:crypto';
6
+ import {buildManifest,normalizeRuntimeMarks,verifyApprovedManifest} from '../../../scripts/cm-spec-manifest.mjs';
7
+ import {buildTaskAcceptanceContract} from '../cm-ai/specification-material.mjs';
8
+ import {parseFeatureTaskText,inspectTaskGrammarTransition} from '../cm-ai/cm-ai-admission.mjs';
9
+ import {TASK_GRAMMAR,SHARED_TASK_GRAMMAR,LEGACY_TASK_GRAMMAR,recordedTaskGrammar,taskLines} from '../spec-task-line.mjs';
10
+ import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
11
+ import {digest,freeze,json,need} from '../cm-ai/effect-contract.mjs';
12
+
13
+ const decode=bytes=>new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);
14
+ const code=error=>/^[a-z][a-z0-9_]{0,95}$/.test(error?.code??'')?error.code:'acceptance_preview_invalid';
15
+ const filenames=['requirements.md','design.md','tasks.md','test-cases.json'];
16
+ const featureName=value=>typeof value==='string'&&/^\d+\.[^/\\\x00-\x1f]+$/.test(value);
17
+ const sourceId=item=>item.id.replace(/:[a-f0-9]{16}:\d+$/,'');
18
+ const unique=values=>[...new Set(values)];
19
+ const sha=value=>createHash('sha256').update(value).digest('hex');
20
+
21
+ export function previewTaskGrammar(statusBytes,fallback=TASK_GRAMMAR){
22
+ need([1,2,TASK_GRAMMAR].includes(fallback),'acceptance_preview_grammar_invalid');
23
+ if(statusBytes===null)return fallback;
24
+ const status=JSON.parse(decode(statusBytes));
25
+ need(status&&['approved','awaiting_review'].includes(status.status),'acceptance_preview_status_invalid');
26
+ need(!Object.hasOwn(status,'taskGrammar')||[2,TASK_GRAMMAR].includes(status.taskGrammar),'acceptance_preview_grammar_invalid');
27
+ return recordedTaskGrammar(status.taskGrammar);
28
+ }
29
+
30
+ function sourceLocations(feature,texts,contract){
31
+ const lines=Object.fromEntries(['tasks.md','requirements.md'].map(file=>[file,
32
+ normalizeRuntimeMarks(texts[file],file).split(/\r?\n/)]));
33
+ const cases=texts['test-cases.json']===undefined?[]:JSON.parse(texts['test-cases.json']).cases;
34
+ return Object.fromEntries(contract.obligations.map(item=>{
35
+ const source=sourceId(item),file=source.startsWith('task:')?'tasks.md':'requirements.md';
36
+ let locations=[];
37
+ if(source.startsWith('TC-')){
38
+ const [id,field]=source.split(':');
39
+ cases.forEach((entry,index)=>{
40
+ if(entry.id!==id)return;
41
+ if(field)(entry[field]??[]).forEach((text,part)=>{
42
+ if(`${field}: ${text}`===item.requirement)locations.push({path:`${feature}/test-cases.json`,pointer:`/cases/${index}/${field}/${part}`});
43
+ });
44
+ else locations.push({path:`${feature}/test-cases.json`,pointer:`/cases/${index}/title`});
45
+ });
46
+ }else lines[file].forEach((line,index)=>{
47
+ if(line.trim()===item.requirement)locations.push({path:`${feature}/${file}`,line:index+1});
48
+ });
49
+ return [item.id,locations];
50
+ }));
51
+ }
52
+
53
+ function taskPreview(feature,texts,task,grammar){
54
+ const taskLocation={path:`${feature}/tasks.md`,line:taskLines(texts['tasks.md'],{grammar})
55
+ .find(line=>line.declaration?.id===task.id).index+1};
56
+ try{
57
+ const contract=buildTaskAcceptanceContract({texts,taskId:task.id,grammar});
58
+ if(contract===null)return {taskId:task.id,description:task.description,status:'ready',protection:'legacy_unprotected',location:taskLocation,
59
+ contract:null,contractDigest:null,locations:{},issues:[],acceptanceCriteria:[],testCases:[],humanReviewIds:[]};
60
+ const locations=sourceLocations(feature,texts,contract);
61
+ const issues=contract.unresolved.map(message=>{
62
+ const reference=/^(AC-\d+|TC-\d+):/.exec(message)?.[1];
63
+ const related=contract.obligations.filter(item=>message.startsWith(`${sourceId(item)}:`)
64
+ ||reference&&item.requirement.includes(reference));
65
+ const at=related.flatMap(item=>locations[item.id]);
66
+ return {message,locations:at.length?at:[taskLocation,{path:`${feature}/requirements.md`}],
67
+ locationKind:at.length?'matching_source':'related_source'};
68
+ });
69
+ return {taskId:task.id,description:task.description,status:issues.length?'needs_clarification':'ready',
70
+ location:taskLocation,contract,contractDigest:digest(contract),locations,issues,
71
+ acceptanceCriteria:unique(contract.obligations.map(sourceId).filter(id=>/^AC-\d+$/.test(id))),
72
+ testCases:unique(contract.obligations.map(sourceId).filter(id=>/^TC-/.test(id)).map(id=>id.split(':')[0])),
73
+ humanReviewIds:contract.obligations.filter(item=>['review','browser','device'].includes(item.evidenceType)).map(item=>item.id)};
74
+ }catch(error){return {taskId:task.id,description:task.description,status:'needs_clarification',location:taskLocation,
75
+ contract:null,issues:[{message:code(error),locations:[taskLocation],locationKind:'related_source'}]};}
76
+ }
77
+
78
+ // Documents are the actual saved bytes or the immutable draft snapshot supplied
79
+ // by the PRD owner. No model response is used to construct the preview.
80
+ export function buildAcceptancePreview({features,taskGrammar=TASK_GRAMMAR,taskId=null,
81
+ featureInventory=features?.map(feature=>feature.directory),approvalTransition=false}){
82
+ need(Array.isArray(features)&&features.length>0&&features.length<=100,'acceptance_preview_scope_invalid');
83
+ need([1,2,TASK_GRAMMAR].includes(taskGrammar),'acceptance_preview_grammar_invalid');
84
+ need(typeof approvalTransition==='boolean'&&Array.isArray(featureInventory)&&featureInventory.length<=100
85
+ &&featureInventory.every(featureName)&&new Set(featureInventory).size===featureInventory.length
86
+ &&features.every(feature=>featureInventory.includes(feature.directory)),'acceptance_preview_scope_invalid');
87
+ need(taskId===null||/^T-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(taskId)&&features.length===1,'acceptance_preview_task_invalid');
88
+ const seen=new Set();
89
+ const result=features.map(feature=>{
90
+ need(featureName(feature.directory)&&!seen.has(feature.directory),'acceptance_preview_scope_invalid');seen.add(feature.directory);
91
+ need(Array.isArray(feature.documents),'acceptance_preview_documents_invalid');
92
+ const texts=Object.fromEntries(feature.documents.map(doc=>[doc.path,doc.content]));
93
+ need(Object.keys(texts).length===feature.documents.length&&Object.keys(texts).every(name=>filenames.includes(name))
94
+ &&filenames.slice(0,3).every(name=>typeof texts[name]==='string'),'acceptance_preview_documents_invalid');
95
+ const parsed=parseFeatureTaskText(texts['tasks.md'],{allowDependencyPunctuation:true,grammar:taskGrammar});
96
+ if(parsed.error)return {feature:feature.directory,status:'needs_clarification',tasks:[],issues:[{
97
+ message:parsed.error,locations:[{path:`${feature.directory}/tasks.md`,line:parsed.detail?.line??1}],locationKind:'matching_source'}]};
98
+ const selected=parsed.tasks.filter(task=>!task.dropped&&(taskId===null||task.id===taskId));
99
+ need(taskId===null||selected.length===1,'acceptance_preview_task_missing');
100
+ const tasks=selected.map(task=>taskPreview(feature.directory,texts,task,taskGrammar));
101
+ const issues=tasks.length?[]:[{message:'acceptance_preview_no_active_tasks',locations:[{path:`${feature.directory}/tasks.md`}],locationKind:'related_source'}];
102
+ if(approvalTransition&&taskGrammar===LEGACY_TASK_GRAMMAR){
103
+ const transition=inspectTaskGrammarTransition(texts['tasks.md'],{grammar:SHARED_TASK_GRAMMAR,fromLegacy:true});
104
+ if(transition.parsed.error||transition.differing.length)issues.push({message:'task_grammar_conflict',
105
+ locations:(transition.parsed.error?[transition.parsed.detail]:transition.differing).map(item=>({
106
+ path:`${feature.directory}/tasks.md`,line:item.line})),locationKind:'matching_source',
107
+ detail:'Explicit approval would change the task declaration set; resolve the original task lines before approval.'});
108
+ }
109
+ return {feature:feature.directory,status:issues.length||tasks.some(task=>task.status!=='ready')?'needs_clarification':'ready',tasks,issues};
110
+ });
111
+ return freeze(json({version:1,status:result.every(feature=>feature.status==='ready')?'ready':'needs_clarification',
112
+ taskGrammar,approvalTransition,featureInventory:[...featureInventory].sort(),
113
+ sourceDigest:digest({features,taskGrammar,featureInventory:[...featureInventory].sort(),approvalTransition}),
114
+ sourceFiles:features.flatMap(feature=>feature.documents.map(doc=>({
115
+ path:`${feature.directory}/${doc.path}`,sha256:sha(doc.content)}))),
116
+ scope:{features:features.map(feature=>feature.directory),taskId},features:result,
117
+ approvalAuthorized:false,executionAuthorized:false,meaning:'Captured source snapshot, requirement mapping only; no tests executed, no approval granted.'},2*1024*1024));
118
+ }
119
+
120
+ // A saved summary remains historical. The status response separately projects
121
+ // whether its preview still matches disk; it never rewrites the saved digest.
122
+ export function currentAcceptancePreview({specs,preview}){
123
+ if(!preview||preview.status==='unavailable')return preview??null;
124
+ try{
125
+ need(path.isAbsolute(specs)&&fs.realpathSync(specs)===specs,'acceptance_preview_root_invalid');
126
+ need(Array.isArray(preview.featureInventory),'acceptance_preview_inventory_missing');
127
+ const inventory=unique(buildManifest(specs).map(row=>row.path.split('/')[0])).sort();
128
+ const expected=new Map(preview.sourceFiles.map(row=>[row.path,row.sha256]));
129
+ const current=()=>preview.scope.features.flatMap(feature=>filenames.flatMap(file=>{
130
+ const name=`${feature}/${file}`,bytes=readCmInitSource(specs,name);
131
+ return bytes===null?[]:[{path:name,sha256:sha(bytes)}];
132
+ }));
133
+ const rows=current(),same=rows.length===expected.size&&rows.every(row=>expected.get(row.path)===row.sha256);
134
+ const statusBytes=readCmInitSource(specs,'.cm-specs-status');
135
+ const grammar=previewTaskGrammar(statusBytes,preview.taskGrammar);
136
+ need(digest(current())===digest(rows)
137
+ &&digest(unique(buildManifest(specs).map(row=>row.path.split('/')[0])).sort())===digest(inventory)
138
+ &&(readCmInitSource(specs,'.cm-specs-status')?.toString('base64')??null)===(statusBytes?.toString('base64')??null),
139
+ 'acceptance_preview_sources_changed');
140
+ if(!same||grammar!==preview.taskGrammar||digest(inventory)!==digest(preview.featureInventory))return freeze({version:1,status:'stale',reason:'acceptance_preview_sources_changed',
141
+ sourceDigest:preview.sourceDigest,scope:preview.scope,approvalAuthorized:false,executionAuthorized:false,
142
+ next:'Rebuild the preview from current specifications; the saved summary is historical.'});
143
+ return preview;
144
+ }catch(error){return {version:1,status:'unavailable',reason:code(error),approvalAuthorized:false,executionAuthorized:false};}
145
+ }
146
+
147
+ // Presentation failures stay visible without changing old summary/publication
148
+ // contracts or blocking replay of already prepared historical summaries.
149
+ export function summaryAcceptancePreview({documents,currentFeatures,statusBytes,taskGrammar}){
150
+ try{
151
+ const preview=buildAcceptancePreview({features:documents.filter(feature=>currentFeatures===undefined||currentFeatures.includes(feature.directory)),
152
+ taskGrammar:previewTaskGrammar(statusBytes,taskGrammar),featureInventory:documents.map(feature=>feature.directory),approvalTransition:true});
153
+ need(Buffer.byteLength(JSON.stringify(preview))<=256*1024,'acceptance_preview_limit');return preview;
154
+ }catch(error){return {version:1,status:'unavailable',reason:code(error),approvalAuthorized:false,executionAuthorized:false,
155
+ next:'Run the read-only acceptance preview for one feature/task; original approval and execution gates remain required.'};}
156
+ }
157
+
158
+ export function inspectAcceptancePreview({specs,feature=null,taskId=null,taskGrammar=TASK_GRAMMAR}){
159
+ need(typeof specs==='string'&&path.isAbsolute(specs)&&fs.realpathSync(specs)===specs,'acceptance_preview_root_invalid');
160
+ const statusBytes=readCmInitSource(specs,'.cm-specs-status'),grammar=previewTaskGrammar(statusBytes,taskGrammar);
161
+ const manifest=buildManifest(specs),names=unique(manifest.map(item=>item.path.split('/')[0]));
162
+ need(names.length<=100,'acceptance_preview_scope_invalid');
163
+ need(feature===null||names.includes(feature),'acceptance_preview_feature_missing');
164
+ const sourceStatus=statusBytes===null?'draft':JSON.parse(decode(statusBytes)).status;
165
+ if(sourceStatus==='approved'){
166
+ try{
167
+ const status=JSON.parse(decode(statusBytes));
168
+ need(Array.isArray(status.features)&&digest([...status.features].sort())===digest([...names].sort()));
169
+ verifyApprovedManifest(specs,path.join(specs,'.cm-specs-status'));
170
+ }
171
+ catch{need(false,'acceptance_preview_approved_sources_changed');}
172
+ }
173
+ let sourceBytes=0;
174
+ const snapshots=new Map(),features=names.filter(name=>feature===null||name===feature).map(directory=>({directory,
175
+ documents:manifest.filter(item=>item.path.startsWith(directory+'/')).map(item=>{
176
+ const bytes=readCmInitSource(specs,item.path);need(bytes!==null,'acceptance_preview_source_missing');
177
+ sourceBytes+=bytes.length;need(sourceBytes<=8*1024*1024,'acceptance_preview_limit');snapshots.set(item.path,bytes);
178
+ return {path:item.path.slice(directory.length+1),content:decode(bytes)};
179
+ })}));
180
+ const result=buildAcceptancePreview({features,taskGrammar:grammar,taskId,featureInventory:names,
181
+ approvalTransition:sourceStatus==='awaiting_review'});
182
+ need([...snapshots].every(([file,bytes])=>readCmInitSource(specs,file)?.equals(bytes))
183
+ &&(readCmInitSource(specs,'.cm-specs-status')?.toString('base64')??null)===(statusBytes?.toString('base64')??null)
184
+ &&digest(buildManifest(specs))===digest(manifest),'acceptance_preview_sources_changed');
185
+ return freeze({...result,sourceStatus});
186
+ }
187
+
188
+ const at=location=>`${location.path}${location.line?`:${location.line}`:location.pointer?`#${location.pointer}`:''}`;
189
+ export function acceptancePreviewLines(preview){
190
+ const lines=[`验收预览:${preview.status};只检查要求映射,未执行测试,未授予批准。`];
191
+ for(const feature of preview.features??[]){
192
+ lines.push(`功能 ${feature.feature}:${feature.status}`);
193
+ for(const issue of feature.issues)lines.push(` 待澄清:${issue.message}(${issue.locations.map(at).join('、')})`);
194
+ for(const task of feature.tasks){
195
+ lines.push(` ${task.taskId}:${task.status}(${at(task.location)})`);
196
+ for(const item of task.contract?.obligations??[])lines.push(` ${item.id} [${item.evidenceType}/${item.environment}${item.run?`/${item.run}`:''}] ${item.requirement}(${task.locations[item.id].map(at).join('、')})`);
197
+ for(const test of task.contract?.requiredTests??[])lines.push(` 必跑测试:${test}`);
198
+ for(const command of task.contract?.requiredCommands??[])lines.push(` 必跑命令 argv:${JSON.stringify(command)}`);
199
+ for(const issue of task.issues)lines.push(` 待澄清:${issue.message}(${issue.locations.map(at).join('、')})`);
200
+ }
201
+ }
202
+ return lines;
203
+ }
@@ -2,6 +2,7 @@ import {assertPrdBatchActive} from './inputs-replaced.mjs';
2
2
  // Original C1–C8, also used for explicitly confirmed revisions of saved drafts.
3
3
  // Proposals are not writes; old review evidence and completed work stay history.
4
4
  import fs from 'node:fs';
5
+ import {summaryAcceptancePreview} from './acceptance-preview.mjs';
5
6
  import {prdSelfCheckRevisionPath} from './self-check-revision.mjs';
6
7
  import path from 'node:path';
7
8
  import {createHash} from 'node:crypto';
@@ -14,6 +15,7 @@ import {prdTreeFileDigest} from './tree-digest.mjs';
14
15
  import {writeImmutableWorkflowFile} from '../cm-ai/review-evidence-file.mjs';
15
16
  import {need,json,shape,digest} from '../cm-ai/effect-contract.mjs';
16
17
  import {inspectPrdDraft} from './draft.mjs';
18
+ import {prdDraftJson,PRD_DRAFT_LIMIT} from './validation-reason.mjs';
17
19
  import {checkPrdDraftMechanics,inspectPrdContextCheck,PRD_SELF_CHECK_RULES} from './self-check.mjs';
18
20
  import {recordPrdTaskScopes,approvedScopeExemptions,prdTaskScopeRecords} from './task-scope-record.mjs';
19
21
  import {replaceSessionFile} from './session.mjs';
@@ -87,7 +89,37 @@ function approvedGrammar(before){
87
89
  function sourceLines(source){return specLines(source).map(line=>line.body);}
88
90
  function userCases(files){return Object.entries(files).filter(([file])=>file.endsWith('/test-cases.json'))
89
91
  .flatMap(([file,content])=>JSON.parse(content).cases.filter(c=>c.origin==='user').map(c=>({feature:file.split('/')[0],value:c})));}
90
- export function inspectPrdChangeProposal(before,raw,selected,config,{rules=PRD_SELF_CHECK_RULES}={}){
92
+ // change_tasks 回包可以省略未改动的文档:已有 feature 省略的 requirements.md/design.md 等于需求、设计阶段已接受的原字节,
93
+ // 省略的 tasks.md 等于原稿,testCasesReason 为 null 时省略的 test-cases.json 也等于原稿;这里按原稿顺序补回,
94
+ // 64 KiB 上限只算实际回的文档(同 draft.mjs 的 withAcceptedPrdDocuments)。否则四件套超过 64 KiB 的 feature
95
+ // 连只改用例格式的变更都提交不进来(wue 8.todo-inbox 约 94 KB,2026-11-14)。省略过去本就是无效回包
96
+ // (prd_draft_triad_missing / prd_draft_cases_reason_missing),所以这层含义不改变任何原本合法的回包;
97
+ // 要删除用例合同仍须写非 null 的 testCasesReason,不会被补回。新 feature 不补,照旧要求完整。
98
+ export function withUnchangedPrdChangeDocuments(raw,before,parts=null){
99
+ if(raw?.status!=='draft'||!Array.isArray(raw.features))return {reply:raw,limit:PRD_DRAFT_LIMIT};
100
+ let restored=0;
101
+ const features=raw.features.map(feature=>{
102
+ if(!feature||typeof feature!=='object'||!before.directories.includes(feature.directory)||!Array.isArray(feature.documents)
103
+ ||new Set(feature.documents.map(doc=>doc?.path)).size!==feature.documents.length)return feature;
104
+ const accepted=parts?.features?.find(item=>item.directory===feature.directory)?.documents??[];
105
+ const original=file=>accepted.find(doc=>doc.path===file)?.content??before.files[`${feature.directory}/${file}`];
106
+ const documents=[];
107
+ for(const file of ['requirements.md','design.md','tasks.md','test-cases.json']){
108
+ const given=feature.documents.find(doc=>doc?.path===file);
109
+ if(given){documents.push(given);continue;}
110
+ if(file==='test-cases.json'&&feature.testCasesReason!==null)continue;
111
+ const content=original(file);
112
+ if(typeof content!=='string')continue;
113
+ documents.push({path:file,content});restored+=Buffer.byteLength(JSON.stringify({path:file,content}));
114
+ }
115
+ documents.push(...feature.documents.filter(doc=>!documents.includes(doc)));
116
+ return {...feature,documents};
117
+ });
118
+ return {reply:{...raw,features},limit:PRD_DRAFT_LIMIT+restored};
119
+ }
120
+ export function inspectPrdChangeProposal(before,sent,selected,config,{rules=PRD_SELF_CHECK_RULES,parts=null}={}){
121
+ prdDraftJson(sent);
122
+ const {reply:raw,limit}=withUnchangedPrdChangeDocuments(sent,before,parts);
91
123
  const grammar=approvedGrammar(before);
92
124
  shape(raw,['status','summary','features','removed']);need(raw.status==='draft'&&text(raw.summary)&&Array.isArray(raw.features)
93
125
  &&Array.isArray(raw.removed)&&new Set(raw.removed).size===raw.removed.length,'prd_change_proposal_invalid');
@@ -101,7 +133,7 @@ export function inspectPrdChangeProposal(before,raw,selected,config,{rules=PRD_S
101
133
  const inspected=inspectPrdDraft({status:'draft',summary:raw.summary,features:[{name:feature.directory.replace(/^\d+\./,''),
102
134
  documents:feature.documents,testCasesReason:feature.testCasesReason}]},
103
135
  {nextIndex:Number(feature.directory.split('.')[0]),generateCases:feature.documents.some(doc=>doc.path==='test-cases.json')||config.policies.generate_cases,
104
- userCasesProvided:false}).features[0];
136
+ userCasesProvided:false,limit}).features[0];
105
137
  if(!config.policies.generate_cases){
106
138
  const contract=inspected.documents.find(doc=>doc.path==='test-cases.json');
107
139
  const prior=JSON.parse(before.files[`${feature.directory}/test-cases.json`]??'{"cases":[]}').cases;
@@ -166,7 +198,22 @@ export function createPrdChange({admission,runtime,call,restored=null,selected=[
166
198
  reference:path.join(admission.skillDir,'references/change-mode.md')},signal);
167
199
  };
168
200
  return {
169
- status:()=>json({...state,mode:'change',completionAuthorized:false},4*1024*1024),
201
+ status:()=>{
202
+ let acceptancePreview=null;
203
+ if(state.stage==='change_confirmation'&&state.proposal){
204
+ try{
205
+ current();
206
+ const documents=[...state.before.directories.filter(directory=>!state.selected.includes(directory)).map(directory=>({directory,
207
+ documents:names.filter(name=>state.before.files[`${directory}/${name}`]!==undefined).map(name=>({path:name,content:state.before.files[`${directory}/${name}`]}))})),...state.proposal.features];
208
+ acceptancePreview={...summaryAcceptancePreview({documents,currentFeatures:state.proposal.features.map(feature=>feature.directory),
209
+ statusBytes:state.before.status===null?null:Buffer.from(state.before.status),taskGrammar:approvedGrammar(state.before)}),
210
+ proposalDigest:state.proposal.proposalDigest,sourceKind:'proposed_documents'};
211
+ current();
212
+ }catch(error){acceptancePreview={version:1,status:'stale',reason:'prd_change_inputs_changed',
213
+ proposalDigest:state.proposal.proposalDigest,approvalAuthorized:false,executionAuthorized:false};}
214
+ }
215
+ return json({...state,mode:'change',completionAuthorized:false,...(acceptancePreview?{acceptancePreview}:{})},4*1024*1024);
216
+ },
170
217
  checkpoint:()=>json(state,4*1024*1024),
171
218
  cancel(){state.stage='cancelled';},
172
219
  async advance(answer,signal){
@@ -194,13 +241,13 @@ export function createPrdChange({admission,runtime,call,restored=null,selected=[
194
241
  messages:state.messages,parts:state.parts,previousProposal:state.proposal,contextCheck:state.contextCheck,text:answer,
195
242
  generateCases:config.policies.generate_cases,userCases:state.userCases,
196
243
  instructions:phase==='change_tasks'?
197
- 'C7/C7.5: return {status:draft,summary,features:[{directory,documents:[{path,content}],testCasesReason}],removed:[directory]}. Include complete triads/optional test contracts for the exact selected plus explicitly proposed new features. Preserve previous requirements/design bytes and inventory from parts. Retain completed task lines EXACTLY; preserve task IDs, mark changed pending CHANGED, obsolete DROPPED, added NEW. Append version rows to changed documents. Preserve unaffected/user cases; changes to user cases require separate explicit human consent. No writes, review/provider calls or approval.':
244
+ 'C7/C7.5: return {status:draft,summary,features:[{directory,documents:[{path,content}],testCasesReason}],removed:[directory]}. Include complete triads/optional test contracts for the exact selected plus explicitly proposed new features; for an existing feature you may omit any document left byte-identical (requirements/design as accepted in parts, tasks.md and, with testCasesReason null, test-cases.json as before) and it is restored, so the 64 KiB limit counts only documents you send. Preserve previous requirements/design bytes and inventory from parts. Retain completed task lines EXACTLY; preserve task IDs, mark changed pending CHANGED, obsolete DROPPED, added NEW. Append version rows to changed documents. Preserve unaffected/user cases; changes to user cases require separate explicit human consent. No writes, review/provider calls or approval.':
198
245
  `Apply ${phase==='change_requirements'?'C5 requirements changes':'C6 design changes'}. Return {status:documents,summary,features:[{directory,documents:[{path,content}]}],removed:[directory]}, or question/blocked. ${phase==='change_requirements'?'Only requirements.md; include retained selected features and proposed additions/removals.':'Keep exact requirements and feature/removal inventory from parts, add design.md; preserve unaffected modules.'} Preserve version rows and append new version for changed documents. Do not change completed history, call reviewers/providers, write files or infer consent.`},signal,'planner');
199
246
  current();
200
247
  if(response.status==='question'){need(text(response.question),'prd_change_reply_invalid');state.messages.push({role:'user',text:answer},{role:'assistant',result:response});state.question=response.question;return this.status();}
201
248
  if(response.status==='blocked'){state.stage='blocked';state.analysis=response;return this.status();}
202
249
  if(phase==='change_tasks'){
203
- const proposal=inspectPrdChangeProposal(state.before,response,state.selected,config,{rules:selfCheckRules()});
250
+ const proposal=inspectPrdChangeProposal(state.before,response,state.selected,config,{rules:selfCheckRules(),parts:state.parts});
204
251
  need(state.userCases===null||userCases(proposal.files).length>0,'prd_user_cases_missing');
205
252
  this.checkParts(proposal.features,proposal.removed,state.parts,true);
206
253
  state.proposal=proposal;state.round++;state.stage='change_check';
@@ -1,5 +1,5 @@
1
1
  // Mechanical subset of the existing Step 10.5 checklist. No semantic approval.
2
- import {parseFeatureTaskText,validDependencies,declaredAcceptanceIds,DEPENDENCY} from '../cm-ai/cm-ai-admission.mjs';
2
+ import {parseFeatureTaskText,validDependencies,declaredAcceptanceIds,acceptanceDeclarations,DEPENDENCY} from '../cm-ai/cm-ai-admission.mjs';
3
3
  import {specLines,taskLines,TASK_GRAMMAR} from '../spec-task-line.mjs';
4
4
  import {parseTaskScopes,BOOTSTRAP_FEATURE,sessionTaskProblem,sessionTaskReason} from '../task-scope.mjs';
5
5
  import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
@@ -41,6 +41,24 @@ function outsideFences(source){
41
41
  return fence===null?line:'';
42
42
  }).join('\n');
43
43
  }
44
+ // Fences for the rule-5 exemption follow CommonMark strictly: a closing fence is the same
45
+ // character, at least as long, with nothing but spaces after it. The looser outsideFences
46
+ // above would end a fence at "```not-a-closing-fence" and expose an example marker.
47
+ function strictOutsideFences(source){
48
+ let fence=null;return source.split(/\r?\n/).map(line=>{
49
+ if(fence===null){const open=line.match(/^ {0,3}(`{3,}|~{3,})/);if(open){fence=open[1];return '';}return line;}
50
+ // Only spaces and tabs may follow a closing fence; \s would also accept U+00A0 and other Unicode spaces.
51
+ const close=line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);
52
+ if(close&&close[1][0]===fence[0]&&close[1].length>=fence.length)fence=null;
53
+ return '';
54
+ }).join('\n');
55
+ }
56
+ // Rule 5: ids whose only declarations say NOT_APPLICABLE. A marker counts only outside strict
57
+ // fences, and any plain declaration of the same id anywhere (fenced or not) keeps it required.
58
+ function inapplicableAcceptanceIds(source){
59
+ const plain=new Set(acceptanceDeclarations(source).filter(item=>!item.inapplicable).map(item=>item.id));
60
+ return new Set(acceptanceDeclarations(strictOutsideFences(source)).filter(item=>item.inapplicable&&!plain.has(item.id)).map(item=>item.id));
61
+ }
44
62
  // Rule 2 adds checks the parser alone cannot make; rule 1 is the original subset.
45
63
  // Only a fresh draft round and a change proposal opt into rule 2. Every re-check
46
64
  // of material that may predate it (corrections, dispositions, summary) stays on
@@ -51,10 +69,18 @@ function outsideFences(source){
51
69
  // instead of a session's guess. Tasks an approved tasks.md already had may stay
52
70
  // without scope (they simply run serially).
53
71
  // Rule 4 reads tasks.md as task grammar 3 (`开发: 会话`) and adds the session-task checks.
54
- export const PRD_SELF_CHECK_RULES=4;
72
+ // Rule 5 = rule 4 plus the NOT_APPLICABLE coverage exemption (inapplicableAcceptanceIds below).
73
+ // Rule 6 = rule 3 plus that exemption, for sessions on specs still published under task grammar 2:
74
+ // they cannot take rule 4's grammar-3 reading, yet need the exemption too (Wue specs8, 2026-11-14).
75
+ // Rules are therefore feature sets, not a ladder: test them with the predicates below.
76
+ // Reports recorded under rules 1–4 recompute exactly as before.
77
+ export const PRD_SELF_CHECK_RULES=5;
78
+ export const PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES=6;
79
+ export const ruleReadsGrammar3=rules=>rules===4||rules===5;
80
+ export const ruleExemptsInapplicable=rules=>rules===5||rules===6;
55
81
  // Every rule a session, an operation or a recorded report may carry. Earlier rules
56
82
  // stay listed explicitly so raising the current one never drops them.
57
- export const PRD_SELF_CHECK_RULE_VERSIONS=Object.freeze([...new Set([PRD_SELF_CHECK_RULES,3,2,1])]);
83
+ export const PRD_SELF_CHECK_RULE_VERSIONS=Object.freeze([...new Set([PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES,4,3,2,1])]);
58
84
  // Task- or dependency-looking lines the parser skips: a task written this way
59
85
  // would silently drop out of execution.
60
86
  const TASK_LIKE=/^\s*-\s*\[[^\]]*\]\s+(?:~~)?T-/,DEPENDENCY_LIKE=/^\s*-\s*T-\S*\s+依赖(?:\s|$)/;
@@ -110,10 +136,12 @@ export function matchesPrdDraftMechanics(draft,recorded,options={}){
110
136
  // `sessionTasks` ([directory...]) likewise applies only what rule 4 adds (tasks.md
111
137
  // read as grammar 3, with the session-task checks) to the features whose save
112
138
  // recorded rule 4, so a correction cannot move or add a `开发: 会话` mark unnoticed.
113
- export function checkPrdDraftMechanics(draft,{change=false,previous=null,rules=1,scopes=null,sessionTasks=null}={}){
139
+ export function checkPrdDraftMechanics(draft,{change=false,previous=null,rules=1,scopes=null,sessionTasks=null,inapplicableAcceptance=null}={}){
114
140
  need(PRD_SELF_CHECK_RULE_VERSIONS.includes(rules),'prd_self_check_rules_invalid');
115
141
  need(sessionTasks===null||Array.isArray(sessionTasks)&&sessionTasks.every(item=>typeof item==='string'),
116
142
  'prd_self_check_rules_invalid');
143
+ need(inapplicableAcceptance===null||Array.isArray(inapplicableAcceptance)&&inapplicableAcceptance.every(item=>typeof item==='string'),
144
+ 'prd_self_check_rules_invalid');
117
145
  const findings=[],features=[];
118
146
  for(const feature of draft.features){
119
147
  const files=new Map(feature.documents.map(document=>[document.path,document.content]));
@@ -139,7 +167,7 @@ export function checkPrdDraftMechanics(draft,{change=false,previous=null,rules=1
139
167
  if(!reported.has(code))add(code);
140
168
  }
141
169
  const scope=scopes!==null&&Object.hasOwn(scopes,feature.directory)?scopes[feature.directory]:null;
142
- const grammar3=rules>=4||sessionTasks?.includes(feature.directory)===true;
170
+ const grammar3=ruleReadsGrammar3(rules)||sessionTasks?.includes(feature.directory)===true;
143
171
  if((rules>=3||scope!==null)&&!parsed.error){
144
172
  // Rules 1-3 predate grammar 3: a `开发:` line there stays prose, as it was then.
145
173
  const scopes=parseTaskScopes(files.get('tasks.md'),{grammar:grammar3?TASK_GRAMMAR:2});
@@ -171,7 +199,9 @@ export function checkPrdDraftMechanics(draft,{change=false,previous=null,rules=1
171
199
  if(cases.cases.some(item=>item.taskIds.length===0||item.taskIds.some(id=>!taskIds.has(id))
172
200
  ||item.acIds.some(id=>!acIds.has(id))))add('test_reference_invalid');
173
201
  const covered=new Set(cases.cases.flatMap(item=>item.acIds));
174
- if([...acIds].some(id=>!covered.has(id)))add('acceptance_test_coverage_missing');
202
+ const inapplicable=ruleExemptsInapplicable(rules)||inapplicableAcceptance?.includes(feature.directory)===true
203
+ ?inapplicableAcceptanceIds(files.get('requirements.md')):new Set();
204
+ if([...acIds].some(id=>!covered.has(id)&&!inapplicable.has(id)))add('acceptance_test_coverage_missing');
175
205
  }
176
206
  }
177
207
  }
@@ -8,7 +8,7 @@ import {recoverPrdResponse,readPrdRepairBinding} from './response-recovery.mjs';
8
8
  import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
9
9
  import {TASK_GRAMMAR} from '../spec-task-line.mjs';
10
10
  import {readSpecsStatus} from '../specs-status.mjs';
11
- import {PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_RULE_VERSIONS} from './self-check.mjs';
11
+ import {PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_RULE_VERSIONS,PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES,ruleReadsGrammar3} from './self-check.mjs';
12
12
 
13
13
  export function readPrdSessionFile(root,relative){
14
14
  if(!['state.json','inputs-replaced.json'].includes(relative))return readCmInitSource(root,relative)?.toString('utf8')??null;
@@ -44,7 +44,9 @@ export function prdSessionVersions(state,specs=null){
44
44
  if(state==null){
45
45
  const status=specs===null?{kind:'missing'}:readSpecsStatus(specs);
46
46
  return status.kind==='missing'||status.kind==='valid'&&status.value.taskGrammar===TASK_GRAMMAR
47
- ?{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES}:{...PRD_SESSION_LEGACY_VERSIONS};
47
+ ?{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES}
48
+ // Same grammar as before; rule 6 adds only the NOT_APPLICABLE exemption to rule 3, never grammar 3.
49
+ :{...PRD_SESSION_LEGACY_VERSIONS,selfCheckRules:PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES};
48
50
  }
49
51
  return Object.hasOwn(state,'selfCheckRules')?{taskGrammar:state.taskGrammar,selfCheckRules:state.selfCheckRules}:{...PRD_SESSION_LEGACY_VERSIONS};
50
52
  }
@@ -70,7 +72,10 @@ export function openPrdSession({specs,sessionId,identity,executionPolicy=null}){
70
72
  try{need([1,2].includes(state.version)&&digest(state.identity)===digest(identity),'prd_session_identity_changed');
71
73
  need(Object.hasOwn(state,'taskGrammar')===Object.hasOwn(state,'selfCheckRules')&&(!Object.hasOwn(state,'taskGrammar')
72
74
  ||Number.isSafeInteger(state.taskGrammar)&&state.taskGrammar>=2&&state.taskGrammar<=TASK_GRAMMAR
73
- &&PRD_SELF_CHECK_RULE_VERSIONS.includes(state.selfCheckRules)),'prd_session_versions_invalid');
75
+ &&PRD_SELF_CHECK_RULE_VERSIONS.includes(state.selfCheckRules)
76
+ // A grammar-3 rule only with grammar 3, and rule 6 (grammar-2 exemption) only with grammar 2.
77
+ &&(!ruleReadsGrammar3(state.selfCheckRules)||state.taskGrammar===TASK_GRAMMAR)
78
+ &&(state.selfCheckRules!==PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES||state.taskGrammar===2)),'prd_session_versions_invalid');
74
79
  if(state.version===2){readExecutionPolicy(state.executionPolicy);need(Array.isArray(state.responseRepairs),'prd_recovery_binding');}
75
80
  else need(executionPolicy===null,'execution_policy_legacy_run');}
76
81
  catch(e){fs.unlinkSync(lock);throw e;}
@@ -17,6 +17,7 @@ import {prdTaskScopeOptions} from './task-scope-record.mjs';
17
17
  import {need,json,shape,digest} from '../cm-ai/effect-contract.mjs';
18
18
  import {inspectPrdFailedCorrection} from './failed-correction.mjs';
19
19
  import {prdDesignRiskSignals} from './design-risk.mjs';
20
+ import {summaryAcceptancePreview} from './acceptance-preview.mjs';
20
21
  const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
21
22
 
22
23
  export function inspectPrdSummaryEvidence(specs,{currentFeatures}={}){
@@ -215,7 +216,11 @@ export function createPrdSummaryOwner({summarize}){
215
216
  if(evidence.predecessor)revisionNotes.push(`前序批次 ${evidence.predecessor.sessionId} 因输入已替换而结束;原因:${evidence.predecessor.reason}。旧证据仅作历史,本批全部重新审查。`);
216
217
  const humanDetails=riskCard.length||revisionNotes.length?{...details,risks:[...riskCard.map(risk=>
217
218
  `${risk.feature}:修正自检失败,待人工裁决;${JSON.stringify(risk.failedChecks)}`),...revisionNotes,details.risks].join('\n')}:details;
219
+ const acceptancePreview=summaryAcceptancePreview({documents:evidence.documents,currentFeatures:scope.currentFeatures,
220
+ statusBytes:readCmInitSource(specs,'.cm-specs-status'),taskGrammar:options.taskGrammar??2});
221
+ need(digest(inspectPrdSummaryEvidence(specs,scope))===evidenceDigest,'prd_summary_inputs_changed');
218
222
  const summary=json({...(evidence.predecessor?{predecessor:evidence.predecessor}:{}),status:'human_summary_prepared',evidenceDigest,details:humanDetails,features:evidence.features,totals,
223
+ acceptancePreview,
219
224
  ...(riskCard.length?{riskCard}:{}),
220
225
  ...(evidence.currentFeatures===undefined?{}:{currentFeatures:evidence.currentFeatures}),
221
226
  notes,historicalSummary:`历史 feature:${historical.length} 个已登记,${historical.filter(item=>Object.values(item.reviews).some(review=>review.archive)).length} 个含旧版归档说明`,
@@ -17,7 +17,7 @@ import path from 'node:path';
17
17
  import {createHash} from 'node:crypto';
18
18
  import {need} from '../cm-ai/effect-contract.mjs';
19
19
  import {parseFeatureTaskText} from '../cm-ai/cm-ai-admission.mjs';
20
- import {checkPrdDraftMechanics,PRD_SELF_CHECK_RULE_VERSIONS} from './self-check.mjs';
20
+ import {checkPrdDraftMechanics,PRD_SELF_CHECK_RULE_VERSIONS,ruleReadsGrammar3,ruleExemptsInapplicable} from './self-check.mjs';
21
21
  import {readPrdSessionFile,replaceSessionFile} from './session.mjs';
22
22
  import {normalizeRuntimeMarkBytes} from '../../../scripts/cm-spec-manifest.mjs';
23
23
 
@@ -29,11 +29,13 @@ function taskIds(text,grammar){
29
29
  const parsed=parseFeatureTaskText(text,{grammar});
30
30
  return parsed.error?[]:parsed.tasks.map(task=>task.id).sort();
31
31
  }
32
+ // Only rules that add something to re-checks are written: grammar-3 session tasks (4, 5) or the exemption (5, 6).
33
+ const recordedRule=rules=>ruleReadsGrammar3(rules)||ruleExemptsInapplicable(rules);
32
34
  function parseRecord(raw){
33
35
  let value;try{value=JSON.parse(raw);}catch{value=null;}
34
36
  need(value!==null&&typeof value==='object'&&value.version===1&&typeof value.enforced==='boolean'
35
37
  &&Array.isArray(value.exempt)&&value.exempt.every(id=>typeof id==='string')
36
- &&(!Object.hasOwn(value,'selfCheckRules')||PRD_SELF_CHECK_RULE_VERSIONS.includes(value.selfCheckRules)&&value.selfCheckRules>=4)
38
+ &&(!Object.hasOwn(value,'selfCheckRules')||PRD_SELF_CHECK_RULE_VERSIONS.includes(value.selfCheckRules)&&recordedRule(value.selfCheckRules))
37
39
  &&Object.keys(value).length===(Object.hasOwn(value,'selfCheckRules')?4:3),'prd_task_scope_record_invalid');
38
40
  return value;
39
41
  }
@@ -64,7 +66,8 @@ export function approvedScopeExemptions(before,directories,grammar){
64
66
 
65
67
  // `exemptions` maps a directory to {exempt} (a change) or is empty (a new draft).
66
68
  // `selfCheckRules` is the rule of the saving operation (session.mjs); only rule 4
67
- // and later are written, since earlier rules add nothing beyond the scope record.
69
+ // and later are written, since earlier rules add nothing beyond the scope record
70
+ // (4: session tasks; 5: also the NOT_APPLICABLE coverage exemption; 6: the exemption only).
68
71
  export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules=1}={}){
69
72
  need(PRD_SELF_CHECK_RULE_VERSIONS.includes(selfCheckRules),'prd_self_check_rules_invalid');
70
73
  const reviews=path.join(specs,'.reviews');
@@ -77,7 +80,7 @@ export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules
77
80
  {scopes:{[feature.directory]:{exempt}}});
78
81
  const enforced=!report.findings.some(item=>SCOPE_CODES.has(item.code));
79
82
  const relative=recordPath(feature.directory),bytes=JSON.stringify({version:1,enforced,exempt,
80
- ...(selfCheckRules>=4?{selfCheckRules}:{})})+'\n';
83
+ ...(recordedRule(selfCheckRules)?{selfCheckRules}:{})})+'\n';
81
84
  const prior=readPrdSessionFile(specs,relative);
82
85
  if(prior!==bytes)replaceSessionFile(specs,relative,prior,bytes);
83
86
  }
@@ -85,13 +88,16 @@ export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules
85
88
 
86
89
  // The checkPrdDraftMechanics options a re-check of saved features must use.
87
90
  export function prdTaskScopeOptions(specs,directories){
88
- const scopes={},sessionTasks=[];
91
+ const scopes={},sessionTasks=[],inapplicableAcceptance=[];
89
92
  for(const directory of typeof directories==='string'?[directories]:directories){
90
93
  const raw=readPrdSessionFile(specs,recordPath(directory));
91
94
  if(raw===null)continue;
92
95
  const value=parseRecord(raw);
93
96
  if(value.enforced)scopes[directory]={exempt:value.exempt};
94
- if(Object.hasOwn(value,'selfCheckRules'))sessionTasks.push(directory);
97
+ if(ruleReadsGrammar3(value.selfCheckRules))sessionTasks.push(directory);
98
+ // Saved under rule 5 or 6: re-checks keep the NOT_APPLICABLE coverage exemption, as rule 4 keeps session tasks.
99
+ if(ruleExemptsInapplicable(value.selfCheckRules))inapplicableAcceptance.push(directory);
95
100
  }
96
- return {...(Object.keys(scopes).length?{scopes}:{}),...(sessionTasks.length?{sessionTasks}:{})};
101
+ return {...(Object.keys(scopes).length?{scopes}:{}),...(sessionTasks.length?{sessionTasks}:{}),
102
+ ...(inapplicableAcceptance.length?{inapplicableAcceptance}:{})};
97
103
  }
@@ -0,0 +1,38 @@
1
+ // Selection adapter for the native Node test runner. This is not an execution
2
+ // receipt: it only models explicit files and options that do not filter tests.
3
+ // Keep custom reporters, preload/config hooks, discovery, globs and filters
4
+ // unknown. A successful wrapper or a reported count cannot supply this mapping.
5
+ const positiveInteger=value=>/^[1-9][0-9]*$/.test(value)
6
+ &&Number.isSafeInteger(Number(value))&&Number(value)<=2147483647;
7
+ const values=new Map([
8
+ ['--test-concurrency',positiveInteger],
9
+ ['--test-timeout',positiveInteger],
10
+ ['--test-reporter',value=>['tap','spec','dot'].includes(value)],
11
+ ['--test-reporter-destination',value=>['stdout','stderr'].includes(value)],
12
+ ]);
13
+ const file=value=>typeof value==='string'&&value.length>0&&!value.startsWith('-')&&!value.startsWith('/')
14
+ &&!/[\\\x00-\x1f\x7f*?\[\]{}]/.test(value)
15
+ &&value.replace(/^\.\//,'').split('/').every(part=>part&&part!=='.'&&part!=='..');
16
+
17
+ export function selectedNodeTestFiles(tokens){
18
+ if(!Array.isArray(tokens)||tokens[0]!==process.execPath
19
+ ||!tokens.every(token=>typeof token==='string'&&token.length>0))return null;
20
+ const seen=new Set();let test=false,index=1;
21
+ for(;index<tokens.length;index++){
22
+ const token=tokens[index];
23
+ if(token==='--'){index++;break;}
24
+ if(!token.startsWith('-'))break;
25
+ if(token==='--test'){
26
+ if(test)return null;test=true;continue;
27
+ }
28
+ const equals=token.indexOf('='),name=equals===-1?token:token.slice(0,equals),validate=values.get(name);
29
+ if(!validate||seen.has(name))return null;
30
+ seen.add(name);
31
+ const value=equals===-1?tokens[++index]:token.slice(equals+1);
32
+ if(typeof value!=='string'||!validate(value))return null;
33
+ }
34
+ if(!test||seen.has('--test-reporter-destination')&&!seen.has('--test-reporter'))return null;
35
+ const files=tokens.slice(index);
36
+ if(files.length===0||!files.every(file))return null;
37
+ return files.map(value=>value.replace(/^\.\//,''));
38
+ }