@aibyzero/cm-workflow 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +26 -0
  4. package/README.md +14 -1
  5. package/VERSION +1 -1
  6. package/docs/architecture.md +3 -0
  7. package/docs/cm-acceptance-completion.md +185 -0
  8. package/docs/installation.md +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/autonomy.mjs +308 -0
  11. package/runtime/js/check-coverage.mjs +130 -0
  12. package/runtime/js/cm-ai/acceptance-contract.mjs +252 -0
  13. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +53 -12
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  16. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  17. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  18. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  19. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  20. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  21. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  22. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  23. package/runtime/js/cm-ai/drive-core.mjs +8 -3
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +2 -2
  25. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  26. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  27. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  28. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  29. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  30. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  31. package/runtime/js/cm-ai/review-package.mjs +2 -2
  32. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  33. package/runtime/js/cm-ai/task-runner.mjs +38 -13
  34. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  35. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  36. package/runtime/js/cm-prd/change.mjs +17 -1
  37. package/runtime/js/cm-prd/summary.mjs +5 -0
  38. package/runtime/js/node-test-selection.mjs +38 -0
  39. package/runtime/js/notify.mjs +17 -8
  40. package/runtime/js/run-analysis.mjs +153 -0
  41. package/runtime/js/session-boundary.mjs +17 -5
  42. package/runtime/js/session-handoff.mjs +5 -2
  43. package/runtime/js/specs-status.mjs +4 -3
  44. package/scripts/cm-acceptance-preview.mjs +26 -0
  45. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  46. package/scripts/cm-ai-acceptance-contract.test.mjs +185 -0
  47. package/scripts/cm-ai-admission.mjs +10 -2
  48. package/scripts/cm-ai-admission.test.mjs +151 -1
  49. package/scripts/cm-ai-blockage.test.mjs +120 -0
  50. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  51. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  52. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  53. package/scripts/cm-ai-progress.test.mjs +7 -0
  54. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  55. package/scripts/cm-ai-run.test.mjs +23 -1
  56. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  57. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  58. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  59. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  60. package/scripts/cm-autonomy-review-r1.test.mjs +93 -0
  61. package/scripts/cm-autonomy.mjs +96 -0
  62. package/scripts/cm-autonomy.test.mjs +163 -0
  63. package/scripts/cm-check-runtime.sh +3 -1
  64. package/scripts/cm-delivery-evidence.mjs +59 -0
  65. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  66. package/scripts/cm-drive-liveness.test.mjs +6 -0
  67. package/scripts/cm-driver-light-import.test.mjs +32 -0
  68. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  69. package/scripts/cm-node-test-selection.test.mjs +108 -0
  70. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  71. package/scripts/cm-notify.test.mjs +6 -0
  72. package/scripts/cm-prd-completion.test.mjs +12 -0
  73. package/scripts/cm-prd-host.mjs +3 -1
  74. package/scripts/cm-prd-host.test.mjs +18 -1
  75. package/scripts/cm-prd-summary.test.mjs +19 -4
  76. package/scripts/cm-review-inventory.test.mjs +21 -6
  77. package/scripts/cm-run-analysis.mjs +21 -0
  78. package/scripts/cm-run-analysis.test.mjs +120 -0
  79. package/scripts/cm-start-check.mjs +128 -6
  80. package/scripts/cm-start-check.test.mjs +163 -3
  81. package/scripts/cm-usage-report.py +8 -3
  82. package/scripts/cm019-r1-contract.test.mjs +137 -0
  83. package/scripts/cm019-review-gates.test.mjs +97 -0
  84. package/scripts/validate-public-repo.py +3 -0
  85. package/skills/cm-ai/references/N3-execute-task.md +1 -1
  86. package/skills/cm-ai/references/js-host.md +31 -1
  87. package/skills/cm-prd/SKILL.md +3 -2
  88. package/skills/cm-prd/references/change-mode.md +3 -2
  89. package/skills/cm-prd/references/js-change-recovery.md +14 -0
  90. package/skills/cm-prd/references/js-host.md +1 -0
@@ -1,13 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  // Read-only start check for a cm-ai single-task drive PLAN. It reports the blocks that
3
- // are already knowable before create: protected scope, check budget, dirty scope files.
3
+ // are already knowable before create: protected scope, check budget, affected old UI tests
4
+ // left out of the checks, dirty scope files.
4
5
  // It never writes a file, never starts a host and never runs a check command.
5
6
  import fs from 'node:fs';
6
7
  import path from 'node:path';
7
8
  import {pathToFileURL} from 'node:url';
8
9
  import {protectedScopePaths, validateDeveloperScope} from '../runtime/js/cm-ai/developer-adapter.mjs';
9
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';
10
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} from '../runtime/js/cm-ai/review-package.mjs';
15
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
16
+ import {acceptanceCoverage} from '../runtime/js/cm-ai/acceptance-contract.mjs';
11
17
 
12
18
  // The whole check step of a current-session run is one host call with this deadline
13
19
  // (runtime/js/cm-ai/host-conversation-execution.mjs, outerTimeoutMs). The test
@@ -26,6 +32,8 @@ const usage = '用法: cm-start-check.mjs --plan PLAN.json [--json] [--strict]\n
26
32
  + ' 1. scope 是否含受保护路径(AGENTS.md、tasks.md、.reviews、.cm-* 等)——error;\n'
27
33
  + ' scope 为空、重复、绝对路径、含 ../反斜杠/冒号等创建必拒的写法——输入不合法,退出 2\n'
28
34
  + ' 2. PLAN.checks 是否重复、是否重复跑全量测试、各检查超时之和是否超过整步 30 分钟——warn\n'
35
+ + ' scope 改到代码根 TESTING.md「## 牵连测试」表里的路径,却没跑表里对应的旧界面测试——warn;\n'
36
+ + ' 只跑了部分界面测试(-only-testing)而项目没有这张表——info(没能核对)\n'
29
37
  + ' 3. scope 内文件在代码根是否已有未提交改动——warn(Git 不可用时是 warn,不是 Git 仓库时是 info)\n'
30
38
  + '退出码:0 无 error(warn 只提示);1 有 error,或加 --strict 时有 warn;2 输入读不了或不支持。\n';
31
39
 
@@ -79,8 +87,6 @@ function checkProtectedScope(scope) {
79
87
  message: `scope 含受保护路径 ${item}:创建运行会被 protected_scope 拒绝。先走人工通道同步该文件,再把它从 scope 里去掉`}));
80
88
  }
81
89
 
82
- const isXcodebuild = tokens => tokens.some(token => path.basename(token) === 'xcodebuild');
83
- const isTestAction = tokens => tokens.some(token => token === 'test' || token === 'test-without-building');
84
90
  const optionValue = (tokens, name) => {
85
91
  const at = tokens.indexOf(name);
86
92
  return at === -1 ? '' : tokens[at + 1] ?? '';
@@ -122,10 +128,73 @@ function checkChecks(plan) {
122
128
  const totalMs = own.reduce((sum, entry) => sum + entry.timeoutMs, 0);
123
129
  if (totalMs > CHECK_CALL_LIMIT_MS)
124
130
  findings.push({level: 'warn', code: 'check_budget_over_call_limit', totalMs, limitMs: CHECK_CALL_LIMIT_MS,
125
- message: `各检查超时之和 ${Math.round(totalMs / 60000)} 分钟,超过检查整步的 ${CHECK_CALL_LIMIT_MS / 60000} 分钟期限;这是最坏情况,实际可能更短。拆成多次运行,或缩减检查`});
131
+ message: `各检查超时之和 ${Math.round(totalMs / 60000)} 分钟,超过检查整步的 ${CHECK_CALL_LIMIT_MS / 60000} 分钟期限;这是最坏情况,实际可能更短。`
132
+ + '按分层缩减(单元测试全跑,界面测试只跑本任务新写的和牵连的,其余留到功能末尾回归任务),或拆成多次运行'});
126
133
  return findings;
127
134
  }
128
135
 
136
+ // The project's own record of which old UI tests a change reaches: a "## 牵连测试" table in
137
+ // TESTING.md (code root first, then docs/). After the header row, each row is
138
+ // | changed paths (a trailing / is a directory) | test identifiers as the check command names them |.
139
+ const AFFECTED_HEADING = /^##\s+牵连测试\s*$/;
140
+ const TESTING_FILES = ['TESTING.md', path.join('docs', 'TESTING.md')];
141
+ // Backticks are optional and may be mixed with plain items in one cell; a backticked item is
142
+ // kept whole (it may hold spaces), the plain rest is split on 、 , ; and spaces.
143
+ const cellItems = cell => [...[...cell.matchAll(/`([^`]+)`/g)].map(match => match[1].trim()),
144
+ ...cell.replace(/`[^`]*`/g, ' ').split(/[、,,;;\s]+/)].filter(Boolean);
145
+
146
+ export function readAffectedMap(root) {
147
+ for (const name of TESTING_FILES) {
148
+ let text;
149
+ try { text = fs.readFileSync(path.join(root, name), 'utf8'); } catch { continue; }
150
+ const lines = text.split(/\r?\n/);
151
+ const start = lines.findIndex(line => AFFECTED_HEADING.test(line.trim()));
152
+ if (start === -1) continue;
153
+ const rows = [];
154
+ let header = true;
155
+ for (const line of lines.slice(start + 1)) {
156
+ if (/^#{1,2}\s/.test(line)) break;
157
+ const cells = line.trim().match(/^\|(.*)\|$/)?.[1].split('|').map(cell => cell.trim());
158
+ if (!cells || cells.length < 2) continue;
159
+ if (cells.every(cell => /^:?-+:?$/.test(cell))) { header = false; continue; }
160
+ if (header) continue;
161
+ const paths = cellItems(cells[0]).map(item => item.replace(/^\.\//, '')), tests = cellItems(cells[1]);
162
+ if (paths.length > 0 && tests.length > 0) rows.push({paths, tests});
163
+ }
164
+ // A heading with no usable row is not a table: report it like a missing one, not as "nothing affected".
165
+ if (rows.length > 0) return {file: name, rows};
166
+ }
167
+ return null;
168
+ }
169
+
170
+ function checkAffectedTests(plan, definition) {
171
+ const commands = (Array.isArray(plan.checks) ? plan.checks : [])
172
+ .map(item => item?.command).filter(tokens => Array.isArray(tokens) && tokens.every(token => typeof token === 'string'));
173
+ const map = fs.existsSync(definition.codeProject) ? readAffectedMap(definition.codeProject) : null;
174
+ if (map === null) {
175
+ if (!commands.some(tokens => tokens.some(token => token.startsWith('-only-testing')))) return [];
176
+ return [{level: 'info', code: 'affected_map_missing',
177
+ message: '只跑了部分界面测试(-only-testing),但代码根 TESTING.md/docs/TESTING.md 没有「## 牵连测试」表,'
178
+ + '没能核对本任务改动牵连的旧界面测试是否都跑了'}];
179
+ }
180
+ const touches = (scopePath, rowPath) => rowPath.endsWith('/') ? scopePath.startsWith(rowPath) : scopePath === rowPath;
181
+ const missing = new Map();
182
+ for (const row of map.rows) {
183
+ const hit = definition.scope.filter(scopePath => row.paths.some(rowPath => touches(scopePath, rowPath)));
184
+ if (hit.length === 0) continue;
185
+ for (const id of row.tests) {
186
+ if (commands.some(tokens => runsTest(tokens, id))) continue;
187
+ missing.set(id, [...new Set([...(missing.get(id) ?? []), ...hit])]);
188
+ }
189
+ }
190
+ if (missing.size === 0) return [];
191
+ const tests = [...missing.keys()], paths = [...new Set([...missing.values()].flat())];
192
+ return [{level: 'warn', code: 'affected_tests_not_run', file: map.file, tests: tests.slice(0, MAX_LISTED), paths: paths.slice(0, MAX_LISTED),
193
+ message: `scope 改到 ${paths.slice(0, MAX_LISTED).join('、')}${paths.length > MAX_LISTED ? '…' : ''},按 ${map.file} 的牵连测试表,`
194
+ + `要在本任务当场跑 ${tests.slice(0, MAX_LISTED).join('、')}${tests.length > MAX_LISTED ? '…' : ''},PLAN.checks 里没有跑它们的检查。`
195
+ + '改了共用模块不能只跑新测试、留到功能末尾回归;补上这些测试,确实不牵连就改 TESTING.md 的表'}];
196
+ }
197
+
129
198
  function hasGitMarker(root) {
130
199
  for (let current = root; ; current = path.dirname(current)) {
131
200
  if (fs.existsSync(path.join(current, '.git'))) return true;
@@ -174,9 +243,62 @@ function checkDirtyScope(definition) {
174
243
  + '运行基线会把它们当起点,交审包里看不到这部分改动;若是上次的任务代码,先还原,确认是有意保留的再继续'}];
175
244
  }
176
245
 
177
- export function startCheck(planFile) {
246
+ // requiredTests comes from the caller's frozen approved contract, never from the
247
+ // mutable affected-test table or the developer's PLAN. Other warnings stay advisory.
248
+ export function checkMandatoryTests(plan, requiredTests) {
249
+ const coverage = mandatoryCheckCoverage({requiredTests,
250
+ commands: (Array.isArray(plan.checks) ? plan.checks : []).map(item => item?.command)});
251
+ if (coverage.satisfied) return [];
252
+ return [{level: 'error', code: 'mandatory_tests_not_covered',
253
+ tests: coverage.missing, unverifiable: coverage.unverifiable,
254
+ message: `已批准必验合同要求 ${coverage.missing.join('、')},当前检查命令未能证明完整选择;`
255
+ + '补充明确执行这些测试的命令。包装脚本须先经原规格流程确认可机械核对的测试映射,不能仅在参数中出现测试名就认定覆盖'}];
256
+ }
257
+
258
+ function approvedStartContract(plan,definition){
259
+ // Old scope-only advisory inputs have no task identity and make no claim
260
+ // about a runnable CM specification. Real run definitions are checked below.
261
+ if(definition.specsDir===undefined&&definition.specification===undefined)return null;
262
+ try{
263
+ if(plan.mode==='resume'){
264
+ const snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,
265
+ identity:{repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});
266
+ const baseline=readReviewBaseline(snapshot.records[0]?.payload?.baseline);
267
+ if(baseline.specificationRoot!==definition.specsDir||baseline.identity.taskId!==definition.identity.taskId)
268
+ throw new Error('owner mismatch');
269
+ return baseline.specification?.acceptanceContract??null;
270
+ }
271
+ // A create-plan may be inspected before any specification has been written.
272
+ // Preserve its old scope/budget diagnostics; this read-only check grants no
273
+ // execution admission. Any existing feature/approval (including symlinks),
274
+ // resume owner or read failure still takes the strict evidence path below.
275
+ if(plan.mode===undefined||plan.mode==='create'){
276
+ const root=definition.specsDir;
277
+ if(typeof root!=='string'||!path.isAbsolute(root)||fs.realpathSync(root)!==root
278
+ ||!fs.lstatSync(root).isDirectory()||typeof definition.feature!=='string'
279
+ ||!/^\d+\.[^/\\\x00-\x1f]+$/.test(definition.feature))throw new Error('invalid specification root');
280
+ const absent=file=>{try{fs.lstatSync(file);return false;}catch(error){if(error.code==='ENOENT')return true;throw error;}};
281
+ if(absent(path.join(root,'.cm-specs-status'))&&absent(path.join(root,definition.feature)))return null;
282
+ }
283
+ return captureSpecificationMaterial({specsRoot:definition.specsDir,feature:definition.feature,
284
+ taskId:definition.identity.taskId}).acceptanceContract;
285
+ }catch{throw new InputError('必验合同无法从已批准规格或原运行读取;先核对规格批准与原运行身份,不能由 PLAN 自报或省略必验范围');}
286
+ }
287
+
288
+ export function startCheck(planFile, {requiredTests = []} = {}) {
178
289
  const {plan, definition} = loadStartInputs(planFile);
179
- return [...checkProtectedScope(definition.scope), ...checkChecks(plan), ...checkDirtyScope(definition)];
290
+ const contract=approvedStartContract(plan,definition),mandatory=[];
291
+ if(contract){
292
+ if(contract.unresolved.length)mandatory.push({level:'error',code:'acceptance_mapping_required',
293
+ message:`已批准材料的必验映射尚不明确:${contract.unresolved.join(';')}`});
294
+ // Planned argv is checked before execution; no success evidence is emitted.
295
+ const coverage=acceptanceCoverage(contract,(Array.isArray(plan.checks)?plan.checks:[]).map(item=>({...item,outcome:'passed'})));
296
+ if(!coverage.satisfied)mandatory.push({level:'error',code:'mandatory_checks_not_covered',
297
+ tests:coverage.missing,unverifiable:coverage.unverifiable,commands:coverage.missingCommands,
298
+ message:'当前计划未完整包含冻结的必验检查;补齐检查,不能缩减批准的验收范围'});
299
+ }
300
+ return [...checkProtectedScope(definition.scope), ...checkChecks(plan), ...checkAffectedTests(plan, definition),
301
+ ...checkMandatoryTests(plan, requiredTests), ...mandatory, ...checkDirtyScope(definition)];
180
302
  }
181
303
 
182
304
  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} 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 => {
@@ -98,13 +142,96 @@ test('two xcodebuild test checks on one scheme and destination warn unless one i
98
142
  const overlap = check(project(t, {checks: [xcode('unit'), xcode('ui', '-resultBundlePath', 'x')]}));
99
143
  assert.deepEqual(overlap.report.findings.map(item => [item.code, item.ids]), [['overlapping_full_test', ['unit', 'ui']]]);
100
144
  assert.equal(overlap.status, 0);
101
- assert.deepEqual(check(project(t, {checks: [xcode('unit'), xcode('ui', '-only-testing:AppUITests')]})).report.findings, []);
145
+ // Narrowed, so no overlap; with no affected-test table the narrowing itself cannot be checked.
146
+ assert.deepEqual(codes(check(project(t, {checks: [xcode('unit'), xcode('ui', '-only-testing:AppUITests')]})).report), ['affected_map_missing']);
102
147
  const other = cmd('ui', ['xcodebuild', 'test', '-scheme', 'Other', '-destination', 'id=U1']);
103
148
  assert.deepEqual(check(project(t, {checks: [xcode('unit'), other]})).report.findings, []);
149
+ const retried = cmd('ui', ['xcodebuild', '-retry-tests-on-failure', 'test', '-scheme', 'App', '-destination', 'id=U1']);
150
+ assert.deepEqual(codes(check(project(t, {checks: [xcode('unit'), retried]})).report), ['overlapping_full_test']);
151
+ for (const mode of ['-enumerate-tests', '-showBuildSettings'])
152
+ assert.deepEqual(check(project(t, {checks: [xcode('unit'), xcode('ui', mode)]})).report.findings, []);
153
+ const buildNamedTest = cmd('ui', ['xcodebuild', '-retry-tests-on-failure', '-resultBundlePath', 'test', 'build-for-testing', '-scheme', 'App', '-destination', 'id=U1']);
154
+ assert.deepEqual(check(project(t, {checks: [xcode('unit'), buildNamedTest]})).report.findings, []);
104
155
  const build = cmd('build', ['xcodebuild', 'build', '-scheme', 'App', '-destination', 'id=U1']);
105
156
  assert.deepEqual(check(project(t, {checks: [xcode('unit'), build]})).report.findings, []);
106
157
  });
107
158
 
159
+ const TABLE = ['# 测试', '', '## 牵连测试', '', '| 改动路径 | 牵连的旧界面测试 |', '|---|---|',
160
+ '| `src/queue.js` | `AppUITests/SearchUITests`、AppUITests/SavedUITests |',
161
+ '| `src/scroll/` | `AppUITests/AnchorUITests` |', '| `src/other.js` | `AppUITests/OtherUITests` |', '', '## 其他', '| `src/a.js` | `AppUITests/NotInTable` |', ''].join('\n');
162
+ const mapped = (t, checks, {scope = ['src/queue.js', 'src/scroll/keep.js', 'src/a.js'], file = 'TESTING.md'} = {}) =>
163
+ project(t, {scope, checks, files: {'src/queue.js': 'q\n', 'src/scroll/keep.js': 'k\n', 'src/a.js': 'a\n', [file]: TABLE}});
164
+
165
+ test('a scope that touches a shared module warns when its mapped old UI tests are not in the checks', t => {
166
+ const narrow = check(mapped(t, [cmd('unit', ['node', '--test']), xcode('ui', '-only-testing:AppUITests/NewUITests')]));
167
+ assert.equal(narrow.status, 0);
168
+ assert.deepEqual(narrow.report.findings.map(item => [item.code, item.level, item.file, item.tests, item.paths]),
169
+ [['affected_tests_not_run', 'warn', 'TESTING.md', ['AppUITests/SearchUITests', 'AppUITests/SavedUITests', 'AppUITests/AnchorUITests'],
170
+ ['src/queue.js', 'src/scroll/keep.js']]]);
171
+ assert.equal(run('--plan', mapped(t, [xcode('ui', '-only-testing:AppUITests/NewUITests')]).planFile, '--strict').status, 1);
172
+ // Rows after the next ## heading, and rows whose paths the scope does not touch, ask for nothing.
173
+ assert.deepEqual(check(mapped(t, [xcode('ui', '-only-testing:AppUITests/NewUITests')], {scope: ['src/a.js']})).report.findings, []);
174
+ });
175
+
176
+ test('a mapped test counts as run by -only-testing on it or an ancestor, a full run, or a wrapper argument; not by one method or a skip', t => {
177
+ const findings = checks => check(mapped(t, checks)).report.findings.map(item => [item.code, item.tests]);
178
+ const all = ['-only-testing:AppUITests/SearchUITests', '-only-testing:AppUITests/SavedUITests', '-only-testing:AppUITests/AnchorUITests'];
179
+ assert.deepEqual(findings([xcode('ui', ...all)]), []);
180
+ assert.deepEqual(findings([xcode('ui', '-only-testing:AppUITests')]), []);
181
+ assert.deepEqual(findings([xcode('ui')]), []);
182
+ assert.deepEqual(findings([cmd('ui', ['sh', 'ui.sh', 'AppUITests/SearchUITests,AppUITests/SavedUITests', 'AppUITests/AnchorUITests'])]), []);
183
+ assert.deepEqual(findings([xcode('ui', '-only-testing:AppUITests/SearchUITests/testOne', ...all.slice(1))]),
184
+ [['affected_tests_not_run', ['AppUITests/SearchUITests']]]);
185
+ assert.deepEqual(findings([xcode('ui', '-skip-testing:AppUITests/AnchorUITests')]), [['affected_tests_not_run', ['AppUITests/AnchorUITests']]]);
186
+ assert.deepEqual(findings([xcode('ui', '-only-testing:AppUITests', '-skip-testing:AppUITests')]),
187
+ [['affected_tests_not_run', ['AppUITests/SearchUITests', 'AppUITests/SavedUITests', 'AppUITests/AnchorUITests']]]);
188
+ // Skipping one method of a mapped class leaves the class only partly run, narrowed or not.
189
+ assert.deepEqual(findings([xcode('ui', ...all, '-skip-testing:AppUITests/SearchUITests/testOld')]),
190
+ [['affected_tests_not_run', ['AppUITests/SearchUITests']]]);
191
+ assert.deepEqual(findings([xcode('ui', '-skip-testing:AppUITests/SearchUITests/testOld')]), [['affected_tests_not_run', ['AppUITests/SearchUITests']]]);
192
+ // A direct xcodebuild runs only through a test action and its test selection, never other arguments.
193
+ const buildOnly = cmd('ui', ['xcodebuild', 'build-for-testing', '-scheme', 'App', ...all]);
194
+ assert.deepEqual(findings([buildOnly]).map(item => item[0]), ['affected_tests_not_run']);
195
+ const valueNamedTest = cmd('ui', ['xcodebuild', 'build-for-testing', '-scheme', 'App', '-resultBundlePath', 'test', ...all]);
196
+ assert.deepEqual(findings([valueNamedTest]).map(item => item[0]), ['affected_tests_not_run']);
197
+ assert.deepEqual(findings([cmd('ui', ['/usr/bin/xcodebuild', 'COMPILER_INDEX_STORE_ENABLE=NO', '-quiet', 'test-without-building', ...all])]), []);
198
+ // No-value flags never swallow the next word; a word after an unknown option is not taken as the action.
199
+ assert.deepEqual(findings([cmd('ui', ['xcodebuild', '-retry-tests-on-failure', 'test', '-scheme', 'App', ...all])]), []);
200
+ assert.deepEqual(findings([cmd('ui', ['xcodebuild', ...all, 'test', '-scheme', 'App'])]), []);
201
+ // Listing and showing modes name the test action but run nothing, before or after it.
202
+ for (const tokens of [['xcodebuild', '-enumerate-tests', 'test'], ['xcodebuild', 'test', '-showBuildSettings'], ['xcodebuild', '-showBuildSettings', 'test']])
203
+ assert.deepEqual(findings([cmd('ui', [...tokens, '-scheme', 'App', ...all])]).map(item => item[0]), ['affected_tests_not_run']);
204
+ const flagThenValue = cmd('ui', ['xcodebuild', '-retry-tests-on-failure', '-resultBundlePath', 'test', 'build-for-testing', '-scheme', 'App', ...all]);
205
+ assert.deepEqual(findings([flagThenValue]).map(item => item[0]), ['affected_tests_not_run']);
206
+ assert.deepEqual(findings([cmd('ui', ['xcodebuild', '-futureFlag', 'test', '-scheme', 'App', ...all])]).map(item => item[0]), ['affected_tests_not_run']);
207
+ assert.deepEqual(findings([xcode('ui', '-only-testing:AppUITests/NewUITests', '-resultBundlePath', 'r/AppUITests/SearchUITests.xcresult',
208
+ ...all.slice(1))]), [['affected_tests_not_run', ['AppUITests/SearchUITests']]]);
209
+ });
210
+
211
+ test('mixed backtick and plain items in one cell are all read; a heading without rows counts as no table', t => {
212
+ const mixed = ['## 牵连测试', '| 路径 | 测试 |', '|:--|--:|', '| `src/queue.js`、src/scroll.js | `AppUITests/SearchUITests`, AppUITests/SavedUITests |', ''].join('\n');
213
+ const p = project(t, {scope: ['src/scroll.js'], checks: [xcode('ui', '-only-testing:AppUITests/SearchUITests')],
214
+ files: {'src/scroll.js': 's\n', 'TESTING.md': mixed}});
215
+ assert.deepEqual(check(p).report.findings.map(item => [item.code, item.tests]), [['affected_tests_not_run', ['AppUITests/SavedUITests']]]);
216
+ const spaced = project(t, {scope: ['src/Shared Module.js'], checks: [xcode('ui', '-only-testing:AppUITests/NewUITests')],
217
+ files: {'src/Shared Module.js': 's\n', 'TESTING.md': '## 牵连测试\n| 路径 | 测试 |\n|---|---|\n| `src/Shared Module.js` | `AppUITests/SearchUITests` |\n'}});
218
+ assert.deepEqual(check(spaced).report.findings.map(item => [item.code, item.paths]), [['affected_tests_not_run', ['src/Shared Module.js']]]);
219
+ const empty = project(t, {checks: [xcode('ui', '-only-testing:AppUITests/NewUITests')],
220
+ files: {'src/a.js': 'a\n', 'TESTING.md': '## 牵连测试\n\nTODO\n\n## 牵连测试\n'}});
221
+ assert.deepEqual(codes(check(empty).report), ['affected_map_missing']);
222
+ });
223
+
224
+ test('the affected-test table is also read from docs/TESTING.md; without one only a narrowed UI run is reported, as info', t => {
225
+ assert.deepEqual(codes(check(mapped(t, [xcode('ui', '-only-testing:AppUITests/NewUITests')], {file: 'docs/TESTING.md'})).report),
226
+ ['affected_tests_not_run']);
227
+ const bare = project(t, {checks: [xcode('ui', '-only-testing:AppUITests/NewUITests')]});
228
+ const info = check(bare);
229
+ assert.equal(info.status, 0);
230
+ assert.deepEqual(info.report.findings.map(item => [item.level, item.code]), [['info', 'affected_map_missing']]);
231
+ assert.match(run('--plan', bare.planFile).out, /体检完成/);
232
+ assert.deepEqual(check(project(t, {checks: [xcode('ui'), cmd('unit', ['node', '--test'])]})).report.findings, []);
233
+ });
234
+
108
235
  test('the summed check timeouts warn only above the 30 minute call limit', t => {
109
236
  assert.equal(CHECK_CALL_LIMIT_MS, 1800000);
110
237
  const exact = project(t, {checks: [cmd('a', ['a']), cmd('b', ['b'])]});
@@ -233,13 +360,15 @@ test('unreadable or unsupported input exits 2 with a Chinese reason and no repor
233
360
  });
234
361
 
235
362
  test('the check never writes: every file, mtime and the git index are unchanged, dirty tree included', t => {
236
- const p = project(t, {scope: ['src/a.js', 'AGENTS.md'], checks: [xcode('unit'), xcode('ui'), cmd('d', ['x']), cmd('e', ['x'])]});
363
+ const p = project(t, {scope: ['src/a.js', 'AGENTS.md'], checks: [cmd('unit', ['swift', 'test']), xcode('ui', '-only-testing:AppUITests/NewUITests'), cmd('d', ['x']), cmd('e', ['x'])],
364
+ files: {'src/a.js': 'a\n', 'TESTING.md': '## 牵连测试\n|路径|测试|\n|-|-|\n|`src/a.js`|`AppUITests/OldUITests`|\n'}});
237
365
  fs.writeFileSync(path.join(p.root, 'src/a.js'), 'dirty\n');
238
366
  fs.writeFileSync(path.join(p.root, 'src/untracked.js'), 'u\n');
239
367
  const before = snapshot(p.dir);
240
368
  const r = check(p);
241
369
  assert.equal(r.status, 1);
242
370
  assert.ok(r.report.findings.length >= 3);
371
+ assert.ok(codes(r.report).includes('affected_tests_not_run'));
243
372
  assert.equal(snapshot(p.dir), before);
244
373
  });
245
374
 
@@ -319,3 +448,34 @@ test('repository config cannot run programs: fsmonitor, clean, process and requi
319
448
  assert.equal(fs.existsSync(mark), false);
320
449
  assert.equal(r.status, 0);
321
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
+ });
@@ -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
+ });