@aibyzero/cm-workflow 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +38 -0
  4. package/README.md +15 -1
  5. package/VERSION +1 -1
  6. package/docs/architecture.md +3 -0
  7. package/docs/cm-acceptance-completion.md +185 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +1 -1
  10. package/docs/proposals/spec-amendment-tiers.md +100 -0
  11. package/package.json +1 -1
  12. package/runtime/js/acceptance-language.mjs +32 -0
  13. package/runtime/js/autonomy.mjs +168 -3
  14. package/runtime/js/check-coverage.mjs +130 -0
  15. package/runtime/js/cm-ai/acceptance-contract.mjs +257 -0
  16. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +49 -8
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  21. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  22. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  24. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  25. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  27. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  28. package/runtime/js/cm-ai/drive-core.mjs +15 -4
  29. package/runtime/js/cm-ai/durable-runner-state.mjs +10 -6
  30. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  32. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  33. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  34. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  35. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  36. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  37. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  38. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  39. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  40. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  41. package/runtime/js/cm-ai/review-package.mjs +22 -8
  42. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  43. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  44. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  45. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  46. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  47. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  48. package/runtime/js/cm-ai/task-runner.mjs +64 -22
  49. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  50. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  51. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  52. package/runtime/js/cm-prd/change.mjs +52 -5
  53. package/runtime/js/cm-prd/self-check.mjs +36 -6
  54. package/runtime/js/cm-prd/session.mjs +8 -3
  55. package/runtime/js/cm-prd/summary.mjs +5 -0
  56. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  57. package/runtime/js/node-test-selection.mjs +38 -0
  58. package/runtime/js/run-analysis.mjs +153 -0
  59. package/runtime/js/session-boundary.mjs +17 -5
  60. package/runtime/js/session-handoff.mjs +5 -2
  61. package/runtime/js/task-scope.mjs +4 -1
  62. package/runtime/test-contract.md +1 -0
  63. package/scripts/cm-acceptance-preview.mjs +26 -0
  64. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  65. package/scripts/cm-ai-acceptance-contract.test.mjs +195 -0
  66. package/scripts/cm-ai-admission.mjs +8 -2
  67. package/scripts/cm-ai-admission.test.mjs +20 -4
  68. package/scripts/cm-ai-blockage.test.mjs +120 -0
  69. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  70. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  71. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  72. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  73. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  74. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  75. package/scripts/cm-ai-drive.mjs +18 -11
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  77. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  78. package/scripts/cm-ai-progress.test.mjs +7 -0
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  80. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  81. package/scripts/cm-ai-run.test.mjs +23 -1
  82. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  83. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  84. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  85. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  86. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  87. package/scripts/cm-autonomy-review-r1.test.mjs +142 -0
  88. package/scripts/cm-autonomy.mjs +3 -1
  89. package/scripts/cm-autonomy.test.mjs +10 -9
  90. package/scripts/cm-check-runtime.sh +5 -2
  91. package/scripts/cm-delivery-evidence.mjs +59 -0
  92. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  93. package/scripts/cm-drive-liveness.test.mjs +14 -0
  94. package/scripts/cm-driver-light-import.test.mjs +32 -0
  95. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  96. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  97. package/scripts/cm-journal-limit.test.mjs +69 -0
  98. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  99. package/scripts/cm-node-test-selection.test.mjs +108 -0
  100. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  101. package/scripts/cm-prd-completion.test.mjs +49 -0
  102. package/scripts/cm-prd-drive.mjs +1 -1
  103. package/scripts/cm-prd-host.mjs +3 -1
  104. package/scripts/cm-prd-host.test.mjs +19 -2
  105. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  106. package/scripts/cm-prd-self-check.test.mjs +24 -1
  107. package/scripts/cm-prd-summary.test.mjs +25 -4
  108. package/scripts/cm-review-inventory.test.mjs +25 -6
  109. package/scripts/cm-run-analysis.mjs +21 -0
  110. package/scripts/cm-run-analysis.test.mjs +120 -0
  111. package/scripts/cm-spec-amend.mjs +68 -0
  112. package/scripts/cm-spec-amend.test.mjs +510 -0
  113. package/scripts/cm-specs-status.test.mjs +6 -0
  114. package/scripts/cm-start-check.mjs +140 -53
  115. package/scripts/cm-start-check.test.mjs +139 -1
  116. package/scripts/cm-task-scope.test.mjs +3 -2
  117. package/scripts/cm-usage-report.py +8 -3
  118. package/scripts/cm019-r1-contract.test.mjs +137 -0
  119. package/scripts/cm019-review-gates.test.mjs +97 -0
  120. package/scripts/test-journal-limit-1mib.mjs +4 -0
  121. package/scripts/validate-public-repo.py +4 -0
  122. package/skills/cm-ai/references/N1-init.md +23 -1
  123. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  124. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  125. package/skills/cm-ai/references/js-host.md +7 -2
  126. package/skills/cm-prd/references/js-change-recovery.md +2 -1
  127. package/skills/cm-prd/references/js-host.md +1 -0
@@ -8,6 +8,10 @@ import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
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
+ import {taskNames,acceptanceLanguage,weakensLanguage,versionNote,plainVersionNote,testingLanguage} from './acceptance-language.mjs';
11
15
 
12
16
  export const AUTONOMY_FILE='autonomy.json',AUTONOMY_OFF_FILE='autonomy.off.json',REOPEN_DIR='autonomy-reopens',AUTO_REOPEN_LIMIT=2;
13
17
  // Same directory as notify.json (notify.mjs notifyHome); kept here so notify.mjs can import this module.
@@ -92,10 +96,157 @@ const userCases=source=>{
92
96
  return new Map(cases.filter(item=>item?.origin==='user').map(item=>[item.id,JSON.stringify(item)]));
93
97
  };
94
98
 
99
+ const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
100
+ const sortedObject=value=>Array.isArray(value)?value.map(sortedObject):record(value)
101
+ ?Object.fromEntries(Object.keys(value).sort().map(key=>[key,sortedObject(value[key])])):value;
102
+ const equalJson=(a,b)=>same(sortedObject(a),sortedObject(b));
103
+ const includesAll=(after,before)=>before.every(value=>after.includes(value));
104
+
105
+ // Preserve old task clauses exactly. Design-only details may evolve, but
106
+ // explicit acceptance wording and fenced examples are retained as written.
107
+ // Added task sections/metadata cannot silently rewrite an older task's duties.
108
+ const versionHeading=/^(?:任务版本|设计版本|版本历史|版本记录|变更记录|Version history)$/i;
109
+ const versionRow=/^\|[^\r\n]*\bv\d+\b[^\r\n]*\|\s*$/;
110
+ const indent=body=>/^[ \t]*/.exec(body)[0].length;
111
+
112
+ function protectedRows(source,{grammar=TASK_GRAMMAR,priorIds=null,tasks=false}={}){
113
+ const rows=[],ids=new Set(),declarations=[];let owner=null,ownerIndent=0,historyLevel=null;
114
+ const physical=specLines(source);
115
+ for(const line of tasks?taskLines(source,{grammar}):physical){
116
+ const {body,declaration}=line;
117
+ // Grammar 1 still decides declarations, but blank lines in a fence remain
118
+ // literal bytes in both sides of a grammar-transition comparison.
119
+ const fenced=line.fenced||physical[line.index]?.fenced===true;
120
+ if(!body.trim()&&!fenced)continue;
121
+ const heading=fenced?null:/^\s*(#{1,6})\s+(.+?)\s*$/.exec(body);
122
+ if(heading){
123
+ if(historyLevel!==null&&heading[1].length<=historyLevel)historyLevel=null;
124
+ if(versionHeading.test(heading[2]))historyLevel=heading[1].length;
125
+ }
126
+ if(declaration){
127
+ if(ids.has(declaration.id))throw new Error('duplicate task');ids.add(declaration.id);declarations.push({id:declaration.id,start:line.start});
128
+ owner=declaration.id;ownerIndent=indent(body);
129
+ if(priorIds&&!priorIds.has(owner)&&
130
+ (declaration.completed||!/^\[NEW\](?:\s|$)/.test(declaration.description)))throw new Error('new task');
131
+ }else if(owner!==null&&!(indent(body)>ownerIndent&&!/^\s*#/.test(body)))owner=null;
132
+ if(priorIds&&owner!==null&&!priorIds.has(owner)){
133
+ const affected=taskNames(body).find(id=>priorIds.has(id));
134
+ if(affected&&(acceptanceLanguage(body)||weakensLanguage(body)))throw new Error(`override:${affected}`);
135
+ continue;
136
+ }
137
+ rows.push({text:fenced?body:body.trimEnd(),start:line.start,owner,fenced,heading,history:historyLevel!==null&&!fenced&&versionRow.test(body),
138
+ scope:tasks&&owner!==null&&!fenced&&!declaration?/^(\s*-\s*(?:范围|scope)\s*[::]\s*)(.*)$/i.exec(body):null});
139
+ }
140
+ return {rows,ids,declarations};
141
+ }
142
+ function scopePaths(raw){
143
+ const paths=[...raw.matchAll(/`([^`]+)`/g)].map(match=>match[1]);
144
+ return paths.length&&raw.replace(/`[^`]+`/g,'').replace(/[\s,,、]/g,'')===''&&new Set(paths).size===paths.length?paths:null;
145
+ }
146
+ function documentProblem(before,after,file,grammar){
147
+ if(before===after&&(!file.endsWith('/tasks.md')||grammar===TASK_GRAMMAR))return null;
148
+ try{
149
+ const tasks=file.endsWith('/tasks.md'),old=protectedRows(before,{tasks,grammar});
150
+ const next=protectedRows(after,{tasks,priorIds:tasks?old.ids:null});
151
+ if(!tasks){
152
+ const protectedDesign=old.rows.some(row=>row.fenced||acceptanceLanguage(row.text));
153
+ // No task/AC contract is built from design-only implementation details.
154
+ // Keep explicit legacy acceptance statements and examples protected.
155
+ // A newly added design version note about tests or acceptance still reaches the
156
+ // history check below; notes already in the approved design do not.
157
+ // Matched by count, so a duplicated or copied-over approved note counts as new.
158
+ const approvedNotes=new Map();
159
+ for(const row of old.rows)if(row.history)approvedNotes.set(row.text,(approvedNotes.get(row.text)??0)+1);
160
+ const newNote=row=>{const left=approvedNotes.get(row.text)??0;if(left>0){approvedNotes.set(row.text,left-1);return false;}return true;};
161
+ if(!protectedDesign&&!next.rows.some(row=>acceptanceLanguage(row.text)||weakensLanguage(row.text)
162
+ ||row.history&&newNote(row)&&!plainVersionNote(row.text)&&testingLanguage(row.text)))return null;
163
+ }
164
+ let position=0;
165
+ for(const row of next.rows){
166
+ const prior=old.rows[position];
167
+ if(prior?.text===row.text&&prior.owner===row.owner){position++;continue;}
168
+ // A history row is metadata only in an explicitly named history section;
169
+ // a table elsewhere may contain an obligation and is never ignored.
170
+ if(row.history){
171
+ const note=versionNote(row.text),affected=taskNames(note).find(id=>old.ids.has(id));
172
+ if(affected&&(acceptanceLanguage(note)||weakensLanguage(note)||testingLanguage(note)))
173
+ return `${file}(${affected})的版本说明改变了既有验收,需明确确认规格变更`;
174
+ // Without a named task, a note about tests or acceptance still cannot be shown
175
+ // not to weaken an obligation, unless it only states that nothing changed.
176
+ if(!plainVersionNote(note)&&testingLanguage(note))
177
+ return `${file} 的版本说明涉及测试或验收,无法证明验收未减弱,需明确确认规格变更`;
178
+ continue;
179
+ }
180
+ if(!tasks&&!row.fenced&&!acceptanceLanguage(row.text)&&!weakensLanguage(row.text))continue;
181
+ if(tasks&&!row.fenced&&row.heading){
182
+ // A new subsection is scaffolding only when it introduces a NEW task,
183
+ // never when it changes the grouping/meaning of an existing task.
184
+ const index=next.rows.indexOf(row),following=next.rows.slice(index+1);
185
+ const level=row.heading[1].length,until=following.findIndex(item=>item.heading&&item.heading[1].length<=level);
186
+ const block=until<0?following:following.slice(0,until);
187
+ const boundary=until<0?after.length:following[until].start;
188
+ const newTasks=next.declarations.filter(item=>item.start>row.start&&item.start<boundary);
189
+ if(newTasks.length&&newTasks.every(item=>!old.ids.has(item.id))
190
+ &&!block.some(item=>item.owner!==null&&old.ids.has(item.owner))
191
+ &&!acceptanceLanguage(row.text)&&!weakensLanguage(row.text))continue;
192
+ }
193
+ if(tasks&&!row.fenced){
194
+ const dependency=DEPENDENCY.exec(row.text);
195
+ if(dependency&&!old.ids.has(dependency[1])&&next.ids.has(dependency[1])
196
+ &&dependency[2].split(/[,,、\s]+/).filter(Boolean).every(id=>next.ids.has(id)))continue;
197
+ }
198
+ if(prior?.owner===row.owner&&prior?.scope&&row.scope){
199
+ const was=scopePaths(prior.scope[2]),now=scopePaths(row.scope[2]);
200
+ if(was&&now&&includesAll(now,was)){position++;continue;}
201
+ }
202
+ return `${file}${prior?.owner?`(${prior.owner})`:''} 的既有条款改变,无法证明验收未减弱,需明确确认规格变更`;
203
+ }
204
+ if(position!==old.rows.length||tasks&&!includesAll([...next.ids],[...old.ids]))
205
+ return `${file} 删除了既有条款或任务,需明确确认规格变更`;
206
+ return null;
207
+ }catch(error){
208
+ const affected=/^override:(T-[A-Za-z0-9._-]+)$/.exec(error.message)?.[1];
209
+ return affected?`${file}(${affected})的新任务条款改变了既有验收,需明确确认规格变更`:
210
+ `${file} 无法可靠比较,需明确确认规格变更`;
211
+ }
212
+ }
213
+
214
+ function caseProtectionProblem(before,after,file,references,acceptanceIds,taskIds){
215
+ let old,next;
216
+ try{
217
+ old=before===undefined?null:JSON.parse(before);next=after===undefined?null:JSON.parse(after);
218
+ if(old&&validateTestCases(old).length||next&&validateTestCases(next).length)throw new Error('cases');
219
+ }catch{return '提案的测试用例无法解析';}
220
+ if(old===null)return null;
221
+ const {cases:was,...beforeContract}=old,{cases:now=[],...afterContract}=next??{};
222
+ if(next!==null&&!equalJson(beforeContract,afterContract))return `${file} 用例合同改变,需明确确认规格变更`;
223
+ // A written reference is retained even when an old case mislabeled itself
224
+ // optional. The boolean alone cannot override an approved task's obligation.
225
+ for(const prior of was.filter(item=>item.blocking||references.has(item.id)
226
+ ||item.acIds.some(id=>acceptanceIds.has(id))&&item.taskIds.some(id=>taskIds.has(id)))){
227
+ const candidate=now.find(item=>item.id===prior.id);
228
+ if(!candidate)return `${file} 删除了必验用例 ${prior.id},需明确确认规格变更`;
229
+ if(prior.blocking&&candidate.blocking!==true)return `${file} 降低了 ${prior.id} 的 blocking,需明确确认规格变更`;
230
+ // QA defers a case until every linked task completes. Adding a task can
231
+ // therefore delay a mandatory check: task bindings must be the same set.
232
+ // AC additions retain the old obligations; JSON key order and provenance
233
+ // do not change the required preconditions/steps/outcome.
234
+ for(const key of Object.keys(prior)){
235
+ if(['id','blocking','origin'].includes(key))continue;
236
+ const preserved=key==='taskIds'?includesAll(candidate[key],prior[key])&&includesAll(prior[key],candidate[key])
237
+ :key==='acIds'?includesAll(candidate[key],prior[key])
238
+ :equalJson(prior[key],candidate[key]);
239
+ if(!preserved)return `${file} 改变了必验用例 ${prior.id} 的 ${key},需明确确认规格变更`;
240
+ }
241
+ if(Object.keys(candidate).some(key=>!Object.hasOwn(prior,key)))return `${file} 改变了必验用例 ${prior.id} 的字段,需明确确认规格变更`;
242
+ }
243
+ return null;
244
+ }
245
+
95
246
  // Whether a change proposal may be approved under the standing authorization,
96
- // judged from the complete before/after contents: it may change design, tasks and
97
- // generated cases of existing features, never a requirement, the feature list or a
98
- // user case. Returns null when it may, else the reason in plain words.
247
+ // judged from the complete before/after contents. A generated/inferred blocking
248
+ // case is an obligation too. Unknown prose edits are not presumed harmless.
249
+ // Returns null when it may, else the reason in plain words.
99
250
  export function standingProposalProblem(before,proposal){
100
251
  if(!record(before)||!Array.isArray(before.directories)||!before.directories.every(dir=>typeof dir==='string')
101
252
  ||!record(before.files)||!Object.values(before.files).every(value=>typeof value==='string')
@@ -114,6 +265,9 @@ export function standingProposalProblem(before,proposal){
114
265
  if(rest.length||!DOCUMENTS.includes(name)&&name!=='test-cases.json')return `提案改了规格以外的文件(${file})`;
115
266
  if(content!==before.files[file]&&!CHANGEABLE.has(name))return '提案改了需求';
116
267
  }
268
+ let grammar=recordedTaskGrammar(undefined);
269
+ try{if(before.status!==undefined)grammar=recordedTaskGrammar(JSON.parse(before.status)?.taskGrammar);}
270
+ catch{return '原规格语法记录无法解析,需明确确认规格变更';}
117
271
  for(const feature of features){
118
272
  const file=`${feature}/test-cases.json`;
119
273
  let was,now;
@@ -121,6 +275,17 @@ export function standingProposalProblem(before,proposal){
121
275
  try{was=userCases(before.files[file]);now=userCases(proposal.files[file]);}
122
276
  catch{return '提案的测试用例无法解析';}
123
277
  for(const [id,item] of was)if(now.get(id)!==item)return '提案删除或减弱了用户用例';
278
+ const references=new Set(DOCUMENTS.flatMap(name=>before.files[`${feature}/${name}`]?.match(/\bTC-\d{3,}\b/g)??[]));
279
+ const caseProblem=caseProtectionProblem(before.files[file],proposal.files[file],file,references,
280
+ declaredAcceptanceIds(before.files[`${feature}/requirements.md`]??''),
281
+ new Set(taskLines(before.files[`${feature}/tasks.md`]??'',{grammar}).filter(row=>row.declaration).map(row=>row.declaration.id)));
282
+ if(caseProblem)return caseProblem;
283
+ }
284
+ for(const feature of features)for(const name of ['design.md','tasks.md']){
285
+ const file=`${feature}/${name}`;
286
+ if(typeof before.files[file]!=='string')return '提案内容不完整,无法判断';
287
+ const problem=documentProblem(before.files[file],proposal.files[file],file,grammar);
288
+ if(problem)return problem;
124
289
  }
125
290
  return null;
126
291
  }
@@ -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
+
@@ -0,0 +1,257 @@
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,acceptanceDeclarations} 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,ownerInapplicable=false;
150
+ for(const {body:line,fenced} of taskLines(requirementsText)){
151
+ const match=fenced?[]:[...declaredAcceptanceIds(line)],indent=/^[ \t]*/.exec(line)[0].length;
152
+ // An item marked NOT_APPLICABLE right after its id stays declared (cases may link it) but its
153
+ // block states why it is excluded, not a duty: inferring "真机"/baseline evidence from the
154
+ // reason would turn the exclusion back into an execution obligation.
155
+ if(match.length){owner=match[0];ownerIndent=indent;declared.add(owner);
156
+ ownerInapplicable=acceptanceDeclarations(line).some(item=>item.id===owner&&item.inapplicable);}
157
+ else if(line.trim()&&indent<=ownerIndent)owner=null;
158
+ if(owner!==null&&ownerInapplicable)continue;
159
+ // Only explicitly linked AC blocks and explicit shared directives are duties.
160
+ // An indented heading never cuts off an AC's environment/expected subclauses.
161
+ if(owner!==null&&linked.has(owner)||owner===null&&/^\s*(?:Shared|共用必验)[::]/i.test(line))add(owner??'requirements:shared',line,null,fenced);
162
+ }
163
+ if(declared.size&&!linked.size)unresolved.push('acceptance criteria have no explicit task/case mapping');
164
+ for(const id of linked)if(!declared.has(id))unresolved.push(`${id}: undeclared acceptance criterion`);
165
+ const compiledCases=new Set(),caseMap=new Map(testCases.map(item=>[item.id,item]));
166
+ if(caseMap.size!==testCases.length)unresolved.push('duplicate case IDs cannot establish acceptance mapping');
167
+ const pending=testCases.filter(item=>item.blocking===true||referencedCases.has(item.id));
168
+ for(let index=0;index<pending.length;index++){
169
+ const item=pending[index];if(compiledCases.has(item.id))continue;compiledCases.add(item.id);
170
+ add(item.id,`${item.id}: ${item.title}`,item.kind);
171
+ for(const field of ['preconditions','steps','expected','cleanup'])for(const entry of item[field]??[])
172
+ add(`${item.id}:${field}`,`${field}: ${entry}`,item.kind);
173
+ for(const id of referencedCases)if(!compiledCases.has(id)&&caseMap.has(id)&&!pending.some(item=>item.id===id))pending.push(caseMap.get(id));
174
+ }
175
+ for(const id of referencedCases)if(!testCases.some(item=>item.id===id))unresolved.push(`${id}: missing task-bound case mapping`);
176
+ if(!obligations.length){
177
+ unresolved.push('no bounded acceptance obligation; split the approved source before execution');
178
+ obligations.push({id:`task:${taskId}:unmapped`,requirement:'Approved source requires explicit bounded acceptance mapping',
179
+ evidenceType:'review',environment:'local',run:null,result:null});
180
+ }
181
+ if(Buffer.byteLength(JSON.stringify(obligations))>40*1024)unresolved.push('acceptance set exceeds report budget; split the approved task');
182
+ const tests=[...new Set(requiredTests)].filter(value=>{
183
+ const valid=!value.startsWith('/')&&!/[\\\x00-\x1f]/.test(value)
184
+ &&value.replace(/^\.\//,'').split('/').every(part=>part&&part!=='.'&&part!=='..');
185
+ if(!valid)unresolved.push('mandatory tests require canonical relative identifiers');return valid;
186
+ });
187
+ if(explicitOnly&&!mandatory)return null;
188
+ return readAcceptanceContract({version:1,taskId,obligations,requiredTests:tests,
189
+ requiredCommands:[...new Map(requiredCommands.map(argv=>[JSON.stringify(argv),argv])).values()],unresolved:[...new Set(unresolved)]});
190
+ }
191
+
192
+ // Commands are taken from approved text and compared with checks actually
193
+ // collected, not developer prose. Only the running Node binary normalizes to
194
+ // `node`; an arbitrary project executable with the same basename does not.
195
+ export function acceptanceCoverage(contract,checks){
196
+ const commands=checks.filter(item=>Array.isArray(item.command)).map(item=>item.command);
197
+ const coverage=mandatoryCheckCoverage({requiredTests:contract.requiredTests,commands});
198
+ const engines=new Map([[process.execPath,'node'],['/usr/bin/xcodebuild','xcodebuild'],['/usr/bin/xcrun','xcrun']]);
199
+ const normalize=argv=>argv.map((token,index)=>index===0?(engines.get(token)??token):token);
200
+ const native=new Set(engines.values());
201
+ const missingCommands=contract.requiredCommands.filter(expected=>!checks.some(check=>check.outcome==='passed'
202
+ &&Array.isArray(check.command)&&(!native.has(normalize(expected)[0])||engines.has(check.command[0]))
203
+ &&digest(normalize(check.command))===digest(normalize(expected))));
204
+ return {...coverage,satisfied:coverage.satisfied&&missingCommands.length===0,missingCommands};
205
+ }
206
+
207
+ export function acceptanceProblems(contract,items,facts=null){
208
+ readAcceptanceContract(contract);
209
+ const problems=[...contract.unresolved];
210
+ if(!Array.isArray(items))return [...problems,'mandatory acceptance report missing'];
211
+ const expected=new Map(contract.obligations.map(item=>[item.id,item])),seen=new Set();
212
+ for(const item of items){
213
+ const obligation=expected.get(item.id);
214
+ if(!obligation||seen.has(item.id)){problems.push('unknown or duplicate acceptance ID');continue;}seen.add(item.id);
215
+ if(item.satisfied!==true||!text(item.evidence))problems.push(`${item.id}: unsatisfied`);
216
+ if(['requirement','evidenceType','environment'].some(key=>item[key]!==obligation[key]))problems.push(`${item.id}: acceptance evidence mismatch`);
217
+ if((item.run??null)!==obligation.run)problems.push(`${item.id}: required run tag mismatch`);
218
+ // An asserted baseline outcome is part of the approved contract, not an
219
+ // optional claim the developer may remove to avoid contradiction checks.
220
+ if(obligation.run==='baseline'&&obligation.result!==null&&facts?.baseline?.outcome!==obligation.result)
221
+ problems.push(`${item.id}: required baseline outcome mismatch`);
222
+ if(obligation.run==='red'&&!(facts?.status==='replayed'&&!facts.red?.skipped&&facts.red?.outcome==='failed'))
223
+ problems.push(`${item.id}: host RED evidence missing`);
224
+ if(obligation.run==='baseline'&&!(facts?.status==='replayed'&&['passed','failed'].includes(facts.baseline?.outcome)))
225
+ problems.push(`${item.id}: host baseline evidence missing`);
226
+ if(item.run==='baseline'&&item.result&&item.result!==facts?.baseline?.outcome)problems.push(`${item.id}: baseline result mismatch`);
227
+ }
228
+ for(const id of expected.keys())if(!seen.has(id))problems.push(`${id}: missing acceptance obligation`);
229
+ return problems;
230
+ }
231
+
232
+ // Describe the validator's exact failures; this adds source text for operators,
233
+ // never a second verdict. Hosts bound/sanitize the final diagnostic for storage.
234
+ export function describeAcceptanceProblems(contract,problems){
235
+ return problems.map(problem=>{
236
+ const obligation=contract.obligations.find(item=>problem.startsWith(`${item.id}: `));
237
+ return obligation?`${problem} [${obligation.requirement}]`:problem;
238
+ });
239
+ }
240
+
241
+ export const ACCEPTANCE_EVIDENCE_PREFIX='cm-acceptance-contract-v1: ';
242
+ export function encodeAcceptanceEvidence({contract,identity,items,facts,coverage}){
243
+ need(acceptanceProblems(contract,items,facts).length===0,'verification_precheck_failed');
244
+ need(coverage?.satisfied===true,'verification_precheck_failed');
245
+ return ACCEPTANCE_EVIDENCE_PREFIX+JSON.stringify({version:1,contractDigest:digest(contract),identity,items,facts,coverage});
246
+ }
247
+ export function verifyAcceptanceEvidence({contract,identity,evidence}){
248
+ try{
249
+ const records=evidence.filter(item=>typeof item==='string'&&item.startsWith(ACCEPTANCE_EVIDENCE_PREFIX));
250
+ need(records.length===1,'verification_precheck_failed');
251
+ const value=JSON.parse(records[0].slice(ACCEPTANCE_EVIDENCE_PREFIX.length));
252
+ shape(value,['version','contractDigest','identity','items','facts','coverage']);
253
+ need(value.version===1&&value.contractDigest===digest(contract)&&digest(value.identity)===digest(identity),'verification_precheck_failed');
254
+ need(acceptanceProblems(contract,value.items,value.facts).length===0&&value.coverage?.satisfied===true,'verification_precheck_failed');
255
+ return true;
256
+ }catch{need(false,'verification_precheck_failed');}
257
+ }
@@ -5,6 +5,8 @@ import {digest,json,shape,need,hex,id,validIdentity,freeze,JOURNAL_PAYLOAD_LIMIT
5
5
 
6
6
  const INVALID='checkpoint_package_material_invalid',STATE_LIMIT=16*1024*1024;
7
7
  const MARKER_ALLOWANCE=1024,REFERENCE_ALLOWANCE=512;
8
+ // The record budget before it was raised to 4 MiB; see checkpointPackageBudget.
9
+ export const INLINE_PACKAGE_LIMIT=1024*1024;
8
10
  const must=condition=>need(condition,INVALID);
9
11
  const guarded=run=>{try{return run();}catch(error){if(error?.code===INVALID)throw error;throw Object.assign(new Error(INVALID),{code:INVALID});}};
10
12
  const size=value=>Buffer.byteLength(JSON.stringify(value));
@@ -129,7 +131,14 @@ export function checkpointPackageBudget({inlineBytes,packageBytes,reserve,enable
129
131
  must([inlineBytes,packageBytes,reserve].every(v=>Number.isSafeInteger(v)&&v>=0)
130
132
  &&packageBytes<=inlineBytes&&reserve<JOURNAL_PAYLOAD_LIMIT&&typeof enabled==='boolean'&&typeof referenced==='boolean');
131
133
  const budget=JOURNAL_PAYLOAD_LIMIT-reserve;
132
- if(!enabled||!referenced&&inlineBytes<=budget)return freeze({fits:inlineBytes<=budget,material:false,bytes:inlineBytes,budget});
134
+ // A package repeats in every later checkpoint unless archived once. The whole
135
+ // state stays 16 MiB, so packages above the original 1 MiB record budget go to
136
+ // a material archive however large the record limit is (a 3.6 MB package
137
+ // repeated through two review rounds overflows the state after the task
138
+ // commit). Runs without archives keep that original inline budget and are
139
+ // refused before develop is accepted, as before the record limit was raised.
140
+ const inline=Math.max(0,Math.min(JOURNAL_PAYLOAD_LIMIT,INLINE_PACKAGE_LIMIT)-reserve);
141
+ if(!enabled||!referenced&&inlineBytes<=inline)return freeze({fits:inlineBytes<=inline,material:false,bytes:inlineBytes,budget:inline});
133
142
  const bytes=inlineBytes-packageBytes+REFERENCE_ALLOWANCE,material=!referenced;
134
143
  return freeze({fits:bytes<=budget&&(!material||inlineBytes+MARKER_ALLOWANCE<=JOURNAL_PAYLOAD_LIMIT),material,bytes,budget});
135
144
  });}
@@ -145,8 +154,9 @@ export function checkpointStoragePlan({records:rawRecords,effectId,checkpoint:ra
145
154
  const ref=findReference(records,pkg,identity);
146
155
  // Develop reserved the later checkpoints before accepting its inline package.
147
156
  // Those later records enforce their actual limit, not that future reserve again;
148
- // a review or completion cannot introduce a first material archive.
149
- if(!ref&&type==='effect-checkpoint'&&['review','complete'].includes(effect.kind)){
157
+ // a review or completion (including a reconciled review invocation) cannot
158
+ // introduce a first material archive.
159
+ if(!ref&&['review','complete'].includes(effect.kind)){
150
160
  must(size(payload)<=JOURNAL_PAYLOAD_LIMIT);return freeze({checkpoint,payloadFields:{}});
151
161
  }
152
162
  const budget=checkpointPackageBudget({inlineBytes:size(payload),packageBytes:size(pkg),reserve,enabled,referenced:ref!==null});