@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,308 @@
1
+ // Standing "run to the end" authorization (scripts/cm-autonomy.mjs). Like
2
+ // --approval-response, the session relays the person's own words; the record
3
+ // changes three things: a driver stop waits waitMinutes instead of paging at once
4
+ // (the session usually carries on), cm-ai admission may approve a change proposal
5
+ // that leaves the requirement contract alone, and the session may reopen a task
6
+ // up to AUTO_REOPEN_LIMIT times. Fatal stops page at once (cm-autonomy.mjs notify).
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {randomUUID,createHash} from 'node:crypto';
11
+ import {taskLines,TASK_GRAMMAR,recordedTaskGrammar,specLines} from './spec-task-line.mjs';
12
+ import {validateTestCases} from '../../scripts/validate-test-cases.mjs';
13
+ import {declaredAcceptanceIds,DEPENDENCY} from './cm-ai/cm-ai-admission.mjs';
14
+
15
+ export const AUTONOMY_FILE='autonomy.json',AUTONOMY_OFF_FILE='autonomy.off.json',REOPEN_DIR='autonomy-reopens',AUTO_REOPEN_LIMIT=2;
16
+ // Same directory as notify.json (notify.mjs notifyHome); kept here so notify.mjs can import this module.
17
+ export const autonomyHome=(env=process.env)=>path.resolve(env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow'));
18
+ const iso=value=>typeof value==='string'&&/^\d{4}-\d\d-\d\dT/.test(value)&&Number.isFinite(Date.parse(value));
19
+ const words=value=>typeof value==='string'&&value.trim()!==''&&Array.from(value).length<=500;
20
+ const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
21
+
22
+ function readJson(file){
23
+ try{if(!fs.lstatSync(file).isFile())return {invalid:true};return {value:JSON.parse(fs.readFileSync(file,'utf8'))};}
24
+ catch(error){return error.code==='ENOENT'?{missing:true}:{invalid:true};}
25
+ }
26
+ function writeJson(home,name,value){
27
+ fs.mkdirSync(home,{recursive:true,mode:0o700});
28
+ const target=path.join(home,name),temporary=path.join(home,`.${name}-${randomUUID()}`);
29
+ try{fs.writeFileSync(temporary,JSON.stringify(value,null,1)+'\n',{mode:0o600,flag:'wx'});fs.renameSync(temporary,target);}
30
+ finally{try{fs.unlinkSync(temporary);}catch(error){if(error.code!=='ENOENT')throw error;}}
31
+ }
32
+
33
+ // {on:true,value} only for a regular file the writer below would produce; anything else is off.
34
+ export function readAutonomy(env=process.env){
35
+ const read=readJson(path.join(autonomyHome(env),AUTONOMY_FILE));
36
+ if(read.missing)return {on:false,reason:'missing'};
37
+ const value=read.value;
38
+ if(read.invalid||!record(value)||Object.keys(value).sort().join()!=='at,mode,response,version'
39
+ ||value.version!==1||value.mode!=='until_fatal'||!words(value.response)||!iso(value.at))return {on:false,reason:'invalid'};
40
+ return {on:true,value:{version:1,mode:'until_fatal',response:value.response,at:value.at}};
41
+ }
42
+
43
+ export function writeAutonomy(response,{env=process.env,now=Date.now()}={}){
44
+ if(!words(response))throw new Error('autonomy_response_invalid');
45
+ const value={version:1,mode:'until_fatal',response,at:new Date(now).toISOString()};
46
+ writeJson(autonomyHome(env),AUTONOMY_FILE,value);
47
+ return value;
48
+ }
49
+
50
+ // Turning it off keeps the record (renamed) so the last grant stays auditable.
51
+ export function clearAutonomy({env=process.env}={}){
52
+ const home=autonomyHome(env);
53
+ try{fs.renameSync(path.join(home,AUTONOMY_FILE),path.join(home,AUTONOMY_OFF_FILE));return true;}
54
+ catch(error){if(error.code==='ENOENT')return false;throw error;}
55
+ }
56
+
57
+ // Automatic reopens per task. Each reopen claims one numbered slot file with an
58
+ // exclusive create, which is atomic: concurrent takers (any project) can never
59
+ // claim the same slot, and there is no lock to reclaim. A slot left half-written
60
+ // by a crash still counts. {count} when a slot was claimed, {refused:true,count}
61
+ // when all AUTO_REOPEN_LIMIT are taken (a fatal stop).
62
+ const reopenKey=(project,task)=>`${path.resolve(project)}|${task}`;
63
+ const slotPrefix=key=>createHash('sha256').update(key).digest('hex').slice(0,32);
64
+ // Counted by slot file name, like takeReopen; a group whose files are all unreadable is still shown.
65
+ export function readReopens(env=process.env){
66
+ const dir=path.join(autonomyHome(env),REOPEN_DIR),groups={};
67
+ let names;try{names=fs.readdirSync(dir);}catch(error){if(error.code==='ENOENT')return {};throw error;}
68
+ for(const name of names){
69
+ const prefix=/^([0-9a-f]{32})-\d+$/.exec(name)?.[1];if(!prefix)continue;
70
+ let key=null;try{key=JSON.parse(fs.readFileSync(path.join(dir,name),'utf8')).key;}catch{}
71
+ const group=groups[prefix]??={key:null,count:0};group.count++;
72
+ if(typeof key==='string'&&slotPrefix(key)===prefix)group.key=key;
73
+ }
74
+ return Object.fromEntries(Object.entries(groups).map(([prefix,{key,count}])=>[key??`未识别|名额 ${prefix}`,count]));
75
+ }
76
+ export function takeReopen(project,task,{env=process.env,now=Date.now()}={}){
77
+ if(typeof task!=='string'||!/^\d+\.[^/\\\s]+\/T-\d+$/.test(task))throw new Error('autonomy_task_invalid');
78
+ const dir=path.join(autonomyHome(env),REOPEN_DIR),key=reopenKey(project,task);
79
+ // A count kept some other way is never taken as "none yet".
80
+ if(fs.existsSync(path.join(autonomyHome(env),'autonomy-reopens.json')))throw new Error('autonomy_reopens_legacy');
81
+ fs.mkdirSync(dir,{recursive:true,mode:0o700});
82
+ for(let slot=1;slot<=AUTO_REOPEN_LIMIT;slot++){
83
+ try{fs.writeFileSync(path.join(dir,`${slotPrefix(key)}-${slot}`),JSON.stringify({key,slot,at:new Date(now).toISOString()})+'\n',{flag:'wx',mode:0o600});}
84
+ catch(error){if(error.code==='EEXIST')continue;throw error;}
85
+ return {count:slot};
86
+ }
87
+ return {refused:true,count:AUTO_REOPEN_LIMIT};
88
+ }
89
+
90
+ const DOCUMENTS=['requirements.md','design.md','tasks.md'],CHANGEABLE=new Set(['design.md','tasks.md','test-cases.json']);
91
+ const userCases=source=>{
92
+ if(source===undefined)return new Map();
93
+ const cases=JSON.parse(source)?.cases;
94
+ if(!Array.isArray(cases))throw new Error('cases');
95
+ return new Map(cases.filter(item=>item?.origin==='user').map(item=>[item.id,JSON.stringify(item)]));
96
+ };
97
+
98
+ const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
99
+ const sortedObject=value=>Array.isArray(value)?value.map(sortedObject):record(value)
100
+ ?Object.fromEntries(Object.keys(value).sort().map(key=>[key,sortedObject(value[key])])):value;
101
+ const equalJson=(a,b)=>same(sortedObject(a),sortedObject(b));
102
+ const includesAll=(after,before)=>before.every(value=>after.includes(value));
103
+
104
+ // Preserve old task clauses exactly. Design-only details may evolve, but
105
+ // explicit acceptance wording and fenced examples are retained as written.
106
+ // Added task sections/metadata cannot silently rewrite an older task's duties.
107
+ const versionHeading=/^(?:任务版本|设计版本|版本历史|版本记录|变更记录|Version history)$/i;
108
+ const versionRow=/^\|[^\r\n]*\bv\d+\b[^\r\n]*\|\s*$/;
109
+ const indent=body=>/^[ \t]*/.exec(body)[0].length;
110
+ const taskNames=body=>body.match(/(?<![A-Za-z0-9])T-[A-Za-z0-9][A-Za-z0-9._-]*/g)??[];
111
+ const acceptanceLanguage=body=>/验收|必验|必跑|必须|要求|真机|物理设备|physical[- ]device|\b(?:must|required|shall|acceptance)\b/i.test(body);
112
+ const weakensLanguage=body=>/取消|无需|不再|改为|可忽略|即可|延期|\b(?:optional|instead|waiv(?:e|ed)|no longer|not required|previous)\b/i.test(body);
113
+
114
+ function protectedRows(source,{grammar=TASK_GRAMMAR,priorIds=null,tasks=false}={}){
115
+ const rows=[],ids=new Set(),declarations=[];let owner=null,ownerIndent=0,historyLevel=null;
116
+ const physical=specLines(source);
117
+ for(const line of tasks?taskLines(source,{grammar}):physical){
118
+ const {body,declaration}=line;
119
+ // Grammar 1 still decides declarations, but blank lines in a fence remain
120
+ // literal bytes in both sides of a grammar-transition comparison.
121
+ const fenced=line.fenced||physical[line.index]?.fenced===true;
122
+ if(!body.trim()&&!fenced)continue;
123
+ const heading=fenced?null:/^\s*(#{1,6})\s+(.+?)\s*$/.exec(body);
124
+ if(heading){
125
+ if(historyLevel!==null&&heading[1].length<=historyLevel)historyLevel=null;
126
+ if(versionHeading.test(heading[2]))historyLevel=heading[1].length;
127
+ }
128
+ if(declaration){
129
+ if(ids.has(declaration.id))throw new Error('duplicate task');ids.add(declaration.id);declarations.push({id:declaration.id,start:line.start});
130
+ owner=declaration.id;ownerIndent=indent(body);
131
+ if(priorIds&&!priorIds.has(owner)&&
132
+ (declaration.completed||!/^\[NEW\](?:\s|$)/.test(declaration.description)))throw new Error('new task');
133
+ }else if(owner!==null&&!(indent(body)>ownerIndent&&!/^\s*#/.test(body)))owner=null;
134
+ if(priorIds&&owner!==null&&!priorIds.has(owner)){
135
+ const affected=taskNames(body).find(id=>priorIds.has(id));
136
+ if(affected&&(acceptanceLanguage(body)||weakensLanguage(body)))throw new Error(`override:${affected}`);
137
+ continue;
138
+ }
139
+ rows.push({text:fenced?body:body.trimEnd(),start:line.start,owner,fenced,heading,history:historyLevel!==null&&!fenced&&versionRow.test(body),
140
+ scope:tasks&&owner!==null&&!fenced&&!declaration?/^(\s*-\s*(?:范围|scope)\s*[::]\s*)(.*)$/i.exec(body):null});
141
+ }
142
+ return {rows,ids,declarations};
143
+ }
144
+ function scopePaths(raw){
145
+ const paths=[...raw.matchAll(/`([^`]+)`/g)].map(match=>match[1]);
146
+ return paths.length&&raw.replace(/`[^`]+`/g,'').replace(/[\s,,、]/g,'')===''&&new Set(paths).size===paths.length?paths:null;
147
+ }
148
+ function documentProblem(before,after,file,grammar){
149
+ if(before===after&&(!file.endsWith('/tasks.md')||grammar===TASK_GRAMMAR))return null;
150
+ try{
151
+ const tasks=file.endsWith('/tasks.md'),old=protectedRows(before,{tasks,grammar});
152
+ const next=protectedRows(after,{tasks,priorIds:tasks?old.ids:null});
153
+ if(!tasks){
154
+ const protectedDesign=old.rows.some(row=>row.fenced||acceptanceLanguage(row.text));
155
+ // No task/AC contract is built from design-only implementation details.
156
+ // Keep explicit legacy acceptance statements and examples protected.
157
+ if(!protectedDesign&&!next.rows.some(row=>acceptanceLanguage(row.text)||weakensLanguage(row.text)))return null;
158
+ }
159
+ let position=0;
160
+ for(const row of next.rows){
161
+ const prior=old.rows[position];
162
+ if(prior?.text===row.text&&prior.owner===row.owner){position++;continue;}
163
+ // A history row is metadata only in an explicitly named history section;
164
+ // a table elsewhere may contain an obligation and is never ignored.
165
+ if(row.history){
166
+ const affected=taskNames(row.text).find(id=>old.ids.has(id));
167
+ if(affected&&(acceptanceLanguage(row.text)||weakensLanguage(row.text)))
168
+ return `${file}(${affected})的版本说明改变了既有验收,需明确确认规格变更`;
169
+ continue;
170
+ }
171
+ if(!tasks&&!row.fenced&&!acceptanceLanguage(row.text)&&!weakensLanguage(row.text))continue;
172
+ if(tasks&&!row.fenced&&row.heading){
173
+ // A new subsection is scaffolding only when it introduces a NEW task,
174
+ // never when it changes the grouping/meaning of an existing task.
175
+ const index=next.rows.indexOf(row),following=next.rows.slice(index+1);
176
+ const level=row.heading[1].length,until=following.findIndex(item=>item.heading&&item.heading[1].length<=level);
177
+ const block=until<0?following:following.slice(0,until);
178
+ const boundary=until<0?after.length:following[until].start;
179
+ const newTasks=next.declarations.filter(item=>item.start>row.start&&item.start<boundary);
180
+ if(newTasks.length&&newTasks.every(item=>!old.ids.has(item.id))
181
+ &&!block.some(item=>item.owner!==null&&old.ids.has(item.owner))
182
+ &&!acceptanceLanguage(row.text)&&!weakensLanguage(row.text))continue;
183
+ }
184
+ if(tasks&&!row.fenced){
185
+ const dependency=DEPENDENCY.exec(row.text);
186
+ if(dependency&&!old.ids.has(dependency[1])&&next.ids.has(dependency[1])
187
+ &&dependency[2].split(/[,,、\s]+/).filter(Boolean).every(id=>next.ids.has(id)))continue;
188
+ }
189
+ if(prior?.owner===row.owner&&prior?.scope&&row.scope){
190
+ const was=scopePaths(prior.scope[2]),now=scopePaths(row.scope[2]);
191
+ if(was&&now&&includesAll(now,was)){position++;continue;}
192
+ }
193
+ return `${file}${prior?.owner?`(${prior.owner})`:''} 的既有条款改变,无法证明验收未减弱,需明确确认规格变更`;
194
+ }
195
+ if(position!==old.rows.length||tasks&&!includesAll([...next.ids],[...old.ids]))
196
+ return `${file} 删除了既有条款或任务,需明确确认规格变更`;
197
+ return null;
198
+ }catch(error){
199
+ const affected=/^override:(T-[A-Za-z0-9._-]+)$/.exec(error.message)?.[1];
200
+ return affected?`${file}(${affected})的新任务条款改变了既有验收,需明确确认规格变更`:
201
+ `${file} 无法可靠比较,需明确确认规格变更`;
202
+ }
203
+ }
204
+
205
+ function caseProtectionProblem(before,after,file,references,acceptanceIds,taskIds){
206
+ let old,next;
207
+ try{
208
+ old=before===undefined?null:JSON.parse(before);next=after===undefined?null:JSON.parse(after);
209
+ if(old&&validateTestCases(old).length||next&&validateTestCases(next).length)throw new Error('cases');
210
+ }catch{return '提案的测试用例无法解析';}
211
+ if(old===null)return null;
212
+ const {cases:was,...beforeContract}=old,{cases:now=[],...afterContract}=next??{};
213
+ if(next!==null&&!equalJson(beforeContract,afterContract))return `${file} 用例合同改变,需明确确认规格变更`;
214
+ // A written reference is retained even when an old case mislabeled itself
215
+ // optional. The boolean alone cannot override an approved task's obligation.
216
+ for(const prior of was.filter(item=>item.blocking||references.has(item.id)
217
+ ||item.acIds.some(id=>acceptanceIds.has(id))&&item.taskIds.some(id=>taskIds.has(id)))){
218
+ const candidate=now.find(item=>item.id===prior.id);
219
+ if(!candidate)return `${file} 删除了必验用例 ${prior.id},需明确确认规格变更`;
220
+ if(prior.blocking&&candidate.blocking!==true)return `${file} 降低了 ${prior.id} 的 blocking,需明确确认规格变更`;
221
+ // QA defers a case until every linked task completes. Adding a task can
222
+ // therefore delay a mandatory check: task bindings must be the same set.
223
+ // AC additions retain the old obligations; JSON key order and provenance
224
+ // do not change the required preconditions/steps/outcome.
225
+ for(const key of Object.keys(prior)){
226
+ if(['id','blocking','origin'].includes(key))continue;
227
+ const preserved=key==='taskIds'?includesAll(candidate[key],prior[key])&&includesAll(prior[key],candidate[key])
228
+ :key==='acIds'?includesAll(candidate[key],prior[key])
229
+ :equalJson(prior[key],candidate[key]);
230
+ if(!preserved)return `${file} 改变了必验用例 ${prior.id} 的 ${key},需明确确认规格变更`;
231
+ }
232
+ if(Object.keys(candidate).some(key=>!Object.hasOwn(prior,key)))return `${file} 改变了必验用例 ${prior.id} 的字段,需明确确认规格变更`;
233
+ }
234
+ return null;
235
+ }
236
+
237
+ // Whether a change proposal may be approved under the standing authorization,
238
+ // judged from the complete before/after contents. A generated/inferred blocking
239
+ // case is an obligation too. Unknown prose edits are not presumed harmless.
240
+ // Returns null when it may, else the reason in plain words.
241
+ export function standingProposalProblem(before,proposal){
242
+ if(!record(before)||!Array.isArray(before.directories)||!before.directories.every(dir=>typeof dir==='string')
243
+ ||!record(before.files)||!Object.values(before.files).every(value=>typeof value==='string')
244
+ ||!record(proposal)||!record(proposal.files)||!Object.keys(proposal.files).length
245
+ ||!Object.values(proposal.files).every(value=>typeof value==='string')
246
+ ||!Array.isArray(proposal.changedUserCases)||!Array.isArray(proposal.removed))return '提案内容不完整,无法判断';
247
+ if(proposal.changedUserCases.length)return '提案删除或减弱了用户用例';
248
+ if(proposal.removed.length)return '提案删除了功能';
249
+ const features=new Set(Object.keys(proposal.files).map(file=>file.split('/')[0]));
250
+ for(const feature of features){
251
+ if(!before.directories.includes(feature))return '提案新增了功能';
252
+ if(DOCUMENTS.some(name=>typeof proposal.files[`${feature}/${name}`]!=='string'))return '提案内容不完整,无法判断';
253
+ }
254
+ for(const [file,content] of Object.entries(proposal.files)){
255
+ const [feature,name,...rest]=file.split('/');
256
+ if(rest.length||!DOCUMENTS.includes(name)&&name!=='test-cases.json')return `提案改了规格以外的文件(${file})`;
257
+ if(content!==before.files[file]&&!CHANGEABLE.has(name))return '提案改了需求';
258
+ }
259
+ let grammar=recordedTaskGrammar(undefined);
260
+ try{if(before.status!==undefined)grammar=recordedTaskGrammar(JSON.parse(before.status)?.taskGrammar);}
261
+ catch{return '原规格语法记录无法解析,需明确确认规格变更';}
262
+ for(const feature of features){
263
+ const file=`${feature}/test-cases.json`;
264
+ let was,now;
265
+ // A test-cases.json the proposal leaves out is deleted on save: its user cases count as removed.
266
+ try{was=userCases(before.files[file]);now=userCases(proposal.files[file]);}
267
+ catch{return '提案的测试用例无法解析';}
268
+ for(const [id,item] of was)if(now.get(id)!==item)return '提案删除或减弱了用户用例';
269
+ const references=new Set(DOCUMENTS.flatMap(name=>before.files[`${feature}/${name}`]?.match(/\bTC-\d{3,}\b/g)??[]));
270
+ const caseProblem=caseProtectionProblem(before.files[file],proposal.files[file],file,references,
271
+ declaredAcceptanceIds(before.files[`${feature}/requirements.md`]??''),
272
+ new Set(taskLines(before.files[`${feature}/tasks.md`]??'',{grammar}).filter(row=>row.declaration).map(row=>row.declaration.id)));
273
+ if(caseProblem)return caseProblem;
274
+ }
275
+ for(const feature of features)for(const name of ['design.md','tasks.md']){
276
+ const file=`${feature}/${name}`;
277
+ if(typeof before.files[file]!=='string')return '提案内容不完整,无法判断';
278
+ const problem=documentProblem(before.files[file],proposal.files[file],file,grammar);
279
+ if(problem)return problem;
280
+ }
281
+ return null;
282
+ }
283
+
284
+ // The saved archive (.reviews/prd-change-<digest>.json) must be this proposal and
285
+ // must be exactly what the specs now hold: features listed, proposal files written,
286
+ // every other feature untouched.
287
+ export function standingArchiveProblem(specsDir,archive,digest){
288
+ if(!record(archive)||archive.proposal?.proposalDigest!==digest)return '找不到这份提案的归档';
289
+ const problem=standingProposalProblem(archive.before,archive.proposal);
290
+ if(problem)return problem;
291
+ const {before,proposal}=archive;
292
+ const listed=fs.readdirSync(specsDir).filter(dir=>/^\d+\./.test(dir)).sort();
293
+ if(listed.join('\n')!==[...before.directories].sort().join('\n'))return '规格目录的功能与提案不一致';
294
+ // What the save leaves (cm-prd change.mjs applyPrdChange): the selected features hold
295
+ // exactly the proposal's files, every other feature its original ones. Compare the
296
+ // complete spec file set, so a file the archive does not list cannot stay on disk.
297
+ const selected=Array.isArray(archive.selected)?archive.selected:[...new Set(Object.keys(proposal.files).map(file=>file.split('/')[0]))];
298
+ const expected={...before.files};
299
+ for(const file of Object.keys(expected))if(selected.includes(file.split('/')[0]))delete expected[file];
300
+ Object.assign(expected,proposal.files);
301
+ const onDisk={};
302
+ for(const dir of listed)for(const name of [...DOCUMENTS,'test-cases.json']){
303
+ const file=`${dir}/${name}`;try{onDisk[file]=fs.readFileSync(path.join(specsDir,file),'utf8');}catch(error){if(error.code!=='ENOENT')return '规格文件与提案不一致';}
304
+ }
305
+ const files=Object.keys(expected).sort();
306
+ if(files.join('\n')!==Object.keys(onDisk).sort().join('\n')||files.some(file=>onDisk[file]!==expected[file]))return '规格文件与提案不一致';
307
+ return null;
308
+ }
@@ -0,0 +1,130 @@
1
+ // Shared command-selection analysis. This proves only that argv selects the
2
+ // frozen test identifiers, never that assertions are sufficient or execution passed.
3
+ import path from 'node:path';
4
+ import {selectedNodeTestFiles} from './node-test-selection.mjs';
5
+
6
+ export const isXcodebuild = tokens => tokens.some(token => path.basename(token) === 'xcodebuild');
7
+ // xcodebuild options that take no value (xcodebuild -help, Xcode 26). A bare word counts as an
8
+ // action only right after xcodebuild, another bare word (an action or an option's value), an
9
+ // -option:value, or one of these. After any other option it may be that option's value
10
+ // (`-resultBundlePath test`), so it is not an action: an unknown flag then makes the coverage
11
+ // check warn instead of passing, never the other way round.
12
+ const XCODE_FLAGS = new Set(['-usage', '-help', '-verbose', '-license', '-checkFirstLaunchStatus', '-runFirstLaunch',
13
+ '-checkForNewerComponents', '-downloadAllPlatforms', '-prepareDeviceSupport', '-alltargets', '-parallelizeTargets', '-quiet',
14
+ '-hideShellScriptEnvironment', '-showsdks', '-showdestinations', '-showTestPlans', '-showBuildSettings', '-showBuildSettingsForIndex',
15
+ '-list', '-version', '-exportArchive', '-exportNotarizedApp', '-skipUnavailableActions', '-exportLocalizations', '-importLocalizations',
16
+ '-retry-tests-on-failure', '-run-tests-until-failure', '-disable-concurrent-destination-testing', '-enumerate-tests',
17
+ '-resolvePackageDependencies', '-disableAutomaticPackageResolution', '-onlyUsePackageVersionsFromResolvedFile', '-skipPackageUpdates',
18
+ '-disablePackageRepositoryCache', '-skipPackagePluginValidation', '-skipMacroValidation', '-skipPackageSignatureValidation', '-json',
19
+ '-allowProvisioningUpdates', '-allowProvisioningDeviceRegistration', '-showBuildTimingSummary']);
20
+ function xcodeActions(tokens) {
21
+ const start = tokens.findIndex(token => path.basename(token) === 'xcodebuild');
22
+ if (start === -1) return [];
23
+ return tokens.slice(start + 1).filter((token, index, rest) => {
24
+ if (token.startsWith('-')) return false;
25
+ const before = index === 0 ? null : rest[index - 1];
26
+ return before === null || !before.startsWith('-') || before.includes(':') || XCODE_FLAGS.has(before);
27
+ });
28
+ }
29
+ // Modes that list, show, export or set up instead of running the scheme action: a `test` beside them
30
+ // selects what to show (xcodebuild -showBuildSettings test) and runs nothing.
31
+ const XCODE_NON_RUNNING = new Set(['-usage', '-help', '-license', '-checkFirstLaunchStatus', '-runFirstLaunch', '-downloadAllPlatforms',
32
+ '-prepareDeviceSupport', '-downloadPlatform', '-importPlatform', '-downloadComponent', '-importComponent', '-deleteComponent',
33
+ '-showComponent', '-showsdks', '-showdestinations', '-showTestPlans', '-showBuildSettings', '-showBuildSettingsForIndex', '-list',
34
+ '-find-executable', '-find-library', '-version', '-exportArchive', '-exportNotarizedApp', '-exportLocalizations', '-importLocalizations',
35
+ '-enumerate-tests', '-resolvePackageDependencies', '-create-xcframework']);
36
+ // Whether a direct xcodebuild actually runs tests; shared by the overlap and the coverage checks.
37
+ export const isTestAction = tokens => !tokens.some(token => XCODE_NON_RUNNING.has(token))
38
+ && xcodeActions(tokens).some(action => action === 'test' || action === 'test-without-building');
39
+
40
+ const ONLY = '-only-testing:', SKIP = '-skip-testing:';
41
+ const within = (id, target) => id === target || id.startsWith(`${target}/`);
42
+ // Whether one check command runs all of test `id`. A direct xcodebuild counts only with a test
43
+ // action and only through its selection: unnarrowed, or an -only-testing naming `id` or an
44
+ // ancestor. Any other command (wrapper script, other runner) counts when an argument contains
45
+ // `id`; the start check cannot see inside it. An -skip-testing on `id`, an ancestor or a part
46
+ // of it (one method of the class) means it does not run all of it.
47
+ export function advisoryRunsTest(tokens, id) {
48
+ if (tokens.some(token => token.startsWith(SKIP)
49
+ && (within(id, token.slice(SKIP.length)) || within(token.slice(SKIP.length), id)))) return false;
50
+ if (isXcodebuild(tokens)) {
51
+ if (!isTestAction(tokens)) return false;
52
+ const only = tokens.filter(token => token.startsWith(ONLY)).map(token => token.slice(ONLY.length));
53
+ return !tokens.some(token => token.startsWith('-only-testing')) || only.some(target => within(id, target));
54
+ }
55
+ return tokens.some(token => !token.startsWith('-skip-testing') && token.includes(id));
56
+ }
57
+
58
+ const directXcode = tokens => tokens[0] === '/usr/bin/xcodebuild'
59
+ || tokens[0] === '/usr/bin/xcrun' && tokens[1] === 'xcodebuild';
60
+ const cleanRelative = value => typeof value === 'string' && value.length > 0
61
+ && !value.startsWith('/') && !/[\\\x00-\x1f]/.test(value)
62
+ && value.replace(/^\.\//, '').split('/').every(part => part && part !== '..' && part !== '.');
63
+ const normalizeFile = value => value.replace(/^\.\//, '');
64
+ const XCODE_SELECTION_VALUES=new Set(['-scheme','-project','-workspace','-destination','-destination-timeout',
65
+ '-configuration','-sdk','-arch','-derivedDataPath','-resultBundlePath','-resultBundleVersion',
66
+ '-enableCodeCoverage','-parallel-testing-enabled','-maximum-concurrent-test-simulator-destinations',
67
+ '-maximum-concurrent-test-device-destinations']);
68
+ function modeledXcodeArguments(tokens){
69
+ for(let index=tokens[0]==='/usr/bin/xcrun'?2:1;index<tokens.length;index++){
70
+ const token=tokens[index];
71
+ if(token.startsWith(ONLY)||token.startsWith(SKIP))continue;
72
+ if(XCODE_SELECTION_VALUES.has(token)){
73
+ if(typeof tokens[index+1]!=='string'||tokens[index+1].startsWith('-'))return false;
74
+ index++;continue;
75
+ }
76
+ if(token.startsWith('-')&&!XCODE_FLAGS.has(token)&&!XCODE_NON_RUNNING.has(token))return false;
77
+ // Unknown build-setting overrides could change which tests are compiled.
78
+ if(!token.startsWith('-')&&token.includes('=')&&token!=='COMPILER_INDEX_STORE_ENABLE=NO')return false;
79
+ }
80
+ return true;
81
+ }
82
+
83
+ // Return true/false only for the command forms whose test selection is modeled.
84
+ // A wrapper mentioning a test is unknown, not proof that it runs that test.
85
+ function mandatorySelection(tokens, id) {
86
+ if (!Array.isArray(tokens) || tokens.length === 0 || !tokens.every(token => typeof token === 'string' && token.length > 0))
87
+ return null;
88
+ if (directXcode(tokens)) {
89
+ // A source-file path is not an XCTest target/class/method identifier.
90
+ // Source-to-test mappings must be explicit in the approved contract.
91
+ if (!/^[A-Za-z_][A-Za-z0-9_-]*(?:\/[A-Za-z_][A-Za-z0-9_]*(?:\(\))?){0,2}$/.test(id)) return null;
92
+ // These option forms do not match Xcode's documented colon selection syntax.
93
+ if (tokens.some(token => /^-(?:only|skip)-testing(?:$|=)/.test(token))) return null;
94
+ if (!modeledXcodeArguments(tokens)) return null;
95
+ // Scheme defaults/test plans can omit targets or skip methods even with an
96
+ // explicit selector. Argv can prove exclusion, never the resolved inventory.
97
+ return advisoryRunsTest(tokens, id) ? null : false;
98
+ }
99
+ // Bare PATH lookups and project binaries named "node" do not establish the
100
+ // actual interpreter. The caller can use its already running Node executable.
101
+ if (tokens[0] !== process.execPath) return null;
102
+ if (!/\.(?:cjs|mjs|js)$/.test(id)) return null;
103
+ const args = tokens.slice(1);
104
+ // An explicit script invocation runs that file; it does not prove that an
105
+ // unrelated test name supplied as an argument is run by that script.
106
+ if (args.length === 1 && !args[0].startsWith('-') && cleanRelative(args[0])) return normalizeFile(args[0]) === normalizeFile(id);
107
+ // Modeled native runner options are shared by planning and collected checks.
108
+ // This does not rewrite argv or execute a different command.
109
+ const files = selectedNodeTestFiles(tokens);
110
+ if(files===null)return null;
111
+ return files.some(file => normalizeFile(file) === normalizeFile(id));
112
+ }
113
+
114
+ // Caller binds requiredTests to the approved specification and commands to the
115
+ // checks actually run. This function is read-only and never treats an empty
116
+ // warning list, a developer claim, or a wrapper argument as execution evidence.
117
+ export function mandatoryCheckCoverage({requiredTests, commands}) {
118
+ if (!Array.isArray(requiredTests) || !requiredTests.every(cleanRelative)
119
+ || new Set(requiredTests).size !== requiredTests.length || !Array.isArray(commands))
120
+ throw Object.assign(new Error('mandatory_check_contract_invalid'), {code: 'mandatory_check_contract_invalid'});
121
+ const missing = [], unverifiable = [];
122
+ for (const id of requiredTests) {
123
+ const selections = commands.map(tokens => mandatorySelection(tokens, id));
124
+ if (selections.includes(true)) continue;
125
+ missing.push(id);
126
+ if (selections.includes(null)) unverifiable.push(id);
127
+ }
128
+ return {satisfied: missing.length === 0, missing, unverifiable};
129
+ }
130
+