@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,7 +8,15 @@ import path from 'node:path';
8
8
  import {pathToFileURL} from 'node:url';
9
9
  import {protectedScopePaths, validateDeveloperScope} from '../runtime/js/cm-ai/developer-adapter.mjs';
10
10
  import {planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
11
+ import {isXcodebuild, isTestAction, advisoryRunsTest as runsTest, mandatoryCheckCoverage} from '../runtime/js/check-coverage.mjs';
11
12
  import {git as safeGit} from '../runtime/js/cm-security/scan.mjs';
13
+ import {captureSpecificationMaterial} from '../runtime/js/cm-ai/specification-material.mjs';
14
+ import {readReviewBaseline,captureReviewBaseline} from '../runtime/js/cm-ai/review-package.mjs';
15
+ import {taskReviewScope} from '../runtime/js/cm-ai/effect-contract.mjs';
16
+ import {codeProjectPaths,resolveCodeProjects} from '../runtime/js/cm-ai/code-projects.mjs';
17
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
18
+ import {acceptanceCoverage} from '../runtime/js/cm-ai/acceptance-contract.mjs';
19
+ import {featureHasBrowserCases,readBrowserCapability} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
12
20
 
13
21
  // The whole check step of a current-session run is one host call with this deadline
14
22
  // (runtime/js/cm-ai/host-conversation-execution.mjs, outerTimeoutMs). The test
@@ -30,6 +38,8 @@ const usage = '用法: cm-start-check.mjs --plan PLAN.json [--json] [--strict]\n
30
38
  + ' scope 改到代码根 TESTING.md「## 牵连测试」表里的路径,却没跑表里对应的旧界面测试——warn;\n'
31
39
  + ' 只跑了部分界面测试(-only-testing)而项目没有这张表——info(没能核对)\n'
32
40
  + ' 3. scope 内文件在代码根是否已有未提交改动——warn(Git 不可用时是 warn,不是 Git 仓库时是 info)\n'
41
+ + ' 4. 按运行时同样的规则采一次审查基线:代码根文件总量超出审查清单上限(如被忽略的大构建目录没被排除)——error\n'
42
+ + ' 5. 启用 QA 且 feature 有交互式用例时缺 --browser-qa 或声明无效;advance 会反问而 answers 目录里缺的答案文件——error\n'
33
43
  + '退出码:0 无 error(warn 只提示);1 有 error,或加 --strict 时有 warn;2 输入读不了或不支持。\n';
34
44
 
35
45
  // Modes this check does not model: another check budget (provider), another scope rule
@@ -82,39 +92,6 @@ function checkProtectedScope(scope) {
82
92
  message: `scope 含受保护路径 ${item}:创建运行会被 protected_scope 拒绝。先走人工通道同步该文件,再把它从 scope 里去掉`}));
83
93
  }
84
94
 
85
- const isXcodebuild = tokens => tokens.some(token => path.basename(token) === 'xcodebuild');
86
- // xcodebuild options that take no value (xcodebuild -help, Xcode 26). A bare word counts as an
87
- // action only right after xcodebuild, another bare word (an action or an option's value), an
88
- // -option:value, or one of these. After any other option it may be that option's value
89
- // (`-resultBundlePath test`), so it is not an action: an unknown flag then makes the coverage
90
- // check warn instead of passing, never the other way round.
91
- const XCODE_FLAGS = new Set(['-usage', '-help', '-verbose', '-license', '-checkFirstLaunchStatus', '-runFirstLaunch',
92
- '-checkForNewerComponents', '-downloadAllPlatforms', '-prepareDeviceSupport', '-alltargets', '-parallelizeTargets', '-quiet',
93
- '-hideShellScriptEnvironment', '-showsdks', '-showdestinations', '-showTestPlans', '-showBuildSettings', '-showBuildSettingsForIndex',
94
- '-list', '-version', '-exportArchive', '-exportNotarizedApp', '-skipUnavailableActions', '-exportLocalizations', '-importLocalizations',
95
- '-retry-tests-on-failure', '-run-tests-until-failure', '-disable-concurrent-destination-testing', '-enumerate-tests',
96
- '-resolvePackageDependencies', '-disableAutomaticPackageResolution', '-onlyUsePackageVersionsFromResolvedFile', '-skipPackageUpdates',
97
- '-disablePackageRepositoryCache', '-skipPackagePluginValidation', '-skipMacroValidation', '-skipPackageSignatureValidation', '-json',
98
- '-allowProvisioningUpdates', '-allowProvisioningDeviceRegistration', '-showBuildTimingSummary']);
99
- function xcodeActions(tokens) {
100
- const start = tokens.findIndex(token => path.basename(token) === 'xcodebuild');
101
- if (start === -1) return [];
102
- return tokens.slice(start + 1).filter((token, index, rest) => {
103
- if (token.startsWith('-')) return false;
104
- const before = index === 0 ? null : rest[index - 1];
105
- return before === null || !before.startsWith('-') || before.includes(':') || XCODE_FLAGS.has(before);
106
- });
107
- }
108
- // Modes that list, show, export or set up instead of running the scheme action: a `test` beside them
109
- // selects what to show (xcodebuild -showBuildSettings test) and runs nothing.
110
- const XCODE_NON_RUNNING = new Set(['-usage', '-help', '-license', '-checkFirstLaunchStatus', '-runFirstLaunch', '-downloadAllPlatforms',
111
- '-prepareDeviceSupport', '-downloadPlatform', '-importPlatform', '-downloadComponent', '-importComponent', '-deleteComponent',
112
- '-showComponent', '-showsdks', '-showdestinations', '-showTestPlans', '-showBuildSettings', '-showBuildSettingsForIndex', '-list',
113
- '-find-executable', '-find-library', '-version', '-exportArchive', '-exportNotarizedApp', '-exportLocalizations', '-importLocalizations',
114
- '-enumerate-tests', '-resolvePackageDependencies', '-create-xcframework']);
115
- // Whether a direct xcodebuild actually runs tests; shared by the overlap and the coverage checks.
116
- const isTestAction = tokens => !tokens.some(token => XCODE_NON_RUNNING.has(token))
117
- && xcodeActions(tokens).some(action => action === 'test' || action === 'test-without-building');
118
95
  const optionValue = (tokens, name) => {
119
96
  const at = tokens.indexOf(name);
120
97
  return at === -1 ? '' : tokens[at + 1] ?? '';
@@ -195,24 +172,6 @@ export function readAffectedMap(root) {
195
172
  return null;
196
173
  }
197
174
 
198
- const ONLY = '-only-testing:', SKIP = '-skip-testing:';
199
- const within = (id, target) => id === target || id.startsWith(`${target}/`);
200
- // Whether one check command runs all of test `id`. A direct xcodebuild counts only with a test
201
- // action and only through its selection: unnarrowed, or an -only-testing naming `id` or an
202
- // ancestor. Any other command (wrapper script, other runner) counts when an argument contains
203
- // `id`; the start check cannot see inside it. An -skip-testing on `id`, an ancestor or a part
204
- // of it (one method of the class) means it does not run all of it.
205
- function runsTest(tokens, id) {
206
- if (tokens.some(token => token.startsWith(SKIP)
207
- && (within(id, token.slice(SKIP.length)) || within(token.slice(SKIP.length), id)))) return false;
208
- if (isXcodebuild(tokens)) {
209
- if (!isTestAction(tokens)) return false;
210
- const only = tokens.filter(token => token.startsWith(ONLY)).map(token => token.slice(ONLY.length));
211
- return !tokens.some(token => token.startsWith('-only-testing')) || only.some(target => within(id, target));
212
- }
213
- return tokens.some(token => !token.startsWith('-skip-testing') && token.includes(id));
214
- }
215
-
216
175
  function checkAffectedTests(plan, definition) {
217
176
  const commands = (Array.isArray(plan.checks) ? plan.checks : [])
218
177
  .map(item => item?.command).filter(tokens => Array.isArray(tokens) && tokens.every(token => typeof token === 'string'));
@@ -289,9 +248,137 @@ function checkDirtyScope(definition) {
289
248
  + '运行基线会把它们当起点,交审包里看不到这部分改动;若是上次的任务代码,先还原,确认是有意保留的再继续'}];
290
249
  }
291
250
 
292
- export function startCheck(planFile) {
251
+ // requiredTests comes from the caller's frozen approved contract, never from the
252
+ // mutable affected-test table or the developer's PLAN. Other warnings stay advisory.
253
+ // The runner captures this baseline when the run is created and again before
254
+ // each review package; a tree it refuses there stops the run after the develop
255
+ // answer was already written. Capture it here the same way, read-only.
256
+ export function checkReviewInventory(definition){
257
+ if(!fs.existsSync(definition.codeProject)||typeof definition.specsDir!=='string'||!definition.identity
258
+ ||!Array.isArray(definition.requirements))return [];
259
+ try{
260
+ const codeProject=definition.codeProject;
261
+ captureReviewBaseline({root:codeProject,specsRoot:definition.specsDir,identity:definition.identity,
262
+ scope:taskReviewScope(definition.scope),requirements:definition.requirements,
263
+ ...(typeof definition.feature==='string'?{specification:{specsRoot:definition.specsDir,feature:definition.feature}}:{}),
264
+ ...(definition.codeProjects?{codeProjectPaths:codeProjectPaths(codeProject,resolveCodeProjects(codeProject,definition.codeProjects))}:{})});
265
+ return [];
266
+ }catch(error){
267
+ if(error.code==='limit_exceeded')return [{level:'error',code:'review_inventory_limit',
268
+ message:`运行时会拒绝这棵代码树:${error.message};把该路径移出代码根,或确认它被 Git 忽略且 git 能在 ${GIT_TIMEOUT_NOTE} 内列完被忽略的文件`}];
269
+ return [{level:'warn',code:'review_inventory_unchecked',message:`没能按运行时规则采集审查基线(${error.code??error.message}),开跑后可能在建运行时被拒`}];
270
+ }
271
+ }
272
+ const GIT_TIMEOUT_NOTE='120 秒';
273
+
274
+ // Both stopped Wue specs8 T-001 one advance at a time after earlier checks
275
+ // passed: the host refuses a launch without the session's interactive QA
276
+ // declaration, and the driver refuses an advance whose asked answers are missing.
277
+ // Same inputs and rules as cm-ai-host.mjs (readBrowserCapability) and
278
+ // cm-ai-drive.mjs (the advance asks for qa_assess, documentation_sync/inspect).
279
+ export function checkLaunchInputs(plan,planFile,definition){
280
+ const findings=[],base=path.dirname(path.resolve(planFile)),permissions=plan.permissions??[];
281
+ const value=flag=>{const at=permissions.indexOf(flag);return at===-1?undefined:permissions[at+1];};
282
+ const read=file=>{try{return JSON.parse(fs.readFileSync(path.resolve(base,file),'utf8'));}catch{return null;}};
283
+ const workflow=value('--workflow-config')===undefined?null:read(value('--workflow-config'));
284
+ const control=typeof plan.controlConfig==='string'?read(plan.controlConfig):null;
285
+ const qaEnabled=!control||control.qa!=='disabled';
286
+ // The host always validates the declaration: without interactive QA there are no
287
+ // carriers, and a stray --browser-qa is refused just the same.
288
+ if(typeof definition.specsDir==='string'&&typeof definition.feature==='string'){
289
+ let carriers=[];
290
+ if(workflow?.qa&&qaEnabled){
291
+ try{carriers=featureHasBrowserCases(definition.specsDir,definition.feature,definition.codeProject)?[workflow.qa.environment?.carrier??'browser']:[];}
292
+ catch{carriers=[];}
293
+ }
294
+ try{readBrowserCapability(value('--browser-qa'),carriers);}
295
+ catch(error){findings.push({level:'error',code:'browser_qa_declaration',
296
+ message:`宿主会拒绝启动(${error.code}):${error.reason??''} 在 PLAN.permissions 里加 --browser-qa available(本会话能跑 ${carriers.join('、')||'交互式'} QA 时)`});}
297
+ }
298
+ // 新版控制策略的重开必须带旧运行 inspect-history 给出的 supersedeTarget 文件(Wue specs8 T-003 重开白跑一轮)
299
+ if(control&&permissions.includes('--supersede-reviewed-evidence')){
300
+ const target=value('--supersede-target');
301
+ if(target===undefined||!fs.existsSync(path.resolve(base,target)))findings.push({level:'error',code:'supersede_target_missing',
302
+ message:'重开(--supersede-reviewed-evidence)需要 --supersede-target 文件:先对旧运行执行 cm-ai-run.mjs inspect-history --config 旧RUN.json,保存其中的 supersedeTarget'});
303
+ }
304
+ if(typeof plan.answers==='string'){
305
+ const root=path.resolve(base,plan.answers),need=[];
306
+ if(control&&control.qa!=='disabled'||!control&&workflow?.qa)need.push('qa-assess.json');
307
+ if(workflow?.documentationPaths?.length)need.push('documentation-sync.json');
308
+ if(workflow)need.push('documentation-inspect.json');
309
+ const has=name=>fs.existsSync(path.join(root,name));
310
+ // 首轮开发答案与驾驶员同一命名规则(drive-bootstrap.mjs attemptAnswerName):develop.json 或 develop-a1.json,二者不能并存
311
+ if(plan.mode==='create'){
312
+ if(has('develop.json')&&has('develop-a1.json'))findings.push({level:'error',code:'answers_conflict',
313
+ message:`develop.json 与 develop-a1.json 不能同时存在(${root})`});
314
+ else if(!has('develop.json')&&!has('develop-a1.json'))need.push('develop.json(或 develop-a1.json)');
315
+ }else if(has('develop.json')&&has('develop-a1.json')){
316
+ // A resume reads them only while the run is still on attempt 1; the check cannot
317
+ // know the attempt, so it warns instead of refusing a later-attempt resume.
318
+ findings.push({level:'warn',code:'answers_conflict',
319
+ message:`develop.json 与 develop-a1.json 同时存在(${root}):原运行仍在第 1 轮时驾驶员会拒绝,删掉其中一份`});
320
+ }
321
+ const missing=need.filter(name=>name.includes('(')||!has(name));
322
+ if(missing.length)findings.push({level:'error',code:'answers_missing',files:missing,
323
+ message:`advance 会反问而答案目录里没有:${missing.join('、')}(${root})`});
324
+ }
325
+ return findings;
326
+ }
327
+
328
+ export function checkMandatoryTests(plan, requiredTests) {
329
+ const coverage = mandatoryCheckCoverage({requiredTests,
330
+ commands: (Array.isArray(plan.checks) ? plan.checks : []).map(item => item?.command)});
331
+ if (coverage.satisfied) return [];
332
+ return [{level: 'error', code: 'mandatory_tests_not_covered',
333
+ tests: coverage.missing, unverifiable: coverage.unverifiable,
334
+ message: `已批准必验合同要求 ${coverage.missing.join('、')},当前检查命令未能证明完整选择;`
335
+ + '补充明确执行这些测试的命令。包装脚本须先经原规格流程确认可机械核对的测试映射,不能仅在参数中出现测试名就认定覆盖'}];
336
+ }
337
+
338
+ function approvedStartContract(plan,definition){
339
+ // Old scope-only advisory inputs have no task identity and make no claim
340
+ // about a runnable CM specification. Real run definitions are checked below.
341
+ if(definition.specsDir===undefined&&definition.specification===undefined)return null;
342
+ try{
343
+ if(plan.mode==='resume'){
344
+ const snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,
345
+ identity:{repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});
346
+ const baseline=readReviewBaseline(snapshot.records[0]?.payload?.baseline);
347
+ if(baseline.specificationRoot!==definition.specsDir||baseline.identity.taskId!==definition.identity.taskId)
348
+ throw new Error('owner mismatch');
349
+ return baseline.specification?.acceptanceContract??null;
350
+ }
351
+ // A create-plan may be inspected before any specification has been written.
352
+ // Preserve its old scope/budget diagnostics; this read-only check grants no
353
+ // execution admission. Any existing feature/approval (including symlinks),
354
+ // resume owner or read failure still takes the strict evidence path below.
355
+ if(plan.mode===undefined||plan.mode==='create'){
356
+ const root=definition.specsDir;
357
+ if(typeof root!=='string'||!path.isAbsolute(root)||fs.realpathSync(root)!==root
358
+ ||!fs.lstatSync(root).isDirectory()||typeof definition.feature!=='string'
359
+ ||!/^\d+\.[^/\\\x00-\x1f]+$/.test(definition.feature))throw new Error('invalid specification root');
360
+ const absent=file=>{try{fs.lstatSync(file);return false;}catch(error){if(error.code==='ENOENT')return true;throw error;}};
361
+ if(absent(path.join(root,'.cm-specs-status'))&&absent(path.join(root,definition.feature)))return null;
362
+ }
363
+ return captureSpecificationMaterial({specsRoot:definition.specsDir,feature:definition.feature,
364
+ taskId:definition.identity.taskId}).acceptanceContract;
365
+ }catch{throw new InputError('必验合同无法从已批准规格或原运行读取;先核对规格批准与原运行身份,不能由 PLAN 自报或省略必验范围');}
366
+ }
367
+
368
+ export function startCheck(planFile, {requiredTests = []} = {}) {
293
369
  const {plan, definition} = loadStartInputs(planFile);
294
- return [...checkProtectedScope(definition.scope), ...checkChecks(plan), ...checkAffectedTests(plan, definition), ...checkDirtyScope(definition)];
370
+ const contract=approvedStartContract(plan,definition),mandatory=[];
371
+ if(contract){
372
+ if(contract.unresolved.length)mandatory.push({level:'error',code:'acceptance_mapping_required',
373
+ message:`已批准材料的必验映射尚不明确:${contract.unresolved.join(';')}`});
374
+ // Planned argv is checked before execution; no success evidence is emitted.
375
+ const coverage=acceptanceCoverage(contract,(Array.isArray(plan.checks)?plan.checks:[]).map(item=>({...item,outcome:'passed'})));
376
+ if(!coverage.satisfied)mandatory.push({level:'error',code:'mandatory_checks_not_covered',
377
+ tests:coverage.missing,unverifiable:coverage.unverifiable,commands:coverage.missingCommands,
378
+ message:'当前计划未完整包含冻结的必验检查;补齐检查,不能缩减批准的验收范围'});
379
+ }
380
+ return [...checkProtectedScope(definition.scope), ...checkChecks(plan), ...checkAffectedTests(plan, definition),
381
+ ...checkMandatoryTests(plan, requiredTests), ...mandatory, ...checkDirtyScope(definition), ...checkReviewInventory(definition), ...checkLaunchInputs(plan, planFile, definition)];
295
382
  }
296
383
 
297
384
  export function main(argv = process.argv.slice(2), out = process.stdout, err = process.stderr) {
@@ -6,7 +6,8 @@ import path from 'node:path';
6
6
  import test from 'node:test';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {spawnSync} from 'node:child_process';
9
- import {CHECK_CALL_LIMIT_MS, MAX_SCOPE_PATHS} from './cm-start-check.mjs';
9
+ import {CHECK_CALL_LIMIT_MS, MAX_SCOPE_PATHS, startCheck, checkMandatoryTests, checkReviewInventory, checkLaunchInputs} from './cm-start-check.mjs';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
10
11
 
11
12
  const here = path.dirname(fileURLToPath(import.meta.url));
12
13
  const script = path.join(here, 'cm-start-check.mjs');
@@ -52,6 +53,49 @@ const codes = report => report.findings.map(item => item.code);
52
53
  const cmd = (id, command, timeoutMs) => ({id, command, ...(timeoutMs === undefined ? {} : {timeoutMs})});
53
54
  const xcode = (id, ...extra) => cmd(id, ['xcodebuild', 'test', '-scheme', 'App', '-destination', 'id=U1', ...extra]);
54
55
 
56
+ test('frozen required tests produce an error without upgrading unrelated affected-map warnings', t => {
57
+ const p = project(t, {scope: ['src/a.js'], files: {'src/a.js': 'a\n', 'TESTING.md':
58
+ '## 牵连测试\n\n| 路径 | 测试 |\n| --- | --- |\n| src/a.js | AppUITests/OldTests AppUITests/NewTests |\n'},
59
+ checks: [cmd('ui', ['/usr/bin/xcodebuild','test','-scheme','App','-only-testing:AppUITests/NewTests'])]});
60
+ assert.equal(check(p).status, 0, 'without a frozen contract the existing diagnostic remains advisory');
61
+ const findings = startCheck(p.planFile, {requiredTests: ['AppUITests/OldTests']});
62
+ assert.equal(findings.find(item => item.code === 'affected_tests_not_run').level, 'warn');
63
+ assert.equal(findings.find(item => item.code === 'mandatory_tests_not_covered').level, 'error');
64
+ assert.deepEqual(findings.find(item => item.code === 'mandatory_tests_not_covered').tests, ['AppUITests/OldTests']);
65
+ const approvedSubset = startCheck(p.planFile, {requiredTests: ['AppUITests/NewTests']});
66
+ assert.equal(approvedSubset.some(item => item.level === 'error'), true);
67
+ assert.deepEqual(approvedSubset.find(item=>item.code==='mandatory_tests_not_covered').unverifiable,['AppUITests/NewTests']);
68
+ assert.equal(approvedSubset.find(item => item.code === 'affected_tests_not_run').level, 'warn');
69
+ });
70
+
71
+ test('mandatory selection never accepts a wrapper solely because its arguments contain a test name', () => {
72
+ const findings = checkMandatoryTests({checks: [cmd('wrapper', ['bash', 'tests.sh', 'AppUITests/OldTests'])]}, ['AppUITests/OldTests']);
73
+ assert.equal(findings[0].level, 'error');
74
+ assert.deepEqual(findings[0].unverifiable, ['AppUITests/OldTests']);
75
+ assert.deepEqual(checkMandatoryTests({checks: {}}, []), [], 'an absent contract does not change legacy input handling');
76
+ assert.equal(checkMandatoryTests({checks: {}}, ['AppUITests/OldTests'])[0].level, 'error');
77
+ });
78
+
79
+ test('the real CLI reads mandatory checks from approved specs, never the editable PLAN',t=>{
80
+ const p=project(t,{checks:[cmd('tests',[process.execPath,'--test','a.test.js'])]});
81
+ const directory=path.join(path.dirname(p.planFile),'specs');fs.mkdirSync(path.join(directory,'1.demo'),{recursive:true});
82
+ const specsDir=fs.realpathSync(directory),feature='1.demo';
83
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement AC-001\n - 必跑测试: `a.test.js`, `b.test.js`\n');
84
+ fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'- [ ] [AC-001] preserve both tests\n');
85
+ fs.writeFileSync(path.join(specsDir,feature,'design.md'),'simple\n');
86
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
87
+ const config=path.join(path.dirname(p.planFile),'run.json'),definition=JSON.parse(fs.readFileSync(config,'utf8'));
88
+ fs.writeFileSync(config,JSON.stringify({...definition,specsDir,feature,identity:{repositoryId:'fixture',runId:'start-check',taskId:'T-001',attempt:1}}));
89
+ const before=snapshot(specsDir),missing=check(p);
90
+ assert.equal(missing.status,1);assert.ok(codes(missing.report).includes('mandatory_checks_not_covered'));
91
+ const plan=JSON.parse(fs.readFileSync(p.planFile,'utf8'));plan.requiredTests=[];
92
+ fs.writeFileSync(p.planFile,JSON.stringify(plan));assert.equal(check(p).status,1,'PLAN cannot waive approved obligations');
93
+ plan.checks[0].command.push('b.test.js');fs.writeFileSync(p.planFile,JSON.stringify(plan));
94
+ assert.equal(check(p).status,0);assert.deepEqual(snapshot(specsDir),before,'preflight never writes specs');
95
+ fs.appendFileSync(path.join(specsDir,feature,'tasks.md'),' - extra unapproved requirement\n');
96
+ assert.equal(check(p).status,2,'unapproved drift is not treated as no contract');
97
+ });
98
+
55
99
  function snapshot(dir) {
56
100
  const rows = [];
57
101
  const walk = current => {
@@ -404,3 +448,97 @@ test('repository config cannot run programs: fsmonitor, clean, process and requi
404
448
  assert.equal(fs.existsSync(mark), false);
405
449
  assert.equal(r.status, 0);
406
450
  });
451
+
452
+ test('B1 legacy empty-spec preflight keeps scope diagnostics without permitting incomplete mandatory specifications',t=>{
453
+ const p=project(t,{scope:['AGENTS.md','src/a.js'],repo:false,checks:[cmd('syntax',[process.execPath,'--check','src/a.js'])]});
454
+ const specsDir=path.join(fs.realpathSync(p.dir),'specs');fs.mkdirSync(specsDir);
455
+ const config=path.join(p.planDir,'run.json'),definition=JSON.parse(fs.readFileSync(config,'utf8'));
456
+ fs.writeFileSync(config,JSON.stringify({...definition,specsDir,feature:'1.demo',identity:{repositoryId:'fixture',runId:'preflight',taskId:'T-001',attempt:1}}));
457
+ const before=snapshot(specsDir),legacy=check(p);
458
+ assert.equal(legacy.status,1,legacy.err);assert(codes(legacy.report).includes('protected_scope'));
459
+ assert.equal(snapshot(specsDir),before,'scope diagnostics do not create approval or execution evidence');
460
+ const alias=path.join(p.dir,'specs-alias');fs.symlinkSync(specsDir,alias);
461
+ const selected=JSON.parse(fs.readFileSync(config,'utf8'));fs.writeFileSync(config,JSON.stringify({...selected,specsDir:alias}));
462
+ assert.equal(check(p).status,2,'a linked specs root cannot acquire the empty-spec compatibility exception');
463
+ fs.writeFileSync(config,JSON.stringify({...selected,feature:'../escape'}));assert.equal(check(p).status,2,'feature containment is not bypassed');
464
+ fs.writeFileSync(config,JSON.stringify(selected));
465
+ const originalPlan=fs.readFileSync(p.planFile);fs.writeFileSync(p.planFile,JSON.stringify({...JSON.parse(originalPlan),mode:'resume'}));
466
+ assert.equal(check(p).status,2,'resume always requires its original owner');fs.writeFileSync(p.planFile,originalPlan);
467
+ const statusPath=path.join(specsDir,'.cm-specs-status');fs.symlinkSync(path.join(p.dir,'absent-status'),statusPath);
468
+ assert.equal(check(p).status,2,'dangling status link is present, not a legacy absence');fs.unlinkSync(statusPath);
469
+ const originalStat=fs.lstatSync;
470
+ fs.lstatSync=function(file,...args){if(file===statusPath)throw Object.assign(new Error('fixture denied'),{code:'EACCES'});return originalStat.call(this,file,...args);};
471
+ try{assert.throws(()=>startCheck(p.planFile),/必验合同无法/,'read failures are not absence');}finally{fs.lstatSync=originalStat;}
472
+ const external=path.join(p.dir,'external-feature');fs.mkdirSync(external);fs.symlinkSync(external,path.join(specsDir,'1.demo'));
473
+ assert.equal(check(p).status,2,'a linked feature is present evidence, never absence');fs.unlinkSync(path.join(specsDir,'1.demo'));
474
+ fs.symlinkSync(path.join(p.dir,'absent-feature'),path.join(specsDir,'1.demo'));
475
+ assert.equal(check(p).status,2,'dangling feature links also remain strict');fs.unlinkSync(path.join(specsDir,'1.demo'));
476
+ fs.mkdirSync(path.join(specsDir,'1.demo'));fs.writeFileSync(path.join(specsDir,'1.demo','tasks.md'),'- [ ] T-001: 必验: verify all files\n');
477
+ assert.equal(check(p).status,2,'a present mandatory specification without approval cannot be downgraded to legacy');
478
+ fs.rmSync(path.join(specsDir,'1.demo'),{recursive:true});
479
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.demo']}));
480
+ assert.equal(check(p).status,2,'an existing approval with missing source remains a hard input error');
481
+ });
482
+
483
+ // Wue specs8: a git query timed out on a 67 GB ignored build tree, the whole tree
484
+ // entered the review inventory and the run was refused only after the develop
485
+ // answer. The start check captures the same baseline first and reports it.
486
+ test('a code tree over the review inventory limit is an error before the run starts; a normal tree adds nothing', t => {
487
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cm-start-inventory-'));
488
+ t.after(() => fs.rmSync(dir, {recursive: true, force: true}));
489
+ const root = path.join(dir, 'code'), specs = path.join(dir, 'specs');
490
+ fs.mkdirSync(path.join(root, 'src'), {recursive: true});
491
+ fs.mkdirSync(specs);
492
+ fs.writeFileSync(path.join(root, 'src/a.js'), 'a\n');
493
+ const definition = {codeProject: root, specsDir: specs, scope: ['src/a.js'], requirements: ['src/a.js'],
494
+ identity: {repositoryId: 'r', runId: 'run-1', taskId: 'T-001', attempt: 1}};
495
+ assert.deepEqual(checkReviewInventory(definition), []);
496
+ // Sparse: the size check refuses it before any byte is read.
497
+ const big = path.join(root, 'build.bin');
498
+ fs.closeSync(fs.openSync(big, 'w'));
499
+ fs.truncateSync(big, 1024 * 1024 * 1024 + 1);
500
+ const findings = checkReviewInventory(definition);
501
+ assert.deepEqual(findings.map(item => [item.level, item.code]), [['error', 'review_inventory_limit']]);
502
+ assert.match(findings[0].message, /build\.bin/);
503
+ });
504
+
505
+ // Wue specs8 T-001: each of these stopped one advance after the start check had passed.
506
+ test('answers the advance will ask and an invalid interactive QA declaration are errors before launch', t => {
507
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cm-start-launch-'));
508
+ t.after(() => fs.rmSync(dir, {recursive: true, force: true}));
509
+ const planFile = path.join(dir, 'PLAN.json'), answers = path.join(dir, 'answers');
510
+ fs.mkdirSync(answers);
511
+ fs.writeFileSync(path.join(dir, 'workflow.json'), JSON.stringify({qa: {commands: [], environment: {kind: 'web', carrier: 'browser'}},
512
+ documentationPaths: [], applicableAgentFiles: []}));
513
+ fs.writeFileSync(path.join(dir, 'POLICY.json'), JSON.stringify({version: 2, qa: 'run'}));
514
+ const definition = {codeProject: dir, specsDir: path.join(dir, 'specs'), feature: '1.f', scope: ['a.js']};
515
+ const plan = extra => ({config: 'RUN.json', mode: 'create', answers: 'answers', controlConfig: 'POLICY.json',
516
+ permissions: ['--workflow-config', 'workflow.json', ...extra]});
517
+ const missing = checkLaunchInputs(plan([]), planFile, definition);
518
+ assert.deepEqual(missing.map(item => item.code), ['answers_missing']);
519
+ assert.deepEqual(missing[0].files, ['qa-assess.json', 'documentation-inspect.json', 'develop.json(或 develop-a1.json)']);
520
+ for (const name of ['qa-assess.json', 'documentation-inspect.json', 'develop-a1.json']) fs.writeFileSync(path.join(answers, name), '{}');
521
+ assert.deepEqual(checkLaunchInputs(plan([]), planFile, definition), [], 'develop-a1.json is a valid first-round answer');
522
+ fs.writeFileSync(path.join(answers, 'develop.json'), '{}');
523
+ assert.deepEqual(checkLaunchInputs(plan([]), planFile, definition).map(item => item.code), ['answers_conflict']);
524
+ fs.rmSync(path.join(answers, 'develop-a1.json'));
525
+ assert.deepEqual(checkLaunchInputs(plan([]), planFile, definition), []);
526
+ // A v2 reopen without the old run's supersedeTarget file is refused by the driver: report it first.
527
+ assert.deepEqual(checkLaunchInputs(plan(['--supersede-reviewed-evidence', '--supersede-reason', 'r']), planFile, definition).map(item => item.code), ['supersede_target_missing']);
528
+ fs.writeFileSync(path.join(dir, 'target.json'), '{}');
529
+ assert.deepEqual(checkLaunchInputs(plan(['--supersede-reviewed-evidence', '--supersede-reason', 'r', '--supersede-target', 'target.json']), planFile, definition), []);
530
+ // No interactive cases in the feature: the host refuses a declaration it cannot use.
531
+ assert.deepEqual(checkLaunchInputs(plan(['--browser-qa', 'available']), planFile, definition).map(item => item.code),
532
+ ['browser_qa_declaration']);
533
+ // Codex review: QA disabled by the policy, or no workflow at all: the host still refuses a stray declaration.
534
+ fs.writeFileSync(path.join(dir, 'POLICY.json'), JSON.stringify({version: 2, qa: 'disabled'}));
535
+ assert.deepEqual(checkLaunchInputs(plan(['--browser-qa', 'available']), planFile, definition).map(item => item.code),
536
+ ['browser_qa_declaration']);
537
+ assert.deepEqual(checkLaunchInputs({config: 'RUN.json', mode: 'create', permissions: ['--browser-qa', 'available']}, planFile, definition)
538
+ .map(item => item.code), ['browser_qa_declaration']);
539
+ assert.deepEqual(checkLaunchInputs({config: 'RUN.json', mode: 'create', permissions: []}, planFile, definition), []);
540
+ // Codex review: a resume reads the first-round answer only while still on attempt 1, so both files warn.
541
+ fs.writeFileSync(path.join(answers, 'develop-a1.json'), '{}');
542
+ const resumed = checkLaunchInputs({...plan([]), mode: 'resume'}, planFile, definition).filter(item => item.code === 'answers_conflict');
543
+ assert.deepEqual(resumed.map(item => item.level), ['warn']);
544
+ });
@@ -115,7 +115,8 @@ test('rule 4: no task may wait for the session task, directly or through another
115
115
  test('only exact relative file paths in backticks are accepted',()=>{
116
116
  for(const bad of ['src/*.js','src/','/etc/passwd','../x.js','a/./b.js','a\\b.js','AGENTS.md','.git/config','x?.js'])
117
117
  assert.equal(validScopePath(bad),false,bad);
118
- for(const good of ['README.md','src/deep/file.test.mjs','docs/中文.md'])assert.equal(validScopePath(good),true,good);
118
+ // expo-router / Next.js dynamic routes are real files; brackets are literal (git calls use :(literal)).
119
+ for(const good of ['README.md','src/deep/file.test.mjs','docs/中文.md','app/reminder/[id].tsx','app/[...slug]/page.tsx'])assert.equal(validScopePath(good),true,good);
119
120
  const {errors}=parseTaskScopes(tasksText(['- [ ] T-001: a',' - 范围: src/a.js','- [ ] T-002: b',' - 范围: `src/*.js`',
120
121
  '- [ ] T-003: c',' - 范围: `a.js`, `a.js`','- [ ] T-004: d',' - 范围: `a.js`',' - 范围: `b.js`']));
121
122
  assert.deepEqual(errors.map(item=>item.taskId),['T-001','T-002','T-003','T-004']);
@@ -173,7 +174,7 @@ const draft=(tasks)=>({draftDigest:'d',features:[{directory:'1.sample',name:'sam
173
174
  const codes=report=>report.findings.map(item=>item.code);
174
175
 
175
176
  test('rule 3: every task of a new draft must declare its files; earlier rules do not ask',()=>{
176
- assert.equal(PRD_SELF_CHECK_RULES,4,'rule 4 keeps the rule-3 scope check');
177
+ assert.equal(PRD_SELF_CHECK_RULES,5,'rules 4 and 5 keep the rule-3 scope check');
177
178
  const without=draft('- [ ] T-001: a\n- [ ] T-002: b\n - 范围: `b.js`\n');
178
179
  const report=checkPrdDraftMechanics(without,{rules:3});
179
180
  assert.deepEqual(codes(report),['task_scope_missing']);
@@ -220,7 +220,10 @@ def add_observed(counts: Dict[str, int], row: Dict[str, Any]) -> None:
220
220
  counts["duration_observed_calls"] += 1
221
221
 
222
222
 
223
- def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
223
+ def build_report(
224
+ log_home: Path, refs: List[RunRef],
225
+ rows_by_run: Optional[Dict[str, List[Tuple[int, Dict[str, Any]]]]] = None,
226
+ ) -> Dict[str, Any]:
224
227
  summary = {
225
228
  "runs": len(refs),
226
229
  "observed_calls": 0,
@@ -249,10 +252,12 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
249
252
 
250
253
  for ref in refs:
251
254
  log_path = safe_log_path(log_home, ref.log_file)
252
- if log_path is None or not log_path.is_file():
255
+ if rows_by_run is None and (log_path is None or not log_path.is_file()):
253
256
  print(f"warning: missing run log for {ref.run_id}", file=sys.stderr)
254
257
  continue
255
- for line_number, row in read_jsonl(log_path):
258
+ # The specs-local report supplies its already validated immutable snapshot.
259
+ rows = read_jsonl(log_path) if rows_by_run is None else rows_by_run.get(ref.run_id, [])
260
+ for line_number, row in rows:
256
261
  if row.get("run_id") != ref.run_id:
257
262
  continue
258
263
  if row.get("event") == "model_call":
@@ -0,0 +1,137 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {buildAcceptanceContract,acceptanceProblems} from '../runtime/js/cm-ai/acceptance-contract.mjs';
7
+ import {buildTaskAcceptanceContract,captureSpecificationMaterial,verifySpecificationMaterial,inspectSpecificationDrift} from '../runtime/js/cm-ai/specification-material.mjs';
8
+ import {buildManifest} from './cm-spec-manifest.mjs';
9
+ const texts=task=>({'tasks.md':task,'requirements.md':'# Requirements\n- [ ] [AC-001] matching output\n - preserve all bytes\n','design.md':'# Design\n'});
10
+ const compile=line=>buildAcceptanceContract({taskId:'T-001',taskText:line,requirementsText:''});
11
+ const items=c=>c.obligations.map(item=>({...item,satisfied:true,evidence:'synthetic fixture evidence'}));
12
+ const facts=outcome=>({status:'replayed',baseline:{outcome},red:{skipped:true}});
13
+
14
+ test('B1 old task prose without explicit mandatory contract remains legacy even with unmapped ACs',()=>{
15
+ assert.equal(buildTaskAcceptanceContract({texts:texts('- [ ] T-001: implement old feature\n'),taskId:'T-001'}),null);
16
+ assert.equal(buildTaskAcceptanceContract({texts:texts('- [ ] T-001: implement AC-001\n - 测试文件: `tests/a.test.mjs`\n'),taskId:'T-001'}),null);
17
+ const oversized=texts('- [ ] T-001: implement AC-001\n');oversized['requirements.md']='- [ ] [AC-001] 必验: '+ 'x'.repeat(2100);
18
+ const active=buildTaskAcceptanceContract({texts:oversized,taskId:'T-001'});assert.notEqual(active,null);assert(active.unresolved.length>0);
19
+ });
20
+
21
+ test('M1 mandatory task selection excludes shared metadata and other task mentions',()=>{
22
+ const source=texts('# Tasks\n| version | T-001 historical note |\n- [ ] T-001: 必验: implement AC-001\n - own clause\n- [ ] T-002: migration acceptance same as T-001 baseline\n - delete old table\n');
23
+ source['requirements.md']='# Product\n| version | TC-999 background |\n'+Array.from({length:80},(_,i)=>`F-${i}: unrelated background`).join('\n')+'\n- [ ] [AC-001] exact output\n - own AC clause\n- [ ] [AC-002] other AC\n - unrelated AC clause\n';
24
+ const c=buildTaskAcceptanceContract({texts:source,taskId:'T-001'});
25
+ assert.equal(c.unresolved.length,0);assert.equal(c.obligations.length,4);
26
+ assert(c.obligations.some(item=>item.requirement==='- own clause'));
27
+ assert(c.obligations.some(item=>item.requirement==='- own AC clause'));
28
+ assert(c.obligations.every(item=>!/(migration|historical|background|delete|other AC)/.test(item.requirement)));
29
+ });
30
+
31
+ test('M2 negated baseline and RED clauses never reverse the required observed result',()=>{
32
+ for(const line of ['- 基线不通过(旧代码下检查应当不通过)','- baseline must not pass']){
33
+ const c=compile(line);assert.equal(c.obligations[0].result,'failed');
34
+ assert.equal(acceptanceProblems(c,items(c),facts('failed')).length,0);
35
+ assert(acceptanceProblems(c,items(c),facts('passed')).some(message=>message.includes('outcome mismatch')));
36
+ }
37
+ const baseline=compile('- 开发前基线不要求通过');assert.notEqual(baseline.obligations[0].result,'passed');
38
+ const red=compile('- 本任务不要求先失败(纯重构)');assert.equal(red.obligations[0].run,null);
39
+ for(const line of ['- baseline must never pass','- baseline must not have passed','- RED must not be run','- 基线不必通过','- baseline does not have to pass']){
40
+ const unknown=compile(line);assert(unknown.unresolved.length>0,'unmodeled negation must require clarification');
41
+ assert.notEqual(unknown.obligations[0].result,'passed');
42
+ }
43
+ });
44
+
45
+ test('M3 executable-name prose and prohibited bare commands are never frozen executable argv',()=>{
46
+ for(const line of ['- node --test a.test.mjs must not be run on CI','- node --test a.test.mjs cannot be run on CI','- node --test a.test.mjs is prohibited on CI','- go to settings and toggle dark mode','- node and npm must be installed','- sh scripts should be removed']){
47
+ const c=compile(line);assert.deepEqual(c.requiredCommands,[],line);assert.notEqual(c.obligations[0].evidenceType,'host-check',line);
48
+ }
49
+ const prohibited=compile('- node --test a.test.mjs must not be run on CI');assert(prohibited.unresolved.length>0);
50
+ assert.deepEqual(compile('- 运行:node --test a.test.mjs').requiredCommands,[['node','--test','a.test.mjs']]);
51
+ });
52
+
53
+ test('N1 prohibited parent clauses never freeze child commands in Chinese or English',async t=>{
54
+ for(const [language,parent,command,constraint] of [
55
+ ['Chinese','下面命令禁止运行:','npm run deploy','不要更改公共 API'],
56
+ ['English','Do not run the following on CI:','node scripts/wipe.mjs','Do not change public API'],
57
+ ])await t.test(language,()=>{
58
+ const task=`- [ ] T-001: 必验: 发布前检查\n - ${parent}\n - ${command}\n`;
59
+ const c=buildTaskAcceptanceContract({texts:{...texts(task),'requirements.md':''},taskId:'T-001'});
60
+ assert.notEqual(c,null);
61
+ assert.deepEqual(c.requiredCommands,[]);
62
+ assert(c.unresolved.some(message=>message.includes('command context')));
63
+ assert.equal(c.obligations.find(item=>item.requirement===`- ${command}`).evidenceType,'review');
64
+ const sibling=buildTaskAcceptanceContract({texts:{...texts(task+' - 必跑检查:\n - npm run check\n'),
65
+ 'requirements.md':''},taskId:'T-001'});
66
+ assert.deepEqual(sibling.requiredCommands,[['npm','run','check']]);
67
+ const allowed=buildTaskAcceptanceContract({texts:{...texts(
68
+ `- [ ] T-001: 必验: ${constraint}\n - 必跑检查:\n - npm run check\n`),
69
+ 'requirements.md':''},taskId:'T-001'});
70
+ assert.deepEqual(allowed.requiredCommands,[['npm','run','check']]);
71
+ assert.deepEqual(allowed.unresolved,[]);
72
+ });
73
+ });
74
+
75
+ test('N1 R3 all reported non-mandatory parents and headings leave commands unresolved',async t=>{
76
+ const contexts=['下面命令禁止运行:','Do not run the following on CI:','Never run these:',
77
+ '下面的命令不能运行:','严禁执行以下命令:','以下命令不可执行:','以下脚本不许跑:',
78
+ 'The following must not be run:','These must never be executed:','Avoid running:','Forbidden commands:',
79
+ '### 禁止运行的命令','参考示例:','For reference:'];
80
+ for(const context of contexts)await t.test(context,()=>{
81
+ for(const command of ['npm run deploy','node scripts/wipe.mjs'])for(const quoted of [false,true]){
82
+ const value=quoted?'`'+command+'`':command;
83
+ const task=`- [ ] T-001: 必验: 发布前检查\n ${context.startsWith('#')?context:'- '+context}\n${context.startsWith('#')?' ':' '}- ${value}\n`;
84
+ const c=buildTaskAcceptanceContract({texts:{...texts(task),'requirements.md':''},taskId:'T-001'});
85
+ assert.notEqual(c,null);assert.deepEqual(c.requiredCommands,[],task);
86
+ assert(c.unresolved.some(message=>message.includes('command context')),task);
87
+ assert.equal(c.obligations.find(item=>item.requirement===`- ${value}`).evidenceType,'review');
88
+ }
89
+ });
90
+ });
91
+
92
+ test('N1 R3 commands require a positive inline parent or heading declaration',()=>{
93
+ for(const command of ['node --test a.test.mjs','./scripts/test.sh']){
94
+ const bare=compile('- '+command);
95
+ assert.deepEqual(bare.requiredCommands,[]);assert(bare.unresolved.length>0);
96
+ for(const label of ['必跑检查:','运行:','mandatory acceptance:']){
97
+ for(const value of [command,'`'+command+'`'])for(const task of [
98
+ `- ${label} ${value}`,`- ${label}\n - ${value}`,`### ${label}\n- ${value}`,
99
+ ]){
100
+ const c=compile(task);assert.deepEqual(c.requiredCommands,[command.split(' ')],task);assert.deepEqual(c.unresolved,[],task);
101
+ }
102
+ }
103
+ }
104
+ });
105
+
106
+ test('N1 R3 the nearest context shadows distant mandatory declarations and resets at boundaries',()=>{
107
+ for(const task of [
108
+ '- 必跑检查:\n - 参考示例:\n - npm run deploy',
109
+ '### 必跑检查\n#### Forbidden commands\n- npm run deploy',
110
+ '### 必跑检查\n- 参考示例:\n - npm run deploy',
111
+ '### 必跑检查\n### 参考示例\n- npm run deploy',
112
+ ' ### 必跑检查\n- npm run deploy',
113
+ ]){const c=compile(task);assert.deepEqual(c.requiredCommands,[],task);assert(c.unresolved.length>0,task);}
114
+ const sibling=compile('### 参考示例\n- npm run deploy\n### 运行:\n- npm run check');
115
+ assert.deepEqual(sibling.requiredCommands,[['npm','run','check']]);assert(sibling.unresolved.length>0);
116
+ const sourceBoundary=buildAcceptanceContract({taskId:'T-001',taskText:'- 必跑检查:\n - npm run check\n- AC-001',
117
+ requirementsText:'- [ ] [AC-001] reference\n - npm run deploy'});
118
+ assert.deepEqual(sourceBoundary.requiredCommands,[['npm','run','check']]);assert(sourceBoundary.unresolved.length>0);
119
+ });
120
+
121
+ test('G2 a frozen contract is validated against its approved sources rather than recompiled on resume',t=>{
122
+ const specsRoot=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm019-frozen-contract-')));t.after(()=>fs.rmSync(specsRoot,{recursive:true,force:true}));
123
+ const feature='1.demo';fs.mkdirSync(path.join(specsRoot,feature));
124
+ const input=texts('- [ ] T-001: 必验: implement AC-001\n- [ ] T-002: old other task\n');for(const [name,content] of Object.entries(input))fs.writeFileSync(path.join(specsRoot,feature,name),content);
125
+ fs.writeFileSync(path.join(specsRoot,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsRoot)}));
126
+ const material=captureSpecificationMaterial({specsRoot,feature,taskId:'T-001'});
127
+ // Historical v1 parser included shared prose. Its stored, structurally valid
128
+ // projection remains authoritative while the exact approved source stays bound.
129
+ const historical={...material,acceptanceContract:{...material.acceptanceContract,obligations:[...material.acceptanceContract.obligations,
130
+ {id:'requirements:shared:historical:1',requirement:'# historical parser projection',evidenceType:'review',environment:'local',run:null,result:null}]}};
131
+ const baseline={specificationRoot:specsRoot,identity:{repositoryId:'fixture',runId:'old',taskId:'T-001',attempt:1},specification:historical};
132
+ assert.deepEqual(verifySpecificationMaterial(baseline),historical);
133
+ const tasks=path.join(specsRoot,feature,'tasks.md');fs.writeFileSync(tasks,fs.readFileSync(tasks,'utf8').replace('old other task','new other task'));
134
+ fs.writeFileSync(path.join(specsRoot,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsRoot)}));
135
+ const drift=inspectSpecificationDrift(baseline);assert.equal(drift.rebindable,true);assert.deepEqual(drift.fields,[]);
136
+ fs.appendFileSync(path.join(specsRoot,feature,'tasks.md'),'changed');assert.throws(()=>verifySpecificationMaterial(baseline),{code:'spec_drift'});
137
+ });