@aibyzero/cm-workflow 0.18.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 (90) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +26 -0
  4. package/README.md +14 -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 +308 -0
  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 +53 -12
  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 +8 -3
  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/notify.mjs +17 -8
  40. package/runtime/js/run-analysis.mjs +153 -0
  41. package/runtime/js/session-boundary.mjs +17 -5
  42. package/runtime/js/session-handoff.mjs +5 -2
  43. package/runtime/js/specs-status.mjs +4 -3
  44. package/scripts/cm-acceptance-preview.mjs +26 -0
  45. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  46. package/scripts/cm-ai-acceptance-contract.test.mjs +185 -0
  47. package/scripts/cm-ai-admission.mjs +10 -2
  48. package/scripts/cm-ai-admission.test.mjs +151 -1
  49. package/scripts/cm-ai-blockage.test.mjs +120 -0
  50. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  51. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  52. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  53. package/scripts/cm-ai-progress.test.mjs +7 -0
  54. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  55. package/scripts/cm-ai-run.test.mjs +23 -1
  56. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  57. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  58. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  59. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  60. package/scripts/cm-autonomy-review-r1.test.mjs +93 -0
  61. package/scripts/cm-autonomy.mjs +96 -0
  62. package/scripts/cm-autonomy.test.mjs +163 -0
  63. package/scripts/cm-check-runtime.sh +3 -1
  64. package/scripts/cm-delivery-evidence.mjs +59 -0
  65. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  66. package/scripts/cm-drive-liveness.test.mjs +6 -0
  67. package/scripts/cm-driver-light-import.test.mjs +32 -0
  68. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  69. package/scripts/cm-node-test-selection.test.mjs +108 -0
  70. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  71. package/scripts/cm-notify.test.mjs +6 -0
  72. package/scripts/cm-prd-completion.test.mjs +12 -0
  73. package/scripts/cm-prd-host.mjs +3 -1
  74. package/scripts/cm-prd-host.test.mjs +18 -1
  75. package/scripts/cm-prd-summary.test.mjs +19 -4
  76. package/scripts/cm-review-inventory.test.mjs +21 -6
  77. package/scripts/cm-run-analysis.mjs +21 -0
  78. package/scripts/cm-run-analysis.test.mjs +120 -0
  79. package/scripts/cm-start-check.mjs +128 -6
  80. package/scripts/cm-start-check.test.mjs +163 -3
  81. package/scripts/cm-usage-report.py +8 -3
  82. package/scripts/cm019-r1-contract.test.mjs +137 -0
  83. package/scripts/cm019-review-gates.test.mjs +97 -0
  84. package/scripts/validate-public-repo.py +3 -0
  85. package/skills/cm-ai/references/N3-execute-task.md +1 -1
  86. package/skills/cm-ai/references/js-host.md +31 -1
  87. package/skills/cm-prd/SKILL.md +3 -2
  88. package/skills/cm-prd/references/change-mode.md +3 -2
  89. package/skills/cm-prd/references/js-change-recovery.md +14 -0
  90. 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';
@@ -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
+ }
@@ -12,6 +12,7 @@ import {spawn} from 'node:child_process';
12
12
  import {fileURLToPath} from 'node:url';
13
13
  import {createHash,randomUUID} from 'node:crypto';
14
14
  import {readRegularFileSync} from './notify-safe-read.mjs';
15
+ import {readAutonomy} from './autonomy.mjs';
15
16
 
16
17
  export const NOTIFY_LIMITS=Object.freeze({sameKeyMs:6*3600*1000,perDay:150,
17
18
  windowMs:10*60000,perWindow:3,followUpMs:2*3600*1000,attentionTtlMs:24*3600*1000,
@@ -563,7 +564,7 @@ function dropPending(home,hash,before){
563
564
  if(pending?.missing||pending&&pending.at>before)return false;
564
565
  return removePending(home,hash);
565
566
  }
566
- function reserve(home,{hash,attention=null,event,code=null,pendingToken},now,limits){
567
+ function reserve(home,{hash,attention=null,event,code=null,pendingToken,urgent=false},now,limits){
567
568
  return withState(home,state=>{
568
569
  // A deferred waiter fires only for its own still-pending stop; any other
569
570
  // notice about the same session supersedes a pending one.
@@ -587,7 +588,10 @@ function reserve(home,{hash,attention=null,event,code=null,pendingToken},now,lim
587
588
  else return {status:'duplicate'};
588
589
  }
589
590
  const persist=extra=>writeState(home,{version:2,keys,attention:records,sends,suppressed:state.suppressed,...extra});
590
- if(sends.filter(at=>now-at<limits.windowMs).length>=limits.perWindow||sends.length>=NOTIFY_LIMITS.perDay){
591
+ // A fatal stop (urgent) is never rate limited. A deferred stop already waited and its
592
+ // pending record is gone, so neither limit may lose it for good: each one is a real
593
+ // stop the session did not move past within waitMinutes, which already bounds them.
594
+ if(!urgent&&pendingToken===undefined&&(sends.filter(at=>now-at<limits.windowMs).length>=limits.perWindow||sends.length>=NOTIFY_LIMITS.perDay)){
591
595
  const status=sends.length>=NOTIFY_LIMITS.perDay?'rate_day':'rate_window';
592
596
  return persist({suppressed:state.suppressed+1})?{status}:{status:'state_write_failed'};
593
597
  }
@@ -696,7 +700,7 @@ export async function sendPendingNotice(fields,token,{env=process.env,attempts=2
696
700
  const LEVEL_OF=Object.freeze({done:'passive',idle:'active'});
697
701
  // Never throws and never waits. Returns {sent, reason}; sent means the command
698
702
  // was handed to the detached launcher, whose own failures go to notify.log.
699
- export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs,pendingToken}={}){
703
+ export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs,pendingToken,urgent=false}={}){
700
704
  try{
701
705
  const config=readNotifyConfig(env);if(!config)return {sent:false,reason:'off'};
702
706
  if(typeof fields?.key!=='string'||!fields.key)return {sent:false,reason:'invalid_key'};
@@ -704,7 +708,7 @@ export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_L
704
708
  const attention=typeof fields.attentionKey==='string'&&fields.attentionKey&&Object.hasOwn(ATTENTION_LEVEL,event)
705
709
  ?keyHash(fields.attentionKey):null;
706
710
  if(pendingToken!==undefined&&attention===null)return {sent:false,reason:'cancelled'};
707
- const reserved=reserve(home,{hash,attention,event,code:clean(fields.code,64)||null,pendingToken},now,config);
711
+ const reserved=reserve(home,{hash,attention,event,code:clean(fields.code,64)||null,pendingToken,urgent:urgent===true},now,config);
708
712
  if(reserved.status!=='ok'){
709
713
  if(!['duplicate','cancelled'].includes(reserved.status))appendNotifyLog(home,now,{event,workflow,hash,result:`skipped ${reserved.status}`});
710
714
  return {sent:false,reason:reserved.status};
@@ -964,11 +968,15 @@ export function classifyDriveResult(workflow,row){
964
968
  const kind=classifyRaw(workflow,row);
965
969
  return kind==='ask'?'stuck':kind;
966
970
  }
967
- export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
971
+ export function driveNotice({host,cwd,args=[],operation,row=null,failure=null,env=process.env}){
968
972
  if(READ_ONLY.has(operation))return null;
973
+ // Under the standing authorization the session decides: a finished unit is not news,
974
+ // and any stop waits waitMinutes (dropped once the session moves on). Fatal stops
975
+ // page at once from the session itself (cm-autonomy.mjs notify).
976
+ const autonomous=readAutonomy(env).on;
969
977
  const workflow=path.basename(String(host??'')).replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
970
978
  const raw=failure?'stuck':classifyRaw(workflow,row),kind=raw==='ask'?'stuck':raw,ask=raw==='ask';
971
- if(!kind)return null;
979
+ if(!kind||autonomous&&kind==='done')return null;
972
980
  const done=kind==='done',result=obj(row?.result),progress=obj(result.progress),nested=obj(result.result);
973
981
  const code=text(failure)??text(row?.error?.code)??text(result.code)??text(result.reason)??text(result.blocker)
974
982
  ??text(progress.blocker)??text(result.overall)??text(nested.overall)??text(result.state)??text(result.status)??text(result.stage)??null;
@@ -981,7 +989,7 @@ export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
981
989
  const reviewFailure=typeof result.reviewFailure==='string'&&/^reviewer_[a-z_]{1,48}$/.test(result.reviewFailure)?result.reviewFailure:null;
982
990
  const developFailure=typeof result.developFailure==='string'&&/^developer_[a-z_]{1,48}$/.test(result.developFailure)?result.developFailure:null;
983
991
  const pendingAction=typeof result.pendingAction==='string'&&/^[a-z_]{1,32}$/.test(result.pendingAction)?result.pendingAction:null;
984
- const delivery=done||immediateStop({codes:[failure,row?.error?.code,result.code,result.reason,result.blocker,progress.blocker],
992
+ const delivery=done||!autonomous&&immediateStop({codes:[failure,row?.error?.code,result.code,result.reason,result.blocker,progress.blocker],
985
993
  state:text(result.state),pendingAction,ask})?'now':'later';
986
994
  return {key:[workflow,run,task??'',attempt??'',stage??'',done?'done':code??''].join('|'),
987
995
  ...(done?{}:{attentionKey:attentionKeyFor({project,session,workflow,runId:run})}),
@@ -989,7 +997,8 @@ export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
989
997
  code:done?(text(result.code)??text(result.overall)??text(nested.overall)??'done'):code,
990
998
  // A finished unit is the natural point to start a fresh session (runtime/model-efficiency.md).
991
999
  nextAction:done?'会话边界:换新会话,下一项在新会话里运行':text(result.guidance?.nextStep)??text(progress.nextAction)??text(result.nextAction),
992
- ...(reviewFailure?{reviewFailure}:{}),...(developFailure?{developFailure}:{}),...(pendingAction&&!done?{pendingAction}:{}),...(ask?{ask:true}:{}),delivery};
1000
+ ...(reviewFailure?{reviewFailure}:{}),...(developFailure?{developFailure}:{}),...(pendingAction&&!done?{pendingAction}:{}),...(ask?{ask:true}:{}),delivery,
1001
+ ...(autonomous?{autonomous:true}:{})};
993
1002
  }
994
1003
 
995
1004
  // The attention record a successful, non-read-only step clears (see clearAttention).
@@ -0,0 +1,153 @@
1
+ // Read-only analysis of one stable authoritative specs log; never execution authority.
2
+ import path from 'node:path';
3
+ import {spawnSync} from 'node:child_process';
4
+ import {fileURLToPath} from 'node:url';
5
+ import {readStableLogRows} from './cm-ai/log-rows.mjs';
6
+
7
+ const MAX_BYTES=32*1024*1024,MAX_ROWS=100000;
8
+ const label=value=>typeof value==='string'&&value.length>0&&value.length<=128
9
+ &&!/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u.test(value);
10
+ const key=parts=>JSON.stringify(parts);
11
+ const fail=()=>{throw Object.assign(new Error('run_analysis_log_invalid'),{code:'run_analysis_log_invalid'});};
12
+ const timestamp=value=>typeof value==='string'&&/T.*(?:Z|[+-]\d\d:\d\d)$/.test(value)&&Number.isFinite(Date.parse(value))?Date.parse(value):null;
13
+ const usageScript=fileURLToPath(new URL('../../scripts/cm-usage-report.py',import.meta.url));
14
+ const usageBridge=`import json,runpy,sys
15
+ from pathlib import Path
16
+ from datetime import datetime,timezone
17
+ m=runpy.run_path(sys.argv[1],run_name='cm_usage_report')
18
+ data=json.load(sys.stdin)
19
+ refs=[m['RunRef'](r,'unknown','unknown','unknown',datetime.now(timezone.utc),'','snapshot.jsonl') for r in data]
20
+ report=m['build_report'](Path('.').resolve(),refs,data)
21
+ report['source']='specs-local-stable-snapshot'
22
+ report['summary']['invalid_claims']=sum(1 for rows in data.values() for _,row in rows if row.get('event')=='model_call' and m['claim_row_error'](row) is not None)
23
+ print(json.dumps(report,separators=(',',':')))
24
+ `;
25
+ function usageReport(rows){
26
+ const grouped=Object.create(null);
27
+ const fields=['run_id','event_id','event','phase','call_id','workflow','runtime','stage','role','adapter','requested_model',
28
+ 'effective_model','source','purpose','outcome','usage_state','input_tokens','output_tokens','cache_read_tokens','cache_write_tokens','reasoning_tokens','duration_ms'];
29
+ rows.forEach((row,index)=>{
30
+ if(!grouped[row.run_id])grouped[row.run_id]=[];
31
+ if(!['model_call','model_usage'].includes(row.event))return;
32
+ const minimal={};
33
+ for(const field of fields)if(Object.hasOwn(row,field)){
34
+ const value=row[field];
35
+ // Invalid identities must remain invalid, rather than becoming a valid alias.
36
+ minimal[field]=typeof value==='string'&&!label(value)||typeof value==='number'&&!Number.isSafeInteger(value)?null:value;
37
+ }
38
+ grouped[row.run_id].push([index+1,minimal]);
39
+ });
40
+ const result=spawnSync('python3',['-I','-c',usageBridge,usageScript],{input:JSON.stringify(grouped),encoding:'utf8',
41
+ timeout:20000,maxBuffer:MAX_BYTES,windowsHide:true});
42
+ if(result.error||result.status!==0)return {status:'unavailable',reason:'usage_reader_unavailable'};
43
+ try{
44
+ const report=JSON.parse(result.stdout),summary=report.summary;
45
+ const complete=summary.observed_calls>0&&!summary.unavailable_calls&&!summary.unresolved_claims&&!summary.invalid_calls&&!summary.invalid_claims;
46
+ return {status:complete?'observed':summary.observed_calls?'partial':'unavailable',...report};
47
+ }catch{return {status:'unavailable',reason:'usage_reader_unavailable'};}
48
+ }
49
+ function unionDuration(intervals){
50
+ let total=0,end=null;
51
+ for(const [start,stop] of intervals.sort((a,b)=>a[0]-b[0])){
52
+ total+=Math.max(0,stop-Math.max(start,end??start));end=Math.max(end??stop,stop);
53
+ }
54
+ return total;
55
+ }
56
+ function timingReport(rows){
57
+ const groups=new Map();let unrecognized=0;
58
+ rows.forEach((row,index)=>{
59
+ if(row.event!=='progress'||!['start','complete'].includes(row.phase))return;
60
+ const prd=row.workflow==='cm-prd'&&Number.isSafeInteger(row.segment)&&row.segment>=1;
61
+ // AI host operations have unique ids and no segment; never infer PRD segment 1.
62
+ const ai=row.workflow==='cm-ai'&&!Object.hasOwn(row,'segment')
63
+ &&['developing','checking','verifying','review_starting','reviewing'].includes(row.phase_name)
64
+ &&label(row.feature)&&label(row.task)&&Number.isSafeInteger(row.attempt)&&row.attempt>=1;
65
+ if(!label(row.operation_id)||!label(row.phase_name)||!prd&&!ai){unrecognized++;return;}
66
+ const protocol=ai?'cm-ai-host-operation':'cm-prd-segment';
67
+ const id=key([row.run_id,row.workflow,row.operation_id,row.phase_name,protocol,
68
+ ...(ai?[row.feature,row.task,row.attempt]:[row.segment])]);
69
+ if(!groups.has(id))groups.set(id,{runId:row.run_id,workflow:row.workflow,stage:row.phase_name,protocol,start:[],complete:[]});
70
+ groups.get(id)[row.phase].push({row,index});
71
+ });
72
+ const stages=new Map(),intervalsByRun=new Map();let incomplete=0,pauses=0,paired=0,combined=0;
73
+ for(const group of groups.values()){
74
+ const {start,complete}=group;
75
+ if(start.length!==1||complete.length!==1){incomplete++;continue;}
76
+ const first=start[0],last=complete[0],a=timestamp(first.row.at),b=timestamp(last.row.at);
77
+ const allowed=group.protocol==='cm-ai-host-operation'?['returned','failed','aborted']:['completed','awaiting_input','blocked'];
78
+ if(a===null||b===null||b<a||first.index>=last.index||!allowed.includes(last.row.outcome)){
79
+ incomplete++;continue;
80
+ }
81
+ paired++;if(last.row.outcome==='awaiting_input')pauses++;
82
+ const isCombined=first.row.timing_scope==='combined_host_call'||last.row.timing_scope==='combined_host_call';
83
+ if(isCombined)combined++;
84
+ const id=key([group.runId,group.workflow,group.stage]);
85
+ if(!stages.has(id))stages.set(id,{runId:group.runId,workflow:group.workflow,stage:group.stage,durationMs:0,pairedSegments:0,combinedSegments:0,outcomes:{}});
86
+ const stage=stages.get(id);stage.durationMs+=b-a;stage.pairedSegments++;stage.combinedSegments+=Number(isCombined);
87
+ stage.outcomes[last.row.outcome]=(stage.outcomes[last.row.outcome]??0)+1;
88
+ if(!intervalsByRun.has(group.runId))intervalsByRun.set(group.runId,[]);
89
+ intervalsByRun.get(group.runId).push([a,b]);
90
+ }
91
+ return {status:paired?(incomplete||unrecognized?'partial':'observed'):'unavailable',
92
+ pairedSegments:paired,incompleteSegments:incomplete,unrecognizedEvents:unrecognized,closedForInput:pauses,combinedSegments:combined,
93
+ activeIntervalUnionMs:paired?[...intervalsByRun.values()].reduce((n,v)=>n+unionDuration(v),0):null,
94
+ waitingMs:null,waitingStatus:'unavailable',stages:[...stages.values()],
95
+ scope:'Only matched progress segments; overlapping stages are not additive; gaps and unpaired time are unknown.'};
96
+ }
97
+ function repetitionReport(rows){
98
+ const groups=new Map();let unrecognized=0;
99
+ for(const row of rows){
100
+ // These are recorded starts/claims, not proof that a command ran or that work was redundant.
101
+ let kind,identity,execution;
102
+ if(row.event==='model_call'&&row.phase==='claimed'){
103
+ kind='model_call_claim';identity=[row.workflow,row.stage,row.role,row.adapter,row.requested_model,row.source,row.purpose];execution=row.call_id;
104
+ }else if(row.event==='test_run'&&row.phase==='start'){
105
+ kind='qa_invocation_start';identity=[row.workflow,row.feature,row.task];execution=row.operation_id;
106
+ }else continue;
107
+ if(!identity.every(label)||!label(execution)){unrecognized++;continue;}
108
+ const id=key([row.run_id,kind,...identity]);
109
+ if(!groups.has(id))groups.set(id,{runId:row.run_id,kind,identity,executions:new Set()});
110
+ groups.get(id).executions.add(execution);
111
+ }
112
+ const repeated=[...groups.values()].filter(x=>x.executions.size>1).map(({executions,...group})=>({...group,count:executions.size,additionalOccurrences:executions.size-1}));
113
+ return {status:groups.size?'observed':'unavailable',groups:repeated,unrecognizedEvents:unrecognized,
114
+ commandReexecution:'unavailable',interpretation:'Repeated recorded starts/claims only; necessity, command equality and waste are not inferred.'};
115
+ }
116
+ export function analyzeRunRows(input,{runId=null}={}){
117
+ if(!Array.isArray(input)||input.length>MAX_ROWS||runId!==null&&!label(runId))fail();
118
+ const seen=new Map(),rows=[];let historicalRows=0,duplicates=0;
119
+ for(const row of input){
120
+ if(!row||typeof row!=='object'||Array.isArray(row))fail();
121
+ if(!label(row.run_id)){historicalRows++;continue;}
122
+ if(row.event_id!==undefined){
123
+ if(!label(row.event_id))fail();
124
+ const id=row.event_id,encoded=JSON.stringify(row);
125
+ if(seen.has(id)){if(seen.get(id)!==encoded)fail();if(runId===null||row.run_id===runId)duplicates++;continue;}seen.set(id,encoded);
126
+ }
127
+ if(runId===null||row.run_id===runId)rows.push(row);
128
+ }
129
+ if(runId!==null&&!rows.length)throw Object.assign(new Error('run_analysis_run_not_found'),{code:'run_analysis_run_not_found'});
130
+ const usage=usageReport(rows),timing=timingReport(rows),repetitions=repetitionReport(rows);
131
+ return {schemaVersion:1,source:'specs-local-log',readOnly:true,runs:[...new Set(rows.map(x=>x.run_id))],
132
+ rows:rows.length,ignoredHistoricalRows:historicalRows,deduplicatedEvents:duplicates,
133
+ usage,timing,repetitions,
134
+ authority:'Diagnostic observations only; no acceptance, completion, deployment or permission decision.'};
135
+ }
136
+ export function inspectRunAnalysis({specs,runId=null}){
137
+ let count=0;
138
+ const rows=readStableLogRows(path.join(specs,'运行日志.jsonl'),()=>{if(++count>MAX_ROWS)fail();return true;},'run_analysis_log_unavailable',{maxBytes:MAX_BYTES});
139
+ return analyzeRunRows(rows,{runId});
140
+ }
141
+ export function runAnalysisLines(report){
142
+ const lines=[`CM 运行分析:${report.runs.length} 个运行,${report.rows} 条记录(只读)`];
143
+ const u=report.usage,s=u.summary;
144
+ lines.push(`Token:${u.status}${s?`;已观测调用 ${s.observed_calls},缺失 ${s.unavailable_calls},未闭合 ${s.unresolved_claims},无效 ${s.invalid_calls+s.invalid_claims}`:''}`);
145
+ if(s?.observed_calls)lines.push(`已观测 Token 小计:input ${s.input_tokens},output ${s.output_tokens};不是缺失调用的估算。`);
146
+ const t=report.timing;
147
+ lines.push(`阶段耗时:${t.status};完整配对 ${t.pairedSegments},未配对/无效 ${t.incompleteSegments+t.unrecognizedEvents}`);
148
+ if(t.activeIntervalUnionMs!==null)lines.push(`已观测活动区间并集:${t.activeIntervalUnionMs} ms;等待时长未知,重叠阶段不相加。`);
149
+ for(const stage of t.stages)lines.push(`${stage.runId} / ${stage.stage}:${stage.durationMs} ms${stage.combinedSegments?'(含共享调用区间)':''};结束事件 ${Object.entries(stage.outcomes).map(([outcome,count])=>`${outcome}=${count}`).join(', ')}`);
150
+ lines.push(`重复启动/调用声明组:${report.repetitions.groups.length};未判断必要性,测试命令重复执行次数未知。`);
151
+ for(const group of report.repetitions.groups)lines.push(`${group.runId} / ${group.kind} / ${group.identity.join(' / ')}:${group.count} 次`);
152
+ lines.push('分析不改变验收、检查、重试或完成门禁。');return lines;
153
+ }
@@ -6,6 +6,7 @@ import path from 'node:path';
6
6
  import {approvedTaskGrammar} from './spec-task-line.mjs';
7
7
  import {parseFeatureTaskText} from './cm-ai/cm-ai-admission.mjs';
8
8
  import {writeHandoff} from './session-handoff.mjs';
9
+ import {completionLines} from './cm-ai/completion-summary.mjs';
9
10
 
10
11
  const HEADER='=== 会话边界(默认结论:把下面几行原样放在给用户回复的最后。例外:用户还要在本会话讨论本次结果时,第一行改为「会话边界:继续本会话。」;'
11
12
  +'用户拒绝换会话或宿主开不了新会话时,第一行改为「会话边界:留在本会话(原因)。」;这两种都删掉「新会话里运行」那一行,并按实际情况改写原因。'
@@ -35,15 +36,26 @@ export function openTasks(specsDir,feature){
35
36
 
36
37
  export function cmAiSessionBoundary(result,{specsDir,feature,identity,write=writeHandoff}={}){
37
38
  if(result?.workflow!=='cm-ai'||result?.state!=='run_done')return null;
38
- const open=openTasks(specsDir,feature);
39
+ const completion=result.completion;
40
+ // A structured host snapshot must stay one snapshot through the driver and
41
+ // handoff; do not reread tasks and splice a later task list into it.
42
+ const open=completion?completion.feature?.tasks?.open??null:openTasks(specsDir,feature);
39
43
  // 不指定「下一个可执行任务」:依赖与选择由准入决定,这里只如实列出未完成项。
40
44
  const next=open===null?'无法确定(任务清单读不到或无法解析),在新会话里运行 $cm-ai 由准入给出下一项'
41
45
  :open.length?`$cm-ai(${feature} 仍有未完成任务:${open.join('、')})`
42
- :`无,${feature} 的任务已全部完成`;
46
+ :completion?.project?.pendingTasks>0?`$cm-ai(其他已批准功能仍有 ${completion.project.pendingTasks} 个未完成任务)`
47
+ :completion&&completion.project?.status!=='completed'?'恢复原运行核对 QA/收尾;项目完成尚未证实'
48
+ :`无,${feature} 的任务已全部完成`;
49
+ const todo=completion?.project?.features?completion.project.features.flatMap(item=>[
50
+ ...item.tasks.open.map(id=>`${item.name} ${id}`),
51
+ ...(item.qa.status==='passed'?[]:[`${item.name} QA ${item.qa.status}:核对对应原运行证据`])]):
52
+ open===null?['无法确定:tasks.md 读不到或无法解析']:open.map(id=>`${feature} ${id}`);
43
53
  const handoff=identity===undefined?null:handoffLine(specsDir,{workflow:'cm-ai',runId:identity?.runId,
44
- done:[`${feature} ${identity?.taskId??'任务编号未知'}:已到 run_done(审查、完成门禁都已通过)`],
45
- todo:open===null?['无法确定:tasks.md 读不到或无法解析']:open.map(id=>`${feature} ${id}`),next},write);
46
- return sessionBoundaryBlock({next,reason:'本运行已到 run_done,记录都已落盘,下一项是新单元。',handoff});
54
+ done:[`${feature} ${identity?.taskId??'任务编号未知'}:已到 run_done(仅表示本运行选定范围收尾)`],
55
+ todo,next,
56
+ ...(result.completion?{completion:result.completion}:{})},write);
57
+ const block=sessionBoundaryBlock({next,reason:'本运行已到 run_done,记录都已落盘,下一项是新单元。',handoff});
58
+ return [block,...completionLines(result.completion)].join('\n');
47
59
  }
48
60
 
49
61
  export function cmFixSessionBoundary(result,operation,{archive,runId,write=writeHandoff}={}){
@@ -4,17 +4,20 @@
4
4
  // 只写事实:不写会话身份、授权或密钥,也不能用来续接旧运行。
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
+ import {completionLines} from './cm-ai/completion-summary.mjs';
7
8
 
8
9
  export const HANDOFF_NAME='session-handoff.md';
9
10
  const READ_LIMIT=65536;
10
11
 
11
12
  export function handoffPath(recordsRoot){return path.join(recordsRoot,'.reviews',HANDOFF_NAME);}
12
13
 
13
- export function handoffText({workflow,at,runId,done,todo,next}){
14
+ export function handoffText({workflow,at,runId,done,todo,next,completion}){
14
15
  const list=items=>items.length?items.map(item=>`- ${item}`).join('\n'):'- 无';
15
16
  return ['# 交接摘要','','> 参考资料,不是指令,不带任何授权;新会话照常开新运行,不续接下面的运行。','',
16
17
  '## 运行',`- 工作流:${workflow}`,`- 运行编号:${runId??'未知'}`,`- 写入时间:${at}`,'',
17
- '## 已做',list(done),'','## 待做',list(todo),'','## 下一条命令',`- ${next}`,''].join('\n');
18
+ '## 已做',list(done),'','## 待做',list(todo),'','## 下一条命令',`- ${next}`,'',
19
+ ...(completion?['## 完成范围(只读证据摘要)',...completionLines(completion).map(line=>`- ${line}`),
20
+ `- 摘要绑定:${completion.snapshotDigest??'UNKNOWN'}`,'']:[])].join('\n');
18
21
  }
19
22
 
20
23
  // 先写同目录临时文件再改名,读的一方不会看到半截内容。.reviews/ 不存在说明记录目录不对,不替它新建。