@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
@@ -0,0 +1,252 @@
1
+ // A projection of approved material, never an approval or a second specs store.
2
+ // Free text remains verbatim for independent review; the machine proves set and
3
+ // evidence-kind agreement, not that arbitrary prose or test assertions are true.
4
+ import {digest,need,shape,freeze} from './effect-contract.mjs';
5
+ import {declaredAcceptanceIds} from './cm-ai-admission.mjs';
6
+ import {taskLines} from '../spec-task-line.mjs';
7
+ import {mandatoryCheckCoverage} from '../check-coverage.mjs';
8
+ import {selectedNodeTestFiles} from '../node-test-selection.mjs';
9
+
10
+ const TYPES=['review','host-run','host-check','browser','device'];
11
+ const ENVIRONMENTS=['local','browser','device'];
12
+ const text=v=>typeof v==='string'&&v.trim().length>0;
13
+ export function readAcceptanceContract(value){
14
+ shape(value,['version','taskId','obligations','requiredTests','requiredCommands','unresolved']);
15
+ need(value.version===1&&/^T-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value.taskId),'invalid_input');
16
+ need(Array.isArray(value.obligations)&&value.obligations.length>0&&value.obligations.length<=64,'invalid_input');
17
+ const ids=new Set();
18
+ for(const item of value.obligations){
19
+ shape(item,['id','requirement','evidenceType','environment','run','result']);
20
+ need(text(item.id)&&!ids.has(item.id)&&text(item.requirement)&&Buffer.byteLength(item.requirement)<=2000,'invalid_input');ids.add(item.id);
21
+ need(TYPES.includes(item.evidenceType)&&ENVIRONMENTS.includes(item.environment)
22
+ &&[null,'red','baseline'].includes(item.run),'invalid_input');
23
+ need((item.run!==null)===(item.evidenceType==='host-run'),'invalid_input');
24
+ need([null,'passed','failed'].includes(item.result),'invalid_input');
25
+ }
26
+ for(const key of ['requiredTests','unresolved'])need(Array.isArray(value[key])&&value[key].every(text)
27
+ &&new Set(value[key]).size===value[key].length,'invalid_input');
28
+ need(Array.isArray(value.requiredCommands)&&value.requiredCommands.every(argv=>Array.isArray(argv)&&argv.length>0&&argv.every(text)),'invalid_input');
29
+ return freeze(value);
30
+ }
31
+
32
+ // Explicit run vocabulary only. Other prose is not silently interpreted as a
33
+ // host-observed result: its full obligation still has to be answered/reviewed.
34
+ function kindFor(requirement,kind=null){
35
+ const redMention=/\bRED\b|先失败|先红/i.test(requirement);
36
+ const negatedRed=/(?:不要求|不需要|无需|不用|禁止|不要)[^,。;;\n]{0,16}(?:\bRED\b|先失败|先红)|(?:\bRED\b|先失败|先红)[^,。;;\n]{0,12}(?:不要求|不需要|无需)|\b(?:not required|need not|do not)\b[^.;\n]{0,24}\b(?:fail|red)\b/i.test(requirement);
37
+ const red=redMention&&!negatedRed;
38
+ const baseline=/\bbaseline\b|基线/i.test(requirement);
39
+ const device=/真机|物理设备|设备[::]\s*需要/.test(requirement);
40
+ const browser=kind==='browser';
41
+ const noOutcome=/(?:不要求|无需|不需要|不用)[^,。;;\n]{0,8}(?:通过|成功|失败)|\b(?:need not|not required to)\s+(?:pass|fail)\b/i.test(requirement);
42
+ const negativePass=/(?:不通过|未通过|不能通过|不得通过|不成功)|\b(?:must|should|shall)\s+not\s+pass\b|\b(?:not pass|must fail)\b/i.test(requirement);
43
+ const negativeFail=/(?:不能失败|不得失败|不失败)|\b(?:must|should|shall)\s+not\s+fail\b/i.test(requirement);
44
+ const outcomeText=requirement.replace(/(?:不通过|未通过|不能通过|不得通过|不成功|不能失败|不得失败|不失败)|\b(?:must|should|shall)\s+not\s+(?:pass|fail)\b|\bnot pass\b/gi,'');
45
+ const passed=baseline&&!noOutcome&&(negativeFail||/通过|成功|\bpass(?:ed)?\b/i.test(outcomeText));
46
+ const failed=baseline&&!noOutcome&&(negativePass||/失败|\bfail(?:ed)?\b/i.test(outcomeText));
47
+ const unknownNegation=(baseline||redMention)&&/(?:\bnot\b|\bnever\b|n't|不|无需|无须|禁止|勿)/i.test(requirement)
48
+ &&!(noOutcome||negativePass||negativeFail||negatedRed);
49
+ const ambiguous=Number(red)+Number(baseline)+Number(device)+Number(browser)>1||passed&&failed||unknownNegation;
50
+ return {ambiguous,evidenceType:device?'device':browser?'browser':red||baseline?'host-run':'review',
51
+ environment:device?'device':browser?'browser':'local',run:device||browser?null:red?'red':baseline?'baseline':null,
52
+ result:unknownNegation?null:red?'failed':baseline&&passed?'passed':baseline&&failed?'failed':null};
53
+ }
54
+
55
+ // Only explicit declaration markers opt a newly created task into mandatory
56
+ // machine evidence. Existing descriptive fields (ACs, 测试文件, 基线, 设备) alone
57
+ // do not migrate an old specification to a new execution contract.
58
+ export const hasMandatoryAcceptance=value=>/(?:必验(?:合同|条款)?|必跑测试|必跑检查|mandatory\s+acceptance)\s*[::]/i.test(value);
59
+ const bareCommand=value=>{
60
+ const tokens=value.trim().split(/\s+/),[engine,...args]=tokens;
61
+ const script=(file,extensions)=>typeof file==='string'&&!file.startsWith('-')&&!file.startsWith('/')
62
+ &&file.replace(/^\.\//,'').split('/').every(part=>part&&part!=='.'&&part!=='..')&&extensions.test(file);
63
+ if(engine==='node'){
64
+ if(args[0]==='--test'||args.some(arg=>arg==='--test')){
65
+ const files=selectedNodeTestFiles([process.execPath,...args]);
66
+ return files!==null&&files.every(file=>script(file,/\.(?:mjs|cjs|js)$/));
67
+ }
68
+ return args.length===1&&script(args[0],/\.(?:mjs|cjs|js)$/)
69
+ ||args.length===2&&['--check','-c'].includes(args[0])&&script(args[1],/\.(?:mjs|cjs|js)$/);
70
+ }
71
+ if(/^\.\/[^\s]+$/.test(engine))return args.length===0;
72
+ if(['bash','sh'].includes(engine))return args.length===1&&script(args[0],/\.sh$/);
73
+ if(['python','python3'].includes(engine))return args.length===1&&script(args[0],/\.py$/);
74
+ if(['npm','pnpm','yarn'].includes(engine))return args.length===1&&['test','build','check'].includes(args[0])
75
+ ||args.length===2&&args[0]==='run'&&/^[A-Za-z0-9][A-Za-z0-9:_-]*$/.test(args[1]);
76
+ // Other argv needs an explicitly delimited command declaration. In prose an
77
+ // executable name is not enough evidence that the rest of the line is argv.
78
+ return false;
79
+ };
80
+ const commandContext=value=>value.trim().replace(/^#{1,6}\s+/,'').replace(/\s+#+\s*$/,'')
81
+ .replace(/^(?:[-*+]|\d+[.)])\s+/,'').replace(/^\[[ xX]\]\s*/,'')
82
+ .replace(/^T-[\w.-]+\s*[::]\s*/,'').replace(/^\[AC-\d+\]\s*/,'').replace(/^(?:steps|expected):\s*/,'');
83
+ // This is a declaration grammar, not a list of ways to forbid execution.
84
+ // An ancestor only authorizes children when its entire content is this label.
85
+ const commandDeclaration=value=>/^(?:必跑检查|必跑命令|运行|执行|验证命令|检查命令|mandatory\s+acceptance|required\s+(?:checks?|commands?))(?:\s*[::]\s*|\s+|$)(.*)$/i.exec(value)?.[1]??null;
86
+ export function buildAcceptanceContract({taskId,taskText,requirementsText,testCases=[],explicitOnly=false}){
87
+ let mandatory=false;
88
+ const obligations=[],unresolved=[],requiredTests=[],requiredCommands=[],seen=new Map(),referencedCases=new Set();
89
+ const parents=[];let parentSource=null;
90
+ const add=(source,requirement,kind=null,fenced=false)=>{
91
+ if(!requirement.trim())return;
92
+ // The nearest containing list item or heading is authoritative. A closer
93
+ // non-declaration shadows a mandatory ancestor, regardless of its wording.
94
+ const indent=/^[ \t]*/.exec(requirement)[0].length;
95
+ const heading=fenced?null:/^\s*(#{1,6})\s+/.exec(requirement)?.[1].length??null;
96
+ if(parentSource!==source){parents.length=0;parentSource=source;}
97
+ while(parents.length){
98
+ const parent=parents.at(-1);
99
+ if(parent.indent<indent||parent.indent===indent&&parent.heading!==null
100
+ &&(heading===null||parent.heading<heading))break;
101
+ parents.pop();
102
+ }
103
+ const inheritedMandatory=parents.at(-1)?.mandatory===true;
104
+ const standalone=commandContext(requirement),declaration=commandDeclaration(standalone);
105
+ parents.push({indent,heading,mandatory:!fenced&&declaration===''});requirement=requirement.trim();
106
+ if(hasMandatoryAcceptance(requirement))mandatory=true;
107
+ for(const id of requirement.match(/\bTC-\d{3,}\b/g)??[])referencedCases.add(id);
108
+ if(/(?:测试文件|必跑测试)[::]/.test(requirement)){
109
+ const tests=[...requirement.matchAll(/`([^`]+)`/g)].map(match=>match[1]);
110
+ if(!tests.length)unresolved.push(`${source}: test declarations require explicit backtick-delimited identifiers`);
111
+ requiredTests.push(...tests);
112
+ }
113
+ // Parse only a standalone command or a backtick-delimited command. Shell
114
+ // operators/substitutions and ambiguous quoting require approved mapping.
115
+ const command=/^(?:(?:node|npm|pnpm|yarn|python3?|bash|sh|xcodebuild|xcrun|swift|go|cargo)\s|\.\/[^\s]+(?:\s|$))/;
116
+ const commandText=declaration??standalone;
117
+ let candidates=[...commandText.matchAll(/`([^`]+)`/g)].map(match=>match[1]);
118
+ if(command.test(commandText)){
119
+ if(bareCommand(commandText))candidates=[commandText];
120
+ else {unresolved.push(`${source}: command context is not an explicit mandatory declaration`);candidates=[];}
121
+ }
122
+ else if(candidates.some(value=>command.test(value))){
123
+ const context=commandText.replace(/`[^`]+`/g,'<command>');
124
+ if(!/^<command>(?:\s*[,,;;]\s*<command>)*[。.]?$/.test(context)){
125
+ unresolved.push(`${source}: command context is not an explicit mandatory declaration`);candidates=[];
126
+ }
127
+ }
128
+ if(!(declaration!==null&&!fenced||inheritedMandatory)&&candidates.some(value=>command.test(value))){
129
+ unresolved.push(`${source}: command context requires an explicit mandatory declaration on this line or its nearest parent/heading`);candidates=[];
130
+ }
131
+ let commandCount=0;
132
+ for(const candidate of candidates.filter(value=>command.test(value))){
133
+ if(!/^[A-Za-z0-9_./:=,@%+ -]+$/.test(candidate)){
134
+ unresolved.push(`${source}: command requires explicit argv mapping; shell syntax is not inferred`);continue;
135
+ }
136
+ requiredCommands.push(candidate.trim().split(/\s+/));commandCount++;
137
+ }
138
+ if(Buffer.byteLength(requirement)>2000||obligations.length>=64){unresolved.push(`${source}: requirement exceeds evidence bounds; split in approved specs`);return;}
139
+ const key=`${source}:${digest(requirement).slice(0,16)}`,n=seen.get(key)??0;seen.set(key,n+1);
140
+ const {ambiguous,...evidence}=kindFor(requirement,kind);
141
+ if(ambiguous||commandCount&&evidence.environment!=='local')unresolved.push(`${source}: compound evidence requirement; split environment/run obligations in approved specs`);
142
+ if(commandCount&&evidence.evidenceType==='review')evidence.evidenceType='host-check';
143
+ obligations.push({id:`${key}:${n+1}`,requirement,...evidence});
144
+ };
145
+ // Keep subclauses, headings and fences; no "short task description" shortcut.
146
+ for(const {body,fenced} of taskLines(taskText))add(`task:${taskId}`,body,null,fenced);
147
+ const linked=new Set(taskText.match(/\bAC-\d{3,}\b/g)??[]);
148
+ for(const item of testCases)for(const id of item.acIds??[])linked.add(id);
149
+ const declared=new Set();let owner=null,ownerIndent=0;
150
+ for(const {body:line,fenced} of taskLines(requirementsText)){
151
+ const match=fenced?[]:[...declaredAcceptanceIds(line)],indent=/^[ \t]*/.exec(line)[0].length;
152
+ if(match.length){owner=match[0];ownerIndent=indent;declared.add(owner);}
153
+ else if(line.trim()&&indent<=ownerIndent)owner=null;
154
+ // Only explicitly linked AC blocks and explicit shared directives are duties.
155
+ // An indented heading never cuts off an AC's environment/expected subclauses.
156
+ if(owner!==null&&linked.has(owner)||owner===null&&/^\s*(?:Shared|共用必验)[::]/i.test(line))add(owner??'requirements:shared',line,null,fenced);
157
+ }
158
+ if(declared.size&&!linked.size)unresolved.push('acceptance criteria have no explicit task/case mapping');
159
+ for(const id of linked)if(!declared.has(id))unresolved.push(`${id}: undeclared acceptance criterion`);
160
+ const compiledCases=new Set(),caseMap=new Map(testCases.map(item=>[item.id,item]));
161
+ if(caseMap.size!==testCases.length)unresolved.push('duplicate case IDs cannot establish acceptance mapping');
162
+ const pending=testCases.filter(item=>item.blocking===true||referencedCases.has(item.id));
163
+ for(let index=0;index<pending.length;index++){
164
+ const item=pending[index];if(compiledCases.has(item.id))continue;compiledCases.add(item.id);
165
+ add(item.id,`${item.id}: ${item.title}`,item.kind);
166
+ for(const field of ['preconditions','steps','expected','cleanup'])for(const entry of item[field]??[])
167
+ add(`${item.id}:${field}`,`${field}: ${entry}`,item.kind);
168
+ for(const id of referencedCases)if(!compiledCases.has(id)&&caseMap.has(id)&&!pending.some(item=>item.id===id))pending.push(caseMap.get(id));
169
+ }
170
+ for(const id of referencedCases)if(!testCases.some(item=>item.id===id))unresolved.push(`${id}: missing task-bound case mapping`);
171
+ if(!obligations.length){
172
+ unresolved.push('no bounded acceptance obligation; split the approved source before execution');
173
+ obligations.push({id:`task:${taskId}:unmapped`,requirement:'Approved source requires explicit bounded acceptance mapping',
174
+ evidenceType:'review',environment:'local',run:null,result:null});
175
+ }
176
+ if(Buffer.byteLength(JSON.stringify(obligations))>40*1024)unresolved.push('acceptance set exceeds report budget; split the approved task');
177
+ const tests=[...new Set(requiredTests)].filter(value=>{
178
+ const valid=!value.startsWith('/')&&!/[\\\x00-\x1f]/.test(value)
179
+ &&value.replace(/^\.\//,'').split('/').every(part=>part&&part!=='.'&&part!=='..');
180
+ if(!valid)unresolved.push('mandatory tests require canonical relative identifiers');return valid;
181
+ });
182
+ if(explicitOnly&&!mandatory)return null;
183
+ return readAcceptanceContract({version:1,taskId,obligations,requiredTests:tests,
184
+ requiredCommands:[...new Map(requiredCommands.map(argv=>[JSON.stringify(argv),argv])).values()],unresolved:[...new Set(unresolved)]});
185
+ }
186
+
187
+ // Commands are taken from approved text and compared with checks actually
188
+ // collected, not developer prose. Only the running Node binary normalizes to
189
+ // `node`; an arbitrary project executable with the same basename does not.
190
+ export function acceptanceCoverage(contract,checks){
191
+ const commands=checks.filter(item=>Array.isArray(item.command)).map(item=>item.command);
192
+ const coverage=mandatoryCheckCoverage({requiredTests:contract.requiredTests,commands});
193
+ const engines=new Map([[process.execPath,'node'],['/usr/bin/xcodebuild','xcodebuild'],['/usr/bin/xcrun','xcrun']]);
194
+ const normalize=argv=>argv.map((token,index)=>index===0?(engines.get(token)??token):token);
195
+ const native=new Set(engines.values());
196
+ const missingCommands=contract.requiredCommands.filter(expected=>!checks.some(check=>check.outcome==='passed'
197
+ &&Array.isArray(check.command)&&(!native.has(normalize(expected)[0])||engines.has(check.command[0]))
198
+ &&digest(normalize(check.command))===digest(normalize(expected))));
199
+ return {...coverage,satisfied:coverage.satisfied&&missingCommands.length===0,missingCommands};
200
+ }
201
+
202
+ export function acceptanceProblems(contract,items,facts=null){
203
+ readAcceptanceContract(contract);
204
+ const problems=[...contract.unresolved];
205
+ if(!Array.isArray(items))return [...problems,'mandatory acceptance report missing'];
206
+ const expected=new Map(contract.obligations.map(item=>[item.id,item])),seen=new Set();
207
+ for(const item of items){
208
+ const obligation=expected.get(item.id);
209
+ if(!obligation||seen.has(item.id)){problems.push('unknown or duplicate acceptance ID');continue;}seen.add(item.id);
210
+ if(item.satisfied!==true||!text(item.evidence))problems.push(`${item.id}: unsatisfied`);
211
+ if(['requirement','evidenceType','environment'].some(key=>item[key]!==obligation[key]))problems.push(`${item.id}: acceptance evidence mismatch`);
212
+ if((item.run??null)!==obligation.run)problems.push(`${item.id}: required run tag mismatch`);
213
+ // An asserted baseline outcome is part of the approved contract, not an
214
+ // optional claim the developer may remove to avoid contradiction checks.
215
+ if(obligation.run==='baseline'&&obligation.result!==null&&facts?.baseline?.outcome!==obligation.result)
216
+ problems.push(`${item.id}: required baseline outcome mismatch`);
217
+ if(obligation.run==='red'&&!(facts?.status==='replayed'&&!facts.red?.skipped&&facts.red?.outcome==='failed'))
218
+ problems.push(`${item.id}: host RED evidence missing`);
219
+ if(obligation.run==='baseline'&&!(facts?.status==='replayed'&&['passed','failed'].includes(facts.baseline?.outcome)))
220
+ problems.push(`${item.id}: host baseline evidence missing`);
221
+ if(item.run==='baseline'&&item.result&&item.result!==facts?.baseline?.outcome)problems.push(`${item.id}: baseline result mismatch`);
222
+ }
223
+ for(const id of expected.keys())if(!seen.has(id))problems.push(`${id}: missing acceptance obligation`);
224
+ return problems;
225
+ }
226
+
227
+ // Describe the validator's exact failures; this adds source text for operators,
228
+ // never a second verdict. Hosts bound/sanitize the final diagnostic for storage.
229
+ export function describeAcceptanceProblems(contract,problems){
230
+ return problems.map(problem=>{
231
+ const obligation=contract.obligations.find(item=>problem.startsWith(`${item.id}: `));
232
+ return obligation?`${problem} [${obligation.requirement}]`:problem;
233
+ });
234
+ }
235
+
236
+ export const ACCEPTANCE_EVIDENCE_PREFIX='cm-acceptance-contract-v1: ';
237
+ export function encodeAcceptanceEvidence({contract,identity,items,facts,coverage}){
238
+ need(acceptanceProblems(contract,items,facts).length===0,'verification_precheck_failed');
239
+ need(coverage?.satisfied===true,'verification_precheck_failed');
240
+ return ACCEPTANCE_EVIDENCE_PREFIX+JSON.stringify({version:1,contractDigest:digest(contract),identity,items,facts,coverage});
241
+ }
242
+ export function verifyAcceptanceEvidence({contract,identity,evidence}){
243
+ try{
244
+ const records=evidence.filter(item=>typeof item==='string'&&item.startsWith(ACCEPTANCE_EVIDENCE_PREFIX));
245
+ need(records.length===1,'verification_precheck_failed');
246
+ const value=JSON.parse(records[0].slice(ACCEPTANCE_EVIDENCE_PREFIX.length));
247
+ shape(value,['version','contractDigest','identity','items','facts','coverage']);
248
+ need(value.version===1&&value.contractDigest===digest(contract)&&digest(value.identity)===digest(identity),'verification_precheck_failed');
249
+ need(acceptanceProblems(contract,value.items,value.facts).length===0&&value.coverage?.satisfied===true,'verification_precheck_failed');
250
+ return true;
251
+ }catch{need(false,'verification_precheck_failed');}
252
+ }
@@ -164,6 +164,24 @@
164
164
  "failed",
165
165
  null
166
166
  ]
167
+ },
168
+ "id": {
169
+ "type": [
170
+ "string",
171
+ "null"
172
+ ]
173
+ },
174
+ "evidenceType": {
175
+ "type": [
176
+ "string",
177
+ "null"
178
+ ]
179
+ },
180
+ "environment": {
181
+ "type": [
182
+ "string",
183
+ "null"
184
+ ]
167
185
  }
168
186
  }
169
187
  }
@@ -380,6 +380,19 @@ export function inspectCmAiAdmission(options){
380
380
  }
381
381
 
382
382
  // The CLI supplies every code project so no project can be skipped before writing.
383
+ // Shared by approval and its read-only preview; returns diagnostics only.
384
+ export function inspectTaskGrammarTransition(source,{grammar,fromLegacy=false}){
385
+ const parsed=parseFeatureTaskText(source,{allowDependencyPunctuation:true,grammar});
386
+ if(parsed.error)return {parsed,differing:[]};
387
+ if(!fromLegacy)return {parsed,differing:[]};
388
+ const view=version=>taskDeclarations(source,{grammar:version}).map(item=>({line:item.index+1,
389
+ key:`${item.id}\0${item.completed}\0${item.body.trim()}`,text:item.body.trim()}));
390
+ const legacy=view(LEGACY_TASK_GRAMMAR),current=view(grammar);
391
+ const legacyKeys=new Set(legacy.map(item=>item.key)),currentKeys=new Set(current.map(item=>item.key));
392
+ return {parsed,differing:[...current.filter(item=>!legacyKeys.has(item.key)),...legacy.filter(item=>!currentKeys.has(item.key))]
393
+ .sort((a,b)=>a.line-b.line)};
394
+ }
395
+
383
396
  export function approveCmAiSpecs(options){
384
397
  const projects=options.codeProjects??[options.codeProject];
385
398
  // The standing authorization (autonomy.mjs) stands in for the reply, and only for a bound change proposal.
@@ -446,15 +459,10 @@ export function approveCmAiSpecs(options){
446
459
  const grammar=status.kind==='valid'&&!fromLegacy?status.value.taskGrammar:SHARED_TASK_GRAMMAR;
447
460
  for(const name of discovered.names){
448
461
  const source=fs.readFileSync(path.join(specsDir,name,'tasks.md'),'utf8');
449
- const parsed=parseFeatureTaskText(source,{allowDependencyPunctuation:true,grammar});
462
+ const {parsed,differing}=inspectTaskGrammarTransition(source,{grammar,fromLegacy});
450
463
  if(parsed.error)return refuse('task_grammar_conflict',`${name}/tasks.md 第 ${parsed.detail.line} 行在新任务行语法下无效(${parsed.error}):`
451
464
  +`${parsed.detail.text}。此前的批准把它当作说明文字;把这类示例放进 \`\`\` 围栏或删去后再批准。`);
452
465
  if(!fromLegacy)continue;
453
- const view=grammar=>taskDeclarations(source,{grammar}).map(item=>({line:item.index+1,key:`${item.id}\0${item.completed}\0${item.body.trim()}`,text:item.body.trim()}));
454
- const legacy=view(LEGACY_TASK_GRAMMAR),current=view(grammar);
455
- const legacyKeys=new Set(legacy.map(item=>item.key)),currentKeys=new Set(current.map(item=>item.key));
456
- const differing=[...current.filter(item=>!legacyKeys.has(item.key)),...legacy.filter(item=>!currentKeys.has(item.key))]
457
- .sort((a,b)=>a.line-b.line);
458
466
  if(differing.length)return refuse('task_grammar_conflict',`${name}/tasks.md 在新任务行语法下任务集合会变化:`
459
467
  +differing.slice(0,5).map(item=>`第 ${item.line} 行 ${item.text}`).join(';')+`${differing.length>5?` 等 ${differing.length} 行`:''}`
460
468
  +'。此前的批准不把这些行当任务(或反之);是示例就放进 ``` 围栏或删去,是任务就改用英文冒号「:」写法后再批准。');
@@ -15,6 +15,7 @@ import {REVIEWED_HANDOFF_HINT} from './host-handoff.mjs';
15
15
  import {readHostQaFixHandoff} from './host-qa-fix.mjs';
16
16
  import {readCloseoutPolicy,readCloseoutReport,closeoutSummary} from './knowledge-closeout.mjs';
17
17
  import {digest,freeze,hex,id,json,need,shape,text,validIdentity} from './effect-contract.mjs';
18
+ import {completionSummary,taskCompletion} from './completion-summary.mjs';
18
19
 
19
20
  const sameIdentity=(left,right)=>['repositoryId','runId','taskId','attempt'].every(key=>left[key]===right[key]);
20
21
  const sameTask=(left,right)=>['repositoryId','runId','taskId'].every(key=>left[key]===right[key]);
@@ -97,7 +98,7 @@ export const developFailureClass=status=>{
97
98
  };
98
99
  const summary=(operation,status,outcome)=>freeze({version:1,workflow:'cm-ai',operation:operation.operation,
99
100
  requestDigest:digest(operation),identity:status.identity,outcome,state:status.state,code:status.code??null,
100
- packageDigest:status.packageDigest??null,pendingAction:pendingAction(status),
101
+ packageDigest:status.packageDigest??null,pendingAction:pendingAction(status),completion:{task:taskCompletion(status)},
101
102
  ...(status.reviewReconciliation?{reviewReconciliation:status.reviewReconciliation}:{}),
102
103
  ...(status.effectiveScope?{effectiveScope:status.effectiveScope}:{}),
103
104
  ...(status.acceptedIntegrationDigest?{acceptedIntegrationDigest:status.acceptedIntegrationDigest}:{}),
@@ -218,7 +219,7 @@ const contextSummary=(operation,status,refresh)=>freeze({version:1,workflow:'cm-
218
219
  requestDigest:digest(operation),identity:status.identity,outcome:'refreshed',state:status.state,
219
220
  code:refresh.state==='complete'?'context_complete':'context_refreshed',packageDigest:status.packageDigest,
220
221
  pendingAction:refresh.state==='complete'?'finish':'start_next_task',nextTask:refresh.nextTask,
221
- contextDigest:refresh.contextDigest,contextFiles:refresh.contextFiles});
222
+ contextDigest:refresh.contextDigest,contextFiles:refresh.contextFiles,completion:{task:taskCompletion(status)}});
222
223
 
223
224
  function validateDocumentationResult(result,status,refresh,policy=null) {
224
225
  shape(result,['syncId','identity','packageDigest','contextDigest','status','reason','at',
@@ -877,13 +878,15 @@ export function createCmAiConversationEntry(options) {
877
878
  +'宿主只在运行日志记有该命令进程组身份且核对进程组已退出时补记释放;先结束残留进程后重发 run_finalize,记录里没有进程身份的旧资源需人工处理。'},'blocked');
878
879
  const input={specsDir:options.specsDir,codeProject:options.codeProject,feature:options.feature,identity,
879
880
  packageDigest:operation.packageDigest,contextDigest:refresh.contextDigest,
880
- documentationSyncId:documentation.syncId};
881
+ documentationSyncId:documentation.syncId,
882
+ scopeFeatures:[...new Set(refresh.contextFiles.filter(file=>file.scope==='specs'&&file.path.endsWith('/tasks.md'))
883
+ .map(file=>file.path.split('/')[0]))].sort()};
881
884
  if(Object.hasOwn(options,'qaLogHome'))input.logHome=options.qaLogHome;
882
885
  const result=recordCmAiRunDone(input);
883
886
  return freeze({version:1,workflow:'cm-ai',operation:operation.operation,requestDigest:digest(operation),identity,
884
887
  outcome:'finalized',state:'run_done',code:result.degraded?'run_done_degraded':'run_done',
885
888
  packageDigest:operation.packageDigest,pendingAction:'none',contextDigest:refresh.contextDigest,
886
- deduplicated:result.deduplicated,degraded:result.degraded,
889
+ deduplicated:result.deduplicated,degraded:result.degraded,completion:{task:taskCompletion(status)},
887
890
  ...closeoutSummary(knowledgeCloseout,documentation)});
888
891
  }
889
892
  need(['start','resume'].includes(operation.operation),'invalid_input');
@@ -927,8 +930,9 @@ export function createCmAiConversationEntry(options) {
927
930
  token=Symbol(operation.operation);inFlightHandles.add(token);
928
931
  }
929
932
  const routed=await route(operation);
930
- const guidance=operatorGuidance(routed,{executionActive:inFlightHandles.size>(token===null?0:1)});
931
- const result=guidance?freeze({...routed,guidance}):routed;
933
+ const projected={...routed,completion:completionSummary({specsDir:options.specsDir,feature:options.feature,result:routed})};
934
+ const guidance=operatorGuidance(projected,{executionActive:inFlightHandles.size>(token===null?0:1)});
935
+ const result=freeze({...projected,...(guidance?{guidance}:{})});
932
936
  if(!admissionReports.has(routed)&&(epoch===cancellationEpoch||operation.operation==='cancel'))projectHostResult({specsDir:options.specsDir,
933
937
  feature:options.feature,result,readCurrent:()=>runner.status()});
934
938
  return result;
@@ -40,15 +40,20 @@ function readResult(stdout,identity,specsDir) {
40
40
  export function recordCmAiRunDone(input) {
41
41
  const keys=['specsDir','codeProject','feature','identity','packageDigest','contextDigest','documentationSyncId'];
42
42
  if(input&&Object.hasOwn(input,'logHome'))keys.push('logHome');
43
+ if(input&&Object.hasOwn(input,'scopeFeatures'))keys.push('scopeFeatures');
43
44
  shape(input,keys);text(input.specsDir);text(input.codeProject);text(input.feature);validIdentity(input.identity);
44
45
  hex(input.packageDigest);hex(input.contextDigest);id(input.documentationSyncId);
46
+ if(Object.hasOwn(input,'scopeFeatures'))need(Array.isArray(input.scopeFeatures)&&input.scopeFeatures.length>0
47
+ &&new Set(input.scopeFeatures).size===input.scopeFeatures.length&&input.scopeFeatures.includes(input.feature)
48
+ &&input.scopeFeatures.every(name=>typeof name==='string'&&/^\d+\.[^/\\\x00-\x1f]+$/.test(name)),'invalid_input');
45
49
  need(validRunId(input.identity.runId),'invalid_run_id');
46
50
  statusTarget(input.specsDir);
47
51
  const data={node:'N8',feature:input.feature,task:input.identity.taskId,package_digest:input.packageDigest,
48
- context_digest:input.contextDigest,documentation_sync_id:input.documentationSyncId};
52
+ context_digest:input.contextDigest,documentation_sync_id:input.documentationSyncId,
53
+ ...(input.scopeFeatures?{scope_features:input.scopeFeatures,repository_id:input.identity.repositoryId,attempt:input.identity.attempt}:{})};
49
54
  const args=[writer,'--workflow','cm-ai','--event','run_done','--runtime','codex',
50
55
  '--project-root',input.codeProject,'--specs-dir',input.specsDir,'--run-id',input.identity.runId,
51
- '--detail','全部任务和文档同步已完成','--data-json',JSON.stringify(data)];
56
+ '--detail','本运行选定范围已通过收尾门禁;产品验收与部署另计','--data-json',JSON.stringify(data)];
52
57
  const options={timeout:10000,maxBuffer:MiB,killSignal:'SIGKILL'};
53
58
  if(Object.hasOwn(input,'logHome')){text(input.logHome);options.env={...process.env,CM_WORKFLOW_LOG_HOME:input.logHome};}
54
59
  let result;
@@ -61,7 +66,7 @@ export function recordCmAiRunDone(input) {
61
66
  catch{need(false,'run_finalize_unknown');}
62
67
  try {
63
68
  writeStatusProjection({specsDir:input.specsDir,feature:input.feature,identity:input.identity,node:'N8',
64
- state:'run_done',detail:'全部任务和文档同步已完成'});
69
+ state:'run_done',detail:'本运行选定范围已收尾;产品验收与部署未由本记录证明'});
65
70
  }catch{need(false,'run_finalize_unknown');}
66
71
  return Object.freeze({eventId:receipt.event_id,runId:receipt.run_id,
67
72
  deduplicated:receipt.deduplicated,degraded:receipt.degraded});
@@ -5,6 +5,6 @@
5
5
  "properties": {
6
6
  "outcome": {"type": "string", "enum": ["implemented", "blocked"]},
7
7
  "reason": {"type": ["string", "null"]},
8
- "requirements": {"type": ["array", "null"], "maxItems": 64, "items": {"type": "object", "additionalProperties": false, "required": ["requirement", "satisfied", "evidence", "run", "result"], "properties": {"requirement": {"type": "string"}, "satisfied": {"type": "boolean"}, "evidence": {"type": "string"}, "run": {"type": ["string", "null"], "enum": ["red", "baseline", null]}, "result": {"type": ["string", "null"], "enum": ["passed", "failed", null]}}}}
8
+ "requirements": {"type": ["array", "null"], "maxItems": 64, "items": {"type": "object", "additionalProperties": false, "required": ["requirement", "satisfied", "evidence", "run", "result", "id", "evidenceType", "environment"], "properties": {"requirement": {"type": "string"}, "satisfied": {"type": "boolean"}, "evidence": {"type": "string"}, "run": {"type": ["string", "null"], "enum": ["red", "baseline", null]}, "result": {"type": ["string", "null"], "enum": ["passed", "failed", null]}, "id": {"type": ["string", "null"]}, "evidenceType": {"type": ["string", "null"]}, "environment": {"type": ["string", "null"]}}}}
9
9
  }
10
10
  }
@@ -5,7 +5,7 @@
5
5
  "properties": {
6
6
  "outcome": {"type": "string", "enum": ["implemented", "blocked"]},
7
7
  "reason": {"type": ["string", "null"]},
8
- "requirements": {"type": ["array", "null"], "maxItems": 64, "items": {"type": "object", "additionalProperties": false, "required": ["requirement", "satisfied", "evidence", "run", "result"], "properties": {"requirement": {"type": "string"}, "satisfied": {"type": "boolean"}, "evidence": {"type": "string"}, "run": {"type": ["string", "null"], "enum": ["red", "baseline", null]}, "result": {"type": ["string", "null"], "enum": ["passed", "failed", null]}}}},
8
+ "requirements": {"type": ["array", "null"], "maxItems": 64, "items": {"type": "object", "additionalProperties": false, "required": ["requirement", "satisfied", "evidence", "run", "result", "id", "evidenceType", "environment"], "properties": {"requirement": {"type": "string"}, "satisfied": {"type": "boolean"}, "evidence": {"type": "string"}, "run": {"type": ["string", "null"], "enum": ["red", "baseline", null]}, "result": {"type": ["string", "null"], "enum": ["passed", "failed", null]}, "id": {"type": ["string", "null"]}, "evidenceType": {"type": ["string", "null"]}, "environment": {"type": ["string", "null"]}}}},
9
9
  "application": {
10
10
  "type": "object", "additionalProperties": false,
11
11
  "required": ["status", "note"],
@@ -0,0 +1,187 @@
1
+ // Read-only completion projection. It neither authorizes a transition nor writes
2
+ // task state. The host supplies its already validated runner status; all wider
3
+ // claims come from the approved inventory and strictly bound latest QA evidence.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import {verifyApprovedManifest} from '../../../scripts/cm-spec-manifest.mjs';
7
+ import {recordedTaskGrammar} from '../spec-task-line.mjs';
8
+ import {parseFeatureTaskText} from './cm-ai-admission.mjs';
9
+ import {findCmAiQaDecision,latestCmAiQaRun} from './cm-ai-qa-log.mjs';
10
+ import {readReviewSourceFiles} from './review-package.mjs';
11
+ import {readStableLogRows} from './log-rows.mjs';
12
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
13
+ import {readRunnerHistory} from './durable-runner-state.mjs';
14
+ import {digest,freeze,need} from './effect-contract.mjs';
15
+ import {deliveryProjection} from './delivery-evidence.mjs';
16
+
17
+ const unknown=reason=>({status:'unknown',reason,evidence:[]});
18
+ const sameIdentity=(a,b)=>a&&b&&['repositoryId','runId','taskId','attempt'].every(key=>a[key]===b[key]);
19
+ const blockedCodes=new Set(['correction_review_required','spec_drift']);
20
+ const safeCode=error=>typeof error?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(error.code)?error.code:'completion_evidence_unavailable';
21
+
22
+ // The receipt has already passed the owning runner's registration/replay gates.
23
+ // These checks prevent this display from accidentally pairing a previous receipt
24
+ // with a different task/attempt/candidate; they are not a new completion gate.
25
+ export function taskCompletion(status){
26
+ const receipt=status?.receipt,{receiptDigest,...body}=receipt??{};
27
+ const matched=receipt?.kind==='cm-review-receipt'&&sameIdentity(receipt.identity,status.identity)
28
+ &&receipt.packageDigest===status.packageDigest&&receiptDigest===digest(body);
29
+ const historicalCompleted=['fixture_completed','run_done'].includes(status?.state);
30
+ const blocked=blockedCodes.has(status?.code)||status?.state==='blocked';
31
+ const review=matched?{status:receipt.result?.verdict==='approved'?'passed':receipt.result?.verdict==='changes_requested'?'failed':'blocked',
32
+ evidence:[`receipt:${receiptDigest}`]}:unknown('registered_review_receipt_unavailable');
33
+ return {status:blocked?'blocked':status?.state==='unknown'?'unknown':historicalCompleted&&review.status==='passed'?'completed':historicalCompleted?'unknown':'pending',
34
+ historicalCompleted,review,reason:blocked?status.code:historicalCompleted&&review.status!=='passed'?'registered_review_receipt_unavailable':null,
35
+ evidence:matched?[`receipt:${receiptDigest}`,`package:${status.packageDigest}`]:[]};
36
+ }
37
+
38
+ const statKey=file=>{
39
+ try{const s=fs.lstatSync(file,{bigint:true});
40
+ need(!s.isSymbolicLink()&&s.isFile()&&s.nlink===1n,'completion_source_invalid');
41
+ return [s.dev,s.ino,s.mode,s.size,s.mtimeNs,s.ctimeNs].join(':');
42
+ }catch(error){if(error.code==='ENOENT')return null;throw error;}
43
+ };
44
+
45
+ export function completionSummary({specsDir,feature,result,task=result?.completion?.task??taskCompletion(result)}){
46
+ const identity=result?.identity??null,packageDigest=result?.packageDigest??null;
47
+ const binding={feature:feature??null,identity,packageDigest,runnerRevision:null};
48
+ const base={version:1,binding,task,feature:unknown('approved_inventory_unavailable'),
49
+ project:unknown('approved_inventory_unavailable'),run:unknown('run_done_evidence_unavailable'),
50
+ productAcceptance:unknown('external_owner_acceptance_not_recorded'),deployment:unknown('deployment_evidence_not_recorded')};
51
+ try{
52
+ need(typeof specsDir==='string'&&path.isAbsolute(specsDir)&&fs.realpathSync(specsDir)===specsDir,'completion_source_invalid');
53
+ const watched=new Map(),watch=file=>{if(!watched.has(file))watched.set(file,statKey(file));};
54
+ const snapshots=new Map(),histories=new Map();
55
+ const snapshotFor=who=>{
56
+ const key=digest({repositoryId:who.repositoryId,runId:who.runId});
57
+ watch(path.join(specsDir,'.reviews','.execution',who.runId,'state.json'));
58
+ if(!snapshots.has(key))snapshots.set(key,readExecutionSnapshot({specsRoot:specsDir,
59
+ identity:{repositoryId:who.repositoryId,runId:who.runId}}));
60
+ return snapshots.get(key);
61
+ };
62
+ const completedOwner=(who,candidate)=>{
63
+ const snapshot=snapshotFor(who);
64
+ if(!histories.has(snapshot.revision)){
65
+ const init=snapshot.records[0]?.payload;
66
+ histories.set(snapshot.revision,readRunnerHistory(snapshot.records,init.config,init.version));
67
+ }
68
+ const history=histories.get(snapshot.revision),state=history.state;
69
+ need(history.pending===null&&state.state==='fixture_completed'&&state.attempt===who.attempt
70
+ &&state.reviewPackage?.packageDigest===candidate&&sameIdentity(state.receipt?.identity,who),'completion_owner_changed');
71
+ return {snapshot,history};
72
+ };
73
+ const statusFile=path.join(specsDir,'.cm-specs-status');watch(statusFile);
74
+ let acceptanceProtection='unknown',boundSources=null;
75
+ if(identity?.runId){
76
+ watch(path.join(specsDir,'.reviews','.execution',identity.runId,'state.json'));
77
+ try{
78
+ const snapshot=snapshotFor(identity);binding.runnerRevision=snapshot.revision;
79
+ const baseline=snapshot.records[0]?.payload?.baseline;
80
+ if(baseline)acceptanceProtection=baseline.specification?.acceptanceContract?.version===1?'contract_v1':'legacy_unprotected';
81
+ if(baseline?.specification)boundSources=snapshot.records.findLast(item=>item.payload?.type==='specification-rebound')?.payload.record?.sources
82
+ ??baseline.specification.sources;
83
+ }catch{/* Missing legacy evidence stays unknown; no upgrade or journal write. */}
84
+ }
85
+ if(task.status==='completed')try{
86
+ const {history}=completedOwner(identity,packageDigest);
87
+ need(task.review.evidence.includes(`receipt:${history.state.receipt.receiptDigest}`),'completion_owner_changed');
88
+ }catch(error){task={...task,status:'unknown',reason:safeCode(error)};}
89
+ const approvalRecord=readReviewSourceFiles(specsDir,['.cm-specs-status'])[0];
90
+ const approval=JSON.parse(Buffer.from(approvalRecord.contentBase64,'base64').toString('utf8'));
91
+ need(approval.status==='approved'&&Array.isArray(approval.features)&&approval.features.length>0
92
+ &&new Set(approval.features).size===approval.features.length,'completion_inventory_invalid');
93
+ const manifest=verifyApprovedManifest(specsDir,statusFile);
94
+ if(boundSources!==null&&digest(boundSources)!==digest(manifest.filter(item=>item.path.startsWith(feature+'/'))))
95
+ task={...task,status:'blocked',reason:'spec_drift'};
96
+ const names=[...approval.features].sort();
97
+ need(digest(names)===digest([...new Set(manifest.map(row=>row.path.split('/')[0]))].sort()),'completion_inventory_invalid');
98
+ for(const row of manifest)watch(path.join(specsDir,row.path));
99
+ const log=path.join(specsDir,'运行日志.jsonl');watch(log);
100
+ const rows=watched.get(log)===null?[]:readStableLogRows(log,row=>row?.schema_version===1&&row.workflow==='cm-ai','completion_log_invalid',{maxBytes:32*1024*1024});
101
+ const latest=new Map();for(const row of rows)if(row.event==='qa'&&row.node==='N6')latest.set(row.feature,row);
102
+ const qaFor=(name,pending)=>{
103
+ const row=latest.get(name);if(!row)return unknown('qa_missing');
104
+ const qaIdentity={repositoryId:row.repository_id,runId:row.run_id,taskId:row.task,attempt:row.attempt};
105
+ const input={specsDir,feature:name,identity:qaIdentity,packageDigest:row.package_digest};
106
+ const evidence=[`运行日志.jsonl#${row.event_id??row.decision_id}`];
107
+ try{
108
+ if(name===feature&&(!identity||!packageDigest))return {...unknown('current_candidate_unavailable'),evidence,binding:input.identity,packageDigest:input.packageDigest};
109
+ if(name===feature)
110
+ need(sameIdentity(qaIdentity,identity)&&row.package_digest===packageDigest,'qa_candidate_changed');
111
+ watch(path.join(specsDir,'.reviews','.execution',qaIdentity.runId,'state.json'));
112
+ for(const item of rows)if(item.event==='test_run'&&item.run_id===qaIdentity.runId&&typeof item.report==='string')
113
+ watch(path.resolve(specsDir,item.report));
114
+ const decision=findCmAiQaDecision(input);need(decision?.decisionId===row.decision_id,'qa_decision_mismatch');
115
+ if(decision.status==='skipped')return {status:'skipped',reason:pending===0?'terminal_feature_qa_required':decision.reason,
116
+ evidence,binding:input.identity,packageDigest:input.packageDigest};
117
+ if(decision.status==='blocked')return {status:'blocked',reason:decision.reason,evidence,binding:input.identity,packageDigest:input.packageDigest};
118
+ const inspected=latestCmAiQaRun(input);
119
+ if(inspected===null)return {...unknown('qa_not_run'),evidence,binding:input.identity,packageDigest:input.packageDigest};
120
+ if(inspected.status==='passed'){
121
+ // A valid old QA round proves its bound candidate, not a later approved
122
+ // specification. Reuse the owner's original sources / explicit rebind.
123
+ let owner;
124
+ try{owner=completedOwner(qaIdentity,row.package_digest).snapshot;}
125
+ catch{return {...unknown('qa_specification_unavailable'),evidence,binding:input.identity,packageDigest:input.packageDigest};}
126
+ const baseline=owner.records[0]?.payload?.baseline,material=baseline?.specification;
127
+ if(!material)return {...unknown('qa_specification_unavailable'),evidence,binding:input.identity,packageDigest:input.packageDigest};
128
+ need(material.feature===name&&baseline.identity.taskId===qaIdentity.taskId,'qa_specification_mismatch');
129
+ const rebind=owner.records.findLast(item=>item.payload?.type==='specification-rebound')?.payload.record;
130
+ const sources=rebind?.sources??material.sources;
131
+ need(digest(sources)===digest(manifest.filter(item=>item.path.startsWith(name+'/'))),'qa_specification_changed');
132
+ }
133
+ return {status:inspected.status,reason:inspected.status==='passed'?null:`qa_${inspected.status}`,
134
+ evidence:[...evidence,`test_run:${inspected.testRunId}`],binding:input.identity,packageDigest:input.packageDigest};
135
+ }catch(error){const code=safeCode(error);return {status:code==='qa_result_incomplete'?'unknown':'blocked',reason:code,evidence,
136
+ binding:input.identity,packageDigest:input.packageDigest};}
137
+ };
138
+ const features=names.map(name=>{
139
+ const record=readReviewSourceFiles(specsDir,[`${name}/tasks.md`])[0];
140
+ const parsed=parseFeatureTaskText(Buffer.from(record.contentBase64,'base64').toString('utf8'),
141
+ {allowDependencyPunctuation:true,grammar:recordedTaskGrammar(approval.taskGrammar)});
142
+ need(!parsed.error,'completion_tasks_invalid');
143
+ const active=parsed.tasks.filter(item=>!item.dropped),completed=active.filter(item=>item.completed).length;
144
+ const pending=active.length-completed,qa=qaFor(name,pending);
145
+ const tasks={completed,total:active.length,pending,open:active.filter(item=>!item.completed).map(item=>item.id),
146
+ dropped:parsed.tasks.filter(item=>item.dropped).length,evidence:[`${name}/tasks.md#sha256=${record.sha256}`]};
147
+ return {name,status:pending>0?'pending':qa.status==='passed'?'passed':qa.status==='failed'?'failed':qa.status==='unknown'?'unknown':'blocked',tasks,qa};
148
+ });
149
+ const finalRow=rows.filter(row=>row.event==='run_done'&&row.node==='N8'&&row.feature===feature
150
+ &&(row.repository_id===identity?.repositoryId||row.repository_id===undefined)&&row.run_id===identity?.runId&&row.task===identity?.taskId
151
+ &&row.package_digest===packageDigest).at(-1);
152
+ const runEvidence=finalRow?[`运行日志.jsonl#${finalRow.event_id}`,`context:${finalRow.context_digest}`]:[];
153
+ const finalized=Boolean(finalRow&&typeof finalRow.documentation_sync_id==='string'
154
+ &&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(finalRow.documentation_sync_id)&&/^[a-f0-9]{64}$/.test(finalRow.context_digest));
155
+ const legacyBinding=finalized&&finalRow.repository_id===undefined;
156
+ const currentBlocked=task.status==='blocked';
157
+ const currentUnknown=task.status==='unknown'&&task.historicalCompleted;
158
+ const scope=finalRow?.scope_features,scoped=Array.isArray(scope)?features.filter(item=>scope.includes(item.name)):[];
159
+ const scopeCurrent=scoped.length>0&&scoped.length===scope?.length&&scoped.every(item=>item.status==='passed');
160
+ const closeoutBlocked=['documentation_sync_blocked','project_qa_not_passed','qa_resources_open'].includes(result?.code);
161
+ const run={status:currentBlocked||closeoutBlocked?'blocked':currentUnknown||legacyBinding?'unknown':finalized?(scopeCurrent?'finalized':scope?'blocked':'unknown'):
162
+ result?.code==='documentation_synced'?'ready_to_finalize':'pending',
163
+ historicalFinalized:finalized,reason:currentBlocked?task.reason:closeoutBlocked?result.code:legacyBinding?'legacy_closeout_binding_unknown':currentUnknown?task.reason:
164
+ finalized?(scopeCurrent?null:scope?'scoped_acceptance_not_current':'legacy_closeout_scope_unknown'):'run_done_not_recorded',
165
+ scope:finalRow?.scope_features??null,evidence:runEvidence};
166
+ const allPassed=features.every(item=>item.status==='passed');
167
+ const fullCloseout=finalized&&!legacyBinding&&Array.isArray(finalRow.scope_features)&&digest([...finalRow.scope_features].sort())===digest(names);
168
+ const project={status:currentBlocked?'blocked':currentUnknown?'unknown':allPassed&&fullCloseout?'completed':allPassed?'ready_to_finalize':features.some(item=>item.status==='failed')?'failed':
169
+ features.some(item=>item.tasks.pending>0)?'pending':features.some(item=>item.status==='blocked')?'blocked':'unknown',
170
+ scope:names,features,completedFeatures:features.filter(item=>item.status==='passed').length,totalFeatures:features.length,
171
+ pendingTasks:features.reduce((sum,item)=>sum+item.tasks.pending,0),historicalFinalized:fullCloseout,
172
+ reason:currentBlocked||currentUnknown?task.reason:allPassed&&!fullCloseout?'full_project_closeout_not_recorded':null,
173
+ evidence:[`.cm-specs-status#sha256=${approvalRecord.sha256}`,...(fullCloseout?runEvidence:[])]};
174
+ const delivery=deliveryProjection({specsDir,feature,identity,packageDigest,specificationDigest:digest(manifest),
175
+ current:task.status==='completed',maxEvidenceBytes:8*1024*1024});
176
+ // Cross-file snapshot: do not compose earlier tasks with a later QA result.
177
+ verifyApprovedManifest(specsDir,statusFile);
178
+ need([...watched].every(([file,key])=>statKey(file)===key),'completion_snapshot_changed');
179
+ const snapshotDigest=digest({approval:approvalRecord.sha256,files:[...watched].map(([file,key])=>[path.relative(specsDir,file),key]),binding,delivery});
180
+ const selected=features.find(item=>item.name===feature)??unknown('feature_not_approved');
181
+ return freeze({...base,...delivery,task:{...task,acceptanceProtection},snapshotDigest,
182
+ feature:currentBlocked||currentUnknown?{...selected,status:currentBlocked?'blocked':'unknown',reason:task.reason}:selected,project,run});
183
+ }catch(error){const reason=safeCode(error);return freeze({...base,task:{...task,status:'unknown',reason},
184
+ feature:unknown(reason),project:unknown(reason),run:unknown(reason)});}
185
+ }
186
+
187
+ export {completionLines} from './operator-guidance.mjs';