@aibyzero/cm-workflow 0.19.0 → 0.20.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 (82) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +8 -0
  4. package/README.md +8 -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/package.json +1 -1
  10. package/runtime/js/autonomy.mjs +159 -3
  11. package/runtime/js/check-coverage.mjs +130 -0
  12. package/runtime/js/cm-ai/acceptance-contract.mjs +252 -0
  13. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +14 -6
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  16. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  17. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  18. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  19. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  20. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  21. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  22. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  23. package/runtime/js/cm-ai/drive-core.mjs +6 -2
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +2 -2
  25. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  26. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  27. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  28. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  29. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  30. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  31. package/runtime/js/cm-ai/review-package.mjs +2 -2
  32. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  33. package/runtime/js/cm-ai/task-runner.mjs +38 -13
  34. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  35. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  36. package/runtime/js/cm-prd/change.mjs +17 -1
  37. package/runtime/js/cm-prd/summary.mjs +5 -0
  38. package/runtime/js/node-test-selection.mjs +38 -0
  39. package/runtime/js/run-analysis.mjs +153 -0
  40. package/runtime/js/session-boundary.mjs +17 -5
  41. package/runtime/js/session-handoff.mjs +5 -2
  42. package/scripts/cm-acceptance-preview.mjs +26 -0
  43. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  44. package/scripts/cm-ai-acceptance-contract.test.mjs +185 -0
  45. package/scripts/cm-ai-admission.test.mjs +5 -2
  46. package/scripts/cm-ai-blockage.test.mjs +120 -0
  47. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  48. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  49. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  50. package/scripts/cm-ai-progress.test.mjs +7 -0
  51. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  52. package/scripts/cm-ai-run.test.mjs +23 -1
  53. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  54. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  55. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  56. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  57. package/scripts/cm-autonomy-review-r1.test.mjs +93 -0
  58. package/scripts/cm-autonomy.mjs +3 -1
  59. package/scripts/cm-autonomy.test.mjs +10 -9
  60. package/scripts/cm-check-runtime.sh +1 -1
  61. package/scripts/cm-delivery-evidence.mjs +59 -0
  62. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  63. package/scripts/cm-drive-liveness.test.mjs +6 -0
  64. package/scripts/cm-driver-light-import.test.mjs +32 -0
  65. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  66. package/scripts/cm-node-test-selection.test.mjs +108 -0
  67. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  68. package/scripts/cm-prd-completion.test.mjs +12 -0
  69. package/scripts/cm-prd-host.mjs +3 -1
  70. package/scripts/cm-prd-host.test.mjs +18 -1
  71. package/scripts/cm-prd-summary.test.mjs +19 -4
  72. package/scripts/cm-review-inventory.test.mjs +21 -6
  73. package/scripts/cm-run-analysis.mjs +21 -0
  74. package/scripts/cm-run-analysis.test.mjs +120 -0
  75. package/scripts/cm-start-check.mjs +60 -53
  76. package/scripts/cm-start-check.test.mjs +76 -1
  77. package/scripts/cm-usage-report.py +8 -3
  78. package/scripts/cm019-r1-contract.test.mjs +137 -0
  79. package/scripts/cm019-review-gates.test.mjs +97 -0
  80. package/skills/cm-ai/references/js-host.md +5 -1
  81. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  82. package/skills/cm-prd/references/js-host.md +1 -0
@@ -8,6 +8,7 @@ import {taskLines,TASK_GRAMMAR,recordedTaskGrammar} from '../spec-task-line.mjs'
8
8
  import {readReviewSourceFiles,readReviewSourceExcerpt} from './review-package.mjs';
9
9
  import {json,need,shape,hex,id,freeze,digest} from './effect-contract.mjs';
10
10
  import {readExecutionSnapshot} from './execution-snapshot.mjs';
11
+ import {buildAcceptanceContract,readAcceptanceContract} from './acceptance-contract.mjs';
11
12
 
12
13
  const DESIGN_LIMIT=64*1024;
13
14
  const filenames=['requirements.md','design.md','tasks.md','test-cases.json'];
@@ -17,7 +18,10 @@ const featureName=value=>need(typeof value==='string'&&/^\d+\.[^/\\\x00-\x1f]+$/
17
18
  export function readSpecificationMaterial(raw,taskId){
18
19
  const v=json(raw,2*1024*1024);
19
20
  shape(v,['feature','task','acceptanceCriteria','designExcerpt','testCases','sources',
20
- ...['truncated','taskScopeDigest'].filter(key=>Object.hasOwn(v,key))]);
21
+ ...['truncated','taskScopeDigest','acceptanceContract'].filter(key=>Object.hasOwn(v,key))]);
22
+ if(Object.hasOwn(v,'acceptanceContract')){
23
+ readAcceptanceContract(v.acceptanceContract);need(v.acceptanceContract.taskId===taskId);
24
+ }
21
25
  if(Object.hasOwn(v,'taskScopeDigest'))hex(v.taskScopeDigest);
22
26
  featureName(v.feature);
23
27
  shape(v.task,['id','description',...(Object.hasOwn(v.task,'verification')?['verification']:[])]);
@@ -53,14 +57,14 @@ const TASK_ID_TOKEN=/(?<![A-Za-z0-9])T-[A-Za-z0-9][A-Za-z0-9._-]*/g;
53
57
  const indentOf=line=>/^[ \t]*/.exec(line)[0].length;
54
58
  const MENTIONS_TASK=/(?<![A-Za-z0-9])T-[A-Za-z0-9]/;
55
59
  const namesTask=(text,taskId)=>(text.match(TASK_ID_TOKEN)??[]).some(id=>id.replace(/[._-]+$/,'')===taskId);
56
- export function taskScopeText(tasks,taskId,grammar=TASK_GRAMMAR){
60
+ export function taskScopeText(tasks,taskId,grammar=TASK_GRAMMAR,includeHeadings=false){
57
61
  const kept=[];let owner=null,ownerIndent=0;
58
62
  for(const {body,fenced,declaration} of taskLines(tasks,{grammar})){
59
63
  if(!body.trim())continue;
60
64
  if(declaration){owner=declaration.id;ownerIndent=indentOf(body);}
61
65
  // Only lines indented under an item belong to it; a fence or heading at
62
66
  // its level ends it, leaving the rest to the shared/named rules below.
63
- else if(owner!==null&&!(indentOf(body)>ownerIndent&&!/^\s*#/.test(body)))owner=null;
67
+ else if(owner!==null&&!(indentOf(body)>ownerIndent&&(includeHeadings||!/^\s*#/.test(body))))owner=null;
64
68
  const dependency=fenced||declaration?null:body.match(DEPENDENCY);
65
69
  const belongs=declaration?declaration.id:owner??dependency?.[1]??null;
66
70
  if(namesTask(body,taskId)||belongs===taskId||belongs===null&&!MENTIONS_TASK.test(body))kept.push(body);
@@ -90,7 +94,41 @@ function verificationFor(source,taskId){
90
94
  return lines.join('\n');
91
95
  }
92
96
 
93
- export function captureSpecificationMaterial({specsRoot,feature,taskId}){
97
+ // Acceptance selection is narrower than the conservative rebind drift scope.
98
+ // A mention in another task, dependency, heading or version table is not an
99
+ // acceptance declaration for this task; only its own list body and children are.
100
+ export function taskAcceptanceText(tasks,taskId,grammar=TASK_GRAMMAR){
101
+ const kept=[];let owner=null,ownerIndent=0;
102
+ for(const {body,declaration} of taskLines(tasks,{grammar})){
103
+ if(declaration){owner=declaration.id;ownerIndent=indentOf(body);}
104
+ else if(body.trim()&&owner!==null&&indentOf(body)<=ownerIndent)owner=null;
105
+ if(owner===taskId&&body.trim())kept.push(body);
106
+ }
107
+ // The dedicated verification section is an explicit task-keyed declaration,
108
+ // unlike incidental mentions elsewhere in the document.
109
+ let level=null;
110
+ for(const body of tasks.split(/\r?\n/)){
111
+ const heading=/^\s*(#{1,6})\s+(.+)$/.exec(body);
112
+ if(heading){if(level!==null&&heading[1].length<=level)level=null;if(heading[2].includes('验证要求'))level=heading[1].length;continue;}
113
+ const key=/^\s*(?:[-*]\s+)?(T-[A-Za-z0-9][A-Za-z0-9._-]*)(?=[::\s])/.exec(body)?.[1];
114
+ if(level!==null&&key===taskId)kept.push(body);
115
+ }
116
+ return kept.join('\n');
117
+ }
118
+
119
+ // Draft previews and approved captures use exactly the same source selection.
120
+ // This pure projection carries no approval, filesystem access or execution.
121
+ export function buildTaskAcceptanceContract({texts,taskId,grammar=TASK_GRAMMAR}){
122
+ const tasks=normalizeRuntimeMarks(texts['tasks.md'],'tasks.md');
123
+ const requirements=normalizeRuntimeMarks(texts['requirements.md'],'requirements.md');
124
+ const cases=texts['test-cases.json']===undefined?[]:JSON.parse(texts['test-cases.json']).cases;
125
+ need(Array.isArray(cases)&&cases.every(item=>item&&Array.isArray(item.taskIds)),'acceptance_preview_cases_invalid');
126
+ const taskText=taskAcceptanceText(tasks,taskId,grammar);
127
+ return buildAcceptanceContract({taskId,taskText,explicitOnly:true,
128
+ requirementsText:requirements,testCases:cases.filter(item=>item.taskIds.includes(taskId))});
129
+ }
130
+
131
+ export function captureSpecificationMaterial({specsRoot,feature,taskId,acceptance=true}){
94
132
  try{
95
133
  featureName(feature);
96
134
  need(path.isAbsolute(specsRoot)&&fs.realpathSync(specsRoot)===specsRoot);
@@ -129,27 +167,33 @@ export function captureSpecificationMaterial({specsRoot,feature,taskId}){
129
167
  [...declaredAcceptanceIds(line)].map(id=>({id,text:line.trim()})));
130
168
  const cases=texts['test-cases.json']===undefined?[]:JSON.parse(texts['test-cases.json']).cases;
131
169
  need(Array.isArray(cases)&&cases.every(item=>item&&Array.isArray(item.taskIds)));
170
+ const acceptanceContract=acceptance?buildTaskAcceptanceContract({texts,taskId,grammar}):null;
132
171
  return readSpecificationMaterial({feature,task,acceptanceCriteria,designExcerpt:design.excerpt,
133
172
  ...(design.truncated?{truncated:true}:{}),testCases:cases.filter(item=>item.taskIds.includes(taskId)),sources,
134
- taskScopeDigest:taskScopeDigest(texts,taskId,grammar)},taskId);
173
+ taskScopeDigest:taskScopeDigest(texts,taskId,grammar),
174
+ ...(acceptanceContract?{acceptanceContract}:{})},taskId);
135
175
  }catch{throw Object.assign(new Error('spec_drift'),{code:'spec_drift'});}
136
176
  }
137
177
 
138
178
  // Material captured by older versions has no taskScopeDigest; compare a fresh
139
179
  // capture in the bound representation so their runs keep verifying.
140
180
  const asBound=(bound,current)=>{
141
- if(Object.hasOwn(bound,'taskScopeDigest'))return current;
142
- const {taskScopeDigest:unused,...legacy}=current;return legacy;
181
+ const result={...current};
182
+ for(const key of ['taskScopeDigest','acceptanceContract'])if(!Object.hasOwn(bound,key))delete result[key];
183
+ // Stored contracts are data in the original validated baseline, not executable
184
+ // parser rules. The source digests and all other material still compare below.
185
+ if(Object.hasOwn(bound,'acceptanceContract'))result.acceptanceContract=bound.acceptanceContract;
186
+ return result;
143
187
  };
144
188
  // Rebind eligibility, deliberately conservative: requirements.md and design.md
145
189
  // must be unchanged as whole files (acceptance items may span lines, and prose
146
190
  // can state requirements); in tasks.md and test-cases.json only other tasks'
147
191
  // items, dependency lines and cases may differ (taskScopeDigest). A run bound
148
192
  // before taskScopeDigest existed cannot prove that and is never rebindable.
149
- const CONTENT_FIELDS=['feature','task','acceptanceCriteria','designExcerpt','truncated','testCases','taskScopeDigest'];
193
+ const CONTENT_FIELDS=['feature','task','acceptanceCriteria','designExcerpt','truncated','testCases','taskScopeDigest','acceptanceContract'];
150
194
  const FIELD_NAMES={feature:'feature',task:'本任务描述/验证要求',acceptanceCriteria:'验收标准',
151
195
  designExcerpt:'设计摘录',truncated:'设计摘录',testCases:'本任务测试用例',
152
- taskScopeDigest:'tasks.md/test-cases.json 中本任务的条目、续行、依赖、用例或共用说明'};
196
+ taskScopeDigest:'tasks.md/test-cases.json 中本任务的条目、续行、依赖、用例或共用说明',acceptanceContract:'冻结的必验合同'};
153
197
  const WHOLE_FILES={'requirements.md':'requirements.md(整份核对,含验收标准续行与说明)','design.md':'design.md(整份核对)'};
154
198
 
155
199
  // Explicit, journaled rebind (task-runner rebindSpecification). It can only ever
@@ -194,7 +238,7 @@ const accepted=(baseline,captured)=>{
194
238
 
195
239
  export function verifySpecificationMaterial(baseline){
196
240
  const current=captureSpecificationMaterial({specsRoot:baseline.specificationRoot,
197
- feature:baseline.specification.feature,taskId:baseline.identity.taskId});
241
+ feature:baseline.specification.feature,taskId:baseline.identity.taskId,acceptance:false});
198
242
  need(accepted(baseline,current),'spec_drift');
199
243
  return baseline.specification;
200
244
  }
@@ -213,9 +257,10 @@ export function boundSpecificationMaterial(baseline,captured){
213
257
  export function inspectSpecificationDrift(baseline){
214
258
  let current;
215
259
  try{current=captureSpecificationMaterial({specsRoot:baseline.specificationRoot,
216
- feature:baseline.specification.feature,taskId:baseline.identity.taskId});}
260
+ feature:baseline.specification.feature,taskId:baseline.identity.taskId,acceptance:false});}
217
261
  catch{return freeze({approved:false,files:[],fields:[],rebindable:false});}
218
262
  if(accepted(baseline,current))return null;
263
+ current=asBound(baseline.specification,current);
219
264
  const bound=baseline.specification,before=new Map(bound.sources.map(row=>[row.path,row.sha256]));
220
265
  const after=new Map(current.sources.map(row=>[row.path,row.sha256]));
221
266
  const files=[...new Set([...before.keys(),...after.keys()])].filter(file=>before.get(file)!==after.get(file)).sort();
@@ -223,7 +268,7 @@ export function inspectSpecificationDrift(baseline){
223
268
  ...files.map(file=>WHOLE_FILES[file.split('/').at(-1)]).filter(Boolean),
224
269
  ...(before.size!==after.size?['test-cases.json 的有无']:[]),
225
270
  ...(Object.hasOwn(bound,'taskScopeDigest')?[]:['本运行由旧版本创建,未记录本任务段落摘要,无法证明其未变']),
226
- ...CONTENT_FIELDS.filter(field=>Object.hasOwn(bound,'taskScopeDigest')||field!=='taskScopeDigest')
271
+ ...CONTENT_FIELDS.filter(field=>!['taskScopeDigest','acceptanceContract'].includes(field)||Object.hasOwn(bound,field))
227
272
  .filter(field=>digest(current[field]??null)!==digest(bound[field]??null)).map(field=>FIELD_NAMES[field])])];
228
273
  return freeze({approved:true,files,fields,rebindable:fields.length===0,sources:current.sources});
229
274
  }
@@ -7,6 +7,7 @@ import {readExternalModels} from './external-models.mjs';
7
7
  import {beforeFirstQaRound,readQaConfigRevision} from './qa-config-revision.mjs';
8
8
  import {readCloseoutPolicy} from './knowledge-closeout.mjs';
9
9
  import {readQaAttachment} from './qa-attachment.mjs';
10
+ import {acceptanceProblems,encodeAcceptanceEvidence,acceptanceCoverage,describeAcceptanceProblems} from './acceptance-contract.mjs';
10
11
  // Trusted synthetic fixture host; explicit V2 supports isolated task-file writes.
11
12
  import { randomUUID } from 'node:crypto';
12
13
  import { types } from 'node:util';
@@ -17,7 +18,7 @@ import {verifySpecificationMaterial,boundSpecificationMaterial,inspectSpecificat
17
18
  readSpecificationRebind} from './specification-material.mjs';
18
19
  import { captureReviewBaseline, captureScopeRevisionSources, captureReviewInventory, compareReviewBaseline, createReviewPackage, verifyReviewPackage, verifyCompletionReviewPackage, validChecks, readReviewSourceFiles } from './review-package.mjs';
19
20
  import { digest,need,shape,id,text,json,freeze,arrayItems,validIdentity,validTaskLearningInput,validCallTimeout,requestFor,terminalFor,failureCode,
20
- JOURNAL_PAYLOAD_LIMIT,developCheckpointReserve,taskReviewScope,boundedReason } from './effect-contract.mjs';
21
+ JOURNAL_PAYLOAD_LIMIT,JOURNAL_REASON_LIMIT,developCheckpointReserve,taskReviewScope,boundedReason } from './effect-contract.mjs';
21
22
  import { reviewResult,reviewReceipt,boundReviewText,reviewPaths } from './review-runner.mjs';
22
23
  import { checkCompletion } from './gate-bridge.mjs';
23
24
  import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
@@ -177,7 +178,7 @@ export function createTaskRunner(options) {
177
178
  // only block: passing it grants nothing and never substitutes for that review.
178
179
  const verificationGate=options.verificationGate??null;
179
180
  // The latest satisfied gate's handoff entry; reset on every gate run.
180
- let requirementEvidence=null,hostReplayEvidence=null;
181
+ let requirementEvidence=null,hostReplayEvidence=null,acceptanceEvidence=null;
181
182
  need(verificationGate===null||typeof verificationGate==='function');
182
183
  if(taskMode)need(Object.hasOwn(options,'persistence'),'runner_completion');
183
184
  const config=json({root:options.root,identity:options.identity,scope:options.scope,requirements:options.requirements,
@@ -294,7 +295,7 @@ export function createTaskRunner(options) {
294
295
  const calls=[],cache=new Map(),session=restored?.session??randomUUID(),registered=new Map(),receipts=[];
295
296
  let state=reviewers.some(r=>r.allowed&&r.available)?'ready':'pending_review',code=null,attempt=1;
296
297
  let busy=false,pending=null,sequence=0,base=original,reviewPackage=null,currentChecks=null,workflowRunning=false;
297
- let reason=null,checkNewPaths=null;
298
+ let reason=null,checkNewPaths=null,verificationReason=null;
298
299
  let receipt=null,priorReview=null,cancelAfterCommit=false,workflowError=null,cancellationRequested=false,reviewInvocation=null;
299
300
  let learningResult=null;
300
301
  // Journaled supersession context: shown, never counted as a review verdict.
@@ -461,7 +462,7 @@ export function createTaskRunner(options) {
461
462
  const baseline=captureReviewBaseline({...configToBaseline(effectiveMetadata()),version:original.version,
462
463
  ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
463
464
  !Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
464
- original.ignorePolicy?.version===2?original.ignorePolicy:null);
465
+ original.ignorePolicy?.version===2?original.ignorePolicy:null,Boolean(original.specification?.acceptanceContract));
465
466
  return splitDocumentationState(baseline.files,paths);
466
467
  }
467
468
  const documentationRefusal=(refusal,detail)=>Object.assign(new Error(refusal),{code:refusal,reason:{
@@ -716,7 +717,7 @@ export function createTaskRunner(options) {
716
717
  compareReviewBaseline(withBoundSpecification(captureReviewBaseline({...configToBaseline(effectiveMetadata()),version:original.version,
717
718
  ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
718
719
  !Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
719
- original.ignorePolicy?.version===2?original.ignorePolicy:null)),original);
720
+ original.ignorePolicy?.version===2?original.ignorePolicy:null,Boolean(original.specification?.acceptanceContract))),original);
720
721
  }
721
722
  const specificationLive=(currentState,currentCode)=>Object.hasOwn(original,'specification')
722
723
  &&['develop','review','complete'].some(kind=>stageAllowed(kind,currentState,currentCode,priorReview?.verdict));
@@ -1167,25 +1168,48 @@ export function createTaskRunner(options) {
1167
1168
  return {files};
1168
1169
  }
1169
1170
  async function verificationSatisfied(checks) {
1170
- requirementEvidence=null;hostReplayEvidence=null;
1171
- if(verificationGate===null)return true;
1171
+ requirementEvidence=null;hostReplayEvidence=null;acceptanceEvidence=null;verificationReason=null;
1172
1172
  // The description carries hard requirements too ("also confirm X/Y/Z do not
1173
1173
  // regress", "do not modify A"), and a gate that reads only the verification
1174
1174
  // section lets exactly those through to the independent review. Both are
1175
1175
  // sent; neither is required to exist.
1176
1176
  const specification=Object.hasOwn(original,'specification')?verifySpecificationMaterial(original):null;
1177
+ const contract=specification?.acceptanceContract??null;
1178
+ if(verificationGate===null){
1179
+ if(contract)verificationReason='verification_precheck_failed: 冻结合同需要验证入口,当前宿主未提供 verificationGate';
1180
+ return contract===null;
1181
+ }
1177
1182
  const verification=specification?.task?.verification??null;
1178
1183
  const description=specification?.task?.description??null;
1179
1184
  const written=value=>typeof value==='string'&&value.trim().length>0;
1180
- if(!written(verification)&&!written(description))return true;
1185
+ if(!contract&&!written(verification)&&!written(description))return true;
1181
1186
  const verdict=json(await bounded(verificationGate,
1182
1187
  json({identity:{...config.identity,attempt},
1183
1188
  ...(written(description)?{description}:{}),
1184
- ...(written(verification)?{verification}:{}),checks,
1189
+ ...(written(verification)?{verification}:{}),...(contract?{acceptanceContract:contract}:{}),checks,
1185
1190
  ...(parsedHistory?.scopeRevisions?{scope:effectiveScope}: {})}),{baselineSnapshot:baselineSnapshot()}));
1186
- shape(verdict,['satisfied',...['items','hostRecord'].filter(key=>Object.hasOwn(verdict,key))]);
1191
+ shape(verdict,['satisfied',...['items','hostRecord','coverage','reason'].filter(key=>Object.hasOwn(verdict,key))]);
1187
1192
  need(typeof verdict.satisfied==='boolean','invalid_result');
1188
1193
  need(verdict.satisfied||!Object.hasOwn(verdict,'items')&&!Object.hasOwn(verdict,'hostRecord'),'invalid_result');
1194
+ if(Object.hasOwn(verdict,'reason')){
1195
+ need(!verdict.satisfied&&typeof verdict.reason==='string'
1196
+ &&verdict.reason.startsWith('verification_precheck_failed: ')
1197
+ &&verdict.reason.length<=JOURNAL_REASON_LIMIT&&!/[\x00-\x1f\x7f]/.test(verdict.reason),'invalid_result');
1198
+ verificationReason=verdict.reason;
1199
+ }
1200
+ if(contract){
1201
+ const coverage=acceptanceCoverage(contract,checks);
1202
+ const problems=verdict.satisfied?acceptanceProblems(contract,verdict.items,verdict.hostRecord??null):[];
1203
+ if(!coverage.satisfied)problems.push('mandatory checks missing or unverifiable: '+JSON.stringify(coverage));
1204
+ if(!verdict.satisfied||problems.length){
1205
+ if(problems.length)verificationReason=boundedReason('verification_precheck_failed: ',
1206
+ [...(verificationReason?[verificationReason.replace(/^verification_precheck_failed:\s*/, '')]:[]),
1207
+ ...describeAcceptanceProblems(contract,problems)]);
1208
+ return false;
1209
+ }
1210
+ acceptanceEvidence=encodeAcceptanceEvidence({contract,identity:{...config.identity,attempt},items:verdict.items,
1211
+ facts:verdict.hostRecord??null,coverage});
1212
+ }
1189
1213
  // The host's own replay record (host-replay.mjs) is a separate handoff entry.
1190
1214
  hostReplayEvidence=Object.hasOwn(verdict,'hostRecord')
1191
1215
  ?encodeHostReplayEvidence({identity:{...config.identity,attempt},facts:verdict.hostRecord}):null;
@@ -1240,7 +1264,7 @@ export function createTaskRunner(options) {
1240
1264
  async function hostDeliveryChecks(){
1241
1265
  currentChecks=await collectChecks();active();
1242
1266
  if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return false;}
1243
- if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return false;}
1267
+ if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed',verificationReason);return false;}
1244
1268
  active();
1245
1269
  // unchangedSinceRejection builds a package too, so an empty delivery or a
1246
1270
  // deleted in-scope requirement surfaces there first and takes the same
@@ -1251,7 +1275,8 @@ export function createTaskRunner(options) {
1251
1275
  try{createHostHandoff({root:config.root,baseline:base,checks:currentChecks,
1252
1276
  handoffPath:completion.handoffs[attempt-1],evidence:[...journal.filter(row=>row.payload.type==='completion-rework-requested')
1253
1277
  .map(row=>'cm-completion-rework-v1: '+JSON.stringify({identity:{...config.identity,attempt:2},recordDigest:row.digest})),
1254
- ...(requirementEvidence===null?[]:[requirementEvidence]),...(hostReplayEvidence===null?[]:[hostReplayEvidence])]});}
1278
+ ...(requirementEvidence===null?[]:[requirementEvidence]),...(hostReplayEvidence===null?[]:[hostReplayEvidence]),
1279
+ ...(acceptanceEvidence===null?[]:[acceptanceEvidence])]});}
1255
1280
  catch(error){emptyDelivery(error);return false;}
1256
1281
  return true;
1257
1282
  }
@@ -1383,7 +1408,7 @@ export function createTaskRunner(options) {
1383
1408
  if(taskLearning?.hostHandoff!==true){
1384
1409
  currentChecks=await collectChecks();active();
1385
1410
  if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return;}
1386
- if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return;}
1411
+ if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed',verificationReason);return;}
1387
1412
  active();
1388
1413
  let unchanged;
1389
1414
  try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return;}
@@ -8,18 +8,20 @@
8
8
  // run "red" needs the test-files-only run to have run and failed; run "baseline"
9
9
  // needs the baseline to have run (a run that could not start proves nothing) and,
10
10
  // with a result, to have that result. An untagged item is not a run claim here.
11
- // The same limit as the session-answered gate: coverage of every written
12
- // requirement, and the tagging of every run claim, are not proven.
11
+ // Legacy material has no expected set. New material supplies a frozen contract:
12
+ // coverage and run tags are checked against it before accepting any report.
13
+ // Neither mode proves arbitrary prose/physical evidence true; independent review remains.
14
+ import {acceptanceProblems} from './acceptance-contract.mjs';
13
15
  const ran=run=>run&&['passed','failed'].includes(run.outcome);
14
16
  const redFact=facts=>facts.status!=='replayed'?`未实跑(${facts.reason})`
15
17
  :facts.red.skipped?'tasks.md 未写测试文件,没有只放入测试文件的实跑'
16
18
  :`只放入测试文件时检查 ${facts.red.outcome}`;
17
19
 
18
20
  // report: the developer's items, null (absent) or 'invalid'. facts: replayDelivery's result.
19
- export function autoVerificationVerdict({report,facts}){
21
+ export function autoVerificationVerdict({report,facts,contract=null}){
20
22
  if(report===null)return {satisfied:false,unsatisfied:['开发结果没有逐条要求与证据(requirements)']};
21
23
  if(report==='invalid')return {satisfied:false,unsatisfied:['开发结果的逐条要求与证据(requirements)格式不合法']};
22
- const unsatisfied=[],replayed=facts.status==='replayed';
24
+ const unsatisfied=contract?acceptanceProblems(contract,report,facts):[],replayed=facts.status==='replayed';
23
25
  for(const item of report){
24
26
  if(item.satisfied!==true){unsatisfied.push(item.requirement);continue;}
25
27
  if(item.run==='red'&&!(replayed&&!facts.red.skipped&&facts.red.outcome==='failed'))
@@ -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';
@@ -166,7 +167,22 @@ export function createPrdChange({admission,runtime,call,restored=null,selected=[
166
167
  reference:path.join(admission.skillDir,'references/change-mode.md')},signal);
167
168
  };
168
169
  return {
169
- status:()=>json({...state,mode:'change',completionAuthorized:false},4*1024*1024),
170
+ status:()=>{
171
+ let acceptancePreview=null;
172
+ if(state.stage==='change_confirmation'&&state.proposal){
173
+ try{
174
+ current();
175
+ const documents=[...state.before.directories.filter(directory=>!state.selected.includes(directory)).map(directory=>({directory,
176
+ documents:names.filter(name=>state.before.files[`${directory}/${name}`]!==undefined).map(name=>({path:name,content:state.before.files[`${directory}/${name}`]}))})),...state.proposal.features];
177
+ acceptancePreview={...summaryAcceptancePreview({documents,currentFeatures:state.proposal.features.map(feature=>feature.directory),
178
+ statusBytes:state.before.status===null?null:Buffer.from(state.before.status),taskGrammar:approvedGrammar(state.before)}),
179
+ proposalDigest:state.proposal.proposalDigest,sourceKind:'proposed_documents'};
180
+ current();
181
+ }catch(error){acceptancePreview={version:1,status:'stale',reason:'prd_change_inputs_changed',
182
+ proposalDigest:state.proposal.proposalDigest,approvalAuthorized:false,executionAuthorized:false};}
183
+ }
184
+ return json({...state,mode:'change',completionAuthorized:false,...(acceptancePreview?{acceptancePreview}:{})},4*1024*1024);
185
+ },
170
186
  checkpoint:()=>json(state,4*1024*1024),
171
187
  cancel(){state.stage='cancelled';},
172
188
  async advance(answer,signal){
@@ -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} 个含旧版归档说明`,
@@ -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
+ }