@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
@@ -34,7 +34,7 @@ function fixture(t){
34
34
  const file=name=>path.join(specsDir,feature,name);
35
35
  fs.writeFileSync(file('requirements.md'),'# Requirements\n- [ ] [AC-001] a exports new\n');
36
36
  fs.writeFileSync(file('design.md'),'# Design\nsimple\n');
37
- fs.writeFileSync(file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b\n\n- T-002 依赖 T-001\n');
37
+ fs.writeFileSync(file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b\n\n- T-002 依赖 T-001\n');
38
38
  fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
39
39
  const identity=(runId='rebind-run-0001')=>({repositoryId:'rebind-fixture',runId,taskId:'T-001',attempt:1});
40
40
  const definition=(runId)=>({version:1,specsDir,codeProject,feature,identity:identity(runId),scope:['a.mjs'],requirements:['requirements.md']});
@@ -60,6 +60,8 @@ function executionFor(f,{decision=null,onReview=()=>{},onDevelop=()=>{}}={}){
60
60
  examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};
61
61
  }};
62
62
  return {configuration:{kind:'synthetic-host-v1'},timeoutMs:2000,excludedContexts:['control'],
63
+ verificationGate:async request=>({satisfied:true,...(request.acceptanceContract?{items:request.acceptanceContract.obligations.map(item=>
64
+ ({...item,satisfied:true,evidence:'Synthetic fixture checks and independent review cover this approved obligation'}))}:{})}),
63
65
  developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({
64
66
  requestedModel:'fixture',worker:async()=>{fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'export const a=2;\n');onDevelop();
65
67
  return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
@@ -83,7 +85,7 @@ const stateFile=(f,runId='rebind-run-0001')=>path.join(f.specsDir,'.reviews','.e
83
85
 
84
86
  test('another task changed and re-approved: status names spec_drift and the rebind; the rebind keeps the delivery',async t=>{
85
87
  const f=fixture(t),packageDigest=await awaitingReview(f);
86
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b(导出 3)\n\n- T-002 依赖 T-001\n');
88
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b(导出 3)\n\n- T-002 依赖 T-001\n');
87
89
  reapprove(f);
88
90
  await withRun(f,'resume',{decision:{status:'approved'}},async(host,identity)=>{
89
91
  const status=await ask(host,identity,'status');
@@ -146,7 +148,7 @@ test('a change to what the run saw fails closed, names it, and both recovery exi
146
148
 
147
149
  test('a rebind cannot carry changed content: a later content change still drifts',async t=>{
148
150
  const f=fixture(t);await awaitingReview(f);
149
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
151
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
150
152
  await withRun(f,'resume',{specRebindReason:'只改了 T-002'},async()=>{});
151
153
  fs.appendFileSync(f.file('requirements.md'),'- [ ] [AC-002] b exports 3\n');reapprove(f);
152
154
  await withRun(f,'resume',{},async(host,identity)=>{
@@ -162,7 +164,7 @@ test('a spec change during review never leaves status advertising a refused acti
162
164
  const f=fixture(t);
163
165
  await withRun(f,'create',{},async(host,identity)=>assert.equal((await ask(host,identity,'start')).state,'awaiting_review'));
164
166
  const changeDuringReview=()=>{
165
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 审查期间改了\n\n- T-002 依赖 T-001\n');reapprove(f);};
167
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 审查期间改了\n\n- T-002 依赖 T-001\n');reapprove(f);};
166
168
  await withRun(f,'resume',{decision:{status:'approved'},onReview:changeDuringReview},async(host,identity)=>{
167
169
  await ask(host,identity,'advance');
168
170
  const status=await ask(host,identity,'status');
@@ -199,7 +201,7 @@ test('host CLI accepts the rebind only on resume with a single-line reason',t=>{
199
201
  test('a run rebound before its first delivery develops against the re-approved spec',async t=>{
200
202
  const f=fixture(t);
201
203
  await withRun(f,'create',{},async(host,identity)=>assert.equal((await ask(host,identity,'status')).state,'ready'));
202
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
204
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
203
205
  await withRun(f,'resume',{},async(host,identity)=>{
204
206
  const status=await ask(host,identity,'status');
205
207
  assert.equal(status.state,'ready');assert.equal(status.code,'spec_drift');assert.equal(status.pendingAction,'spec_rebind');
@@ -213,7 +215,7 @@ test('a run rebound before its first delivery develops against the re-approved s
213
215
 
214
216
  test('journal replay accepts a rebind only bound to this run material and before completion',async t=>{
215
217
  const f=fixture(t);await awaitingReview(f);
216
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
218
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
217
219
  await withRun(f,'resume',{specRebindReason:'只改了 T-002'},async()=>{});
218
220
  const records=JSON.parse(fs.readFileSync(stateFile(f),'utf8')).records,config=records[0].payload.config;
219
221
  const index=records.findIndex(row=>row.payload.type==='specification-rebound');
@@ -249,7 +251,7 @@ test('a spec change while the developer works stops the run with its real exits'
249
251
  // decide from the material alone.
250
252
  async function multiLineRun(f){
251
253
  fs.writeFileSync(f.file('requirements.md'),'# Requirements\n- [ ] [AC-001] Store user data\n 必须静态加密\n- [ ] [AC-002] b exports 3\n');
252
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n - 约束:保留旧接口\n- [ ] T-002: 新增 b\n - 约束:导出 3\n\n## 验证要求\n- T-002: node --test b\n\n## 依赖关系\n- T-002 依赖 T-001\n');
254
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n - 约束:保留旧接口\n- [ ] T-002: 新增 b\n - 约束:导出 3\n\n## 验证要求\n- T-002: node --test b\n\n## 依赖关系\n- T-002 依赖 T-001\n');
253
255
  reapprove(f);
254
256
  return awaitingReview(f);
255
257
  }
@@ -293,12 +295,12 @@ test('multi-line spec: other tasks items, sub-bullets, verification and new task
293
295
  test('a run bound before taskScopeDigest keeps verifying but is never rebindable',async t=>{
294
296
  const f=fixture(t);
295
297
  await withRun(f,'create',{},async(host,identity)=>assert.equal((await ask(host,identity,'status')).state,'ready'));
296
- // Legacy-shaped journal: the init baseline material without taskScopeDigest.
298
+ // Legacy-shaped journal: before either taskScopeDigest or acceptanceContract existed.
297
299
  const file=stateFile(f),state=JSON.parse(fs.readFileSync(file,'utf8'));
298
300
  assert.equal(state.records.length,1);
299
301
  const init=state.records[0],{baselineDigest,...baseline}=init.payload.baseline;
300
302
  assert.match(baseline.specification.taskScopeDigest,/^[a-f0-9]{64}$/);
301
- const {taskScopeDigest,...material}=baseline.specification;
303
+ const {taskScopeDigest,acceptanceContract,...material}=baseline.specification;
302
304
  const legacyBaseline={...baseline,specification:material};
303
305
  const {digest:oldDigest,...body}=init;
304
306
  const record={...body,payload:{...init.payload,baseline:{...legacyBaseline,baselineDigest:digest(legacyBaseline)}}};
@@ -307,12 +309,46 @@ test('a run bound before taskScopeDigest keeps verifying but is never rebindable
307
309
  await withRun(f,'resume',{},async(host,identity)=>{
308
310
  const status=await ask(host,identity,'status');assert.equal(status.state,'ready');assert.equal(status.code,null);
309
311
  });
310
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
312
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
311
313
  const status=await statusOf(f);
312
314
  assert.equal(status.code,'spec_drift');assert.equal(status.pendingAction,'none');assert.match(status.reason,/旧版本创建/);
313
315
  await assert.rejects(withRun(f,'resume',{specRebindReason:'旧运行'},async()=>{}),error=>error.code==='spec_rebind_refused');
314
316
  });
315
317
 
318
+ test('a 0.19 journal without acceptanceContract resumes through review and completion without rewriting its baseline',async t=>{
319
+ const f=fixture(t);
320
+ // The old material allowed a task description beyond the new evidence-item
321
+ // bound. Resume must not construct a new contract just to discard it later.
322
+ fs.writeFileSync(f.file('tasks.md'),fs.readFileSync(f.file('tasks.md'),'utf8')
323
+ .replace('修改 a [AC-001]','必验: 修改 a [AC-001] '+ 'x'.repeat(2100)));
324
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[f.feature],
325
+ specFiles:buildManifest(f.specsDir)}));
326
+ await withRun(f,'create',{},async(host,identity)=>assert.equal((await ask(host,identity,'status')).state,'ready'));
327
+ // A 0.19 run already recorded taskScopeDigest, but had no acceptance contract.
328
+ // Reseal only this synthetic init to model that original, supported shape.
329
+ const file=stateFile(f),state=JSON.parse(fs.readFileSync(file,'utf8'));
330
+ assert.equal(state.records.length,1);
331
+ const init=state.records[0],{baselineDigest,...baseline}=init.payload.baseline;
332
+ const {acceptanceContract,...material}=baseline.specification;
333
+ assert.equal(acceptanceContract.version,1);assert.match(material.taskScopeDigest,/^[a-f0-9]{64}$/);
334
+ assert.ok(material.task.description.length>2100,'legacy task text is beyond the new evidence item bound');
335
+ const legacyBaseline={...baseline,specification:material},{digest:oldDigest,...body}=init;
336
+ const record={...body,payload:{...init.payload,baseline:{...legacyBaseline,baselineDigest:digest(legacyBaseline)}}};
337
+ const legacyInit={...record,digest:digest(record)},{revision,...rest}=state,next={...rest,records:[legacyInit]};
338
+ fs.writeFileSync(file,JSON.stringify({...next,revision:digest(next)})+'\n');
339
+ let developments=0,reviews=0;
340
+ const execution=()=>({...executionFor(f,{onDevelop:()=>developments++,onReview:()=>reviews++}),verificationGate:null});
341
+ let opened=await openControlRun(f.definition(),'resume',execution());
342
+ try{assert.equal((await ask(opened.host,f.identity(),'start')).state,'awaiting_review');}finally{opened.close();}
343
+ opened=await openControlRun(f.definition(),'resume',execution(),{decision:{status:'approved'}});
344
+ try{assert.equal((await ask(opened.host,f.identity(),'advance')).state,'fixture_completed');}finally{opened.close();}
345
+ assert.equal(developments,1);assert.equal(reviews,1);
346
+ const records=JSON.parse(fs.readFileSync(file,'utf8')).records;
347
+ assert.deepEqual(records[0],legacyInit,'the old baseline and its digest remain original');
348
+ assert.equal(readRunnerHistory(records,records[0].payload.config,3).state.state,'fixture_completed');
349
+ assert.match(fs.readFileSync(f.file('tasks.md'),'utf8'),/\[x\] T-001/);
350
+ });
351
+
316
352
  test('test cases: another task case may change, this task case may not',async t=>{
317
353
  const f=fixture(t);
318
354
  const testCase=(id,taskId,title)=>({id,origin:'user',kind:'logic',blocking:true,acIds:['AC-001'],taskIds:[taskId],
@@ -340,7 +376,7 @@ test('task scope keeps shared fenced text after another task item',async()=>{
340
376
 
341
377
  test('a line naming this task under another task item changes: refused',async t=>{
342
378
  const f=fixture(t);
343
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b\n - T-001 must encrypt backups\n\n## 依赖关系\n- T-002 依赖 T-001\n');
379
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b\n - T-001 must encrypt backups\n\n## 依赖关系\n- T-002 依赖 T-001\n');
344
380
  reapprove(f);await awaitingReview(f);
345
381
  fs.writeFileSync(f.file('tasks.md'),fs.readFileSync(f.file('tasks.md'),'utf8').replace('T-001 must encrypt backups','T-001 may store plaintext backups'));
346
382
  reapprove(f);
@@ -364,7 +400,7 @@ test('another task test case that names this task changes: refused',async t=>{
364
400
  // original parse. Under the old parser `T-001:` is prose, not a duplicate task.
365
401
  test('an approval recorded before the shared grammar keeps parsing with the old grammar end to end',async t=>{
366
402
  const f=fixture(t);
367
- const tasks='# tasks\n- [ ] T-001: 修改 a\n- [ ] T-001:示例写法(旧解析器视为说明)\n- [ ] T-002: 新增 b\n\n- T-002 依赖 T-001\n';
403
+ const tasks='# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-001:示例写法(旧解析器视为说明)\n- [ ] T-002: 新增 b\n\n- T-002 依赖 T-001\n';
368
404
  fs.writeFileSync(f.file('tasks.md'),tasks);
369
405
  // Legacy-shaped approval: no taskGrammar field.
370
406
  fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[f.feature],specFiles:buildManifest(f.specsDir)}));
@@ -372,7 +408,7 @@ test('an approval recorded before the shared grammar keeps parsing with the old
372
408
  const done=await withRun(f,'create',{decision:{status:'approved'}},(host,identity)=>ask(host,identity,'advance'));
373
409
  assert.equal(done.state,'fixture_completed',JSON.stringify(done));
374
410
  const after=fs.readFileSync(f.file('tasks.md'),'utf8');
375
- assert.equal(after,tasks.replace('- [ ] T-001: 修改 a','- [x] T-001: 修改 a'),'the old mark-done flips only the real task');
411
+ assert.equal(after,tasks.replace('- [ ] T-001: 修改 a [AC-001]','- [x] T-001: 修改 a [AC-001]'),'the old mark-done flips only the real task');
376
412
  assert.equal(inspectCmAiAdmission({specsDir:f.specsDir,codeProject:f.codeProject}).nextTask.id,'T-002');
377
413
  // supersede reads the tick with the same old grammar: one task, already ticked.
378
414
  await assert.rejects(withRun(f,'create',{supersedeReason:'重跑'},async()=>{},'rebind-run-legacy-2'),
@@ -398,7 +434,7 @@ function reapproveRaw(f){
398
434
 
399
435
  test('re-approving another feature is refused while an untouched feature would change meaning',async t=>{
400
436
  const f=fixture(t);
401
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-001:旧示例\n');
437
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-001:旧示例\n');
402
438
  const other=path.join(f.specsDir,'2.other');fs.mkdirSync(other);
403
439
  for(const [name,body] of [['requirements.md','# R\n- [ ] [AC-001] other\n'],['design.md','# D\n'],['tasks.md','- [ ] T-001: other\n']])
404
440
  fs.writeFileSync(path.join(other,name),body);
@@ -482,7 +518,7 @@ test('a batch member never advertises spec_rebind and names the real exits',asyn
482
518
  executionFor:async()=>({...executionFor(f),check:createHostCheck({cwd:f.codeProject,commands:[{id:'hold',command:[process.execPath,'-e','process.exit(1)']}]})}),logHome:path.join(f.root,'batch-logs')});
483
519
  const first=await batch().handle({operation:'advance',requestId:'batch-advance'});
484
520
  assert.equal(first.state,'blocked',JSON.stringify(first));assert.equal(first.code,'develop_checks_not_passed');
485
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
521
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
486
522
  const status=await batch().handle({operation:'status',requestId:'batch-status'});
487
523
  assert.equal(status.code,'spec_drift');assert.equal(status.pendingAction,'none');
488
524
  assert.match(status.reason,/1\.work\/tasks\.md/);assert.match(status.reason,/批次成员不能换绑/);
@@ -29,7 +29,7 @@ async function fixture(fn){
29
29
  fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,runtimes:{available:'codex'}}));
30
30
  fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'# Requirements\n');
31
31
  fs.writeFileSync(path.join(specsDir,feature,'design.md'),'# Design\n');
32
- fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: 实现 a.js\n - 范围: `a.js`, `a.test.js`\n - 测试文件: `a.test.js`\n\n'
32
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: 必验: 实现 a.js\n - 范围: `a.js`, `a.test.js`\n - 测试文件: `a.test.js`\n\n'
33
33
  +'## 验证要求\n\n- T-001: RED 必须先失败;全部放入后检查通过。\n');
34
34
  fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
35
35
  const definition={version:1,codeProject,specsDir,feature,identity,scope:['a.js','a.test.js'],requirements:['requirements.md'],
@@ -40,11 +40,12 @@ async function fixture(fn){
40
40
  const develop=(requirements,test=TEST)=>({async call(kind,payload){
41
41
  assert.equal(kind,'develop');
42
42
  return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
43
- retrospective:{status:'no_new_lesson',candidates:[],reason:null},...(requirements===undefined?{}:{requirements})},
43
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null},...(requirements===undefined?{}:{requirements:typeof requirements==='function'?requirements(payload.request.payload.specification.acceptanceContract):requirements})},
44
44
  edits:[{path:'a.js',beforeSha256:payload.expected['a.js'],content:'new\n'},{path:'a.test.js',beforeSha256:null,content:test}]};
45
45
  }});
46
- const run=async(definition,bridge,protection)=>{
47
- const execution=createConversationExecution(definition,'host',bridge,null,null,null,false,'codex',{protection,controlPolicy:policy});
46
+ const completeReport=contract=>contract.obligations.map(item=>({...item,satisfied:true,evidence:'isolated fixture: a.js export and a.test.js assertions'}));
47
+ const run=async(definition,bridge,protection,selectedPolicy=policy)=>{
48
+ const execution=createConversationExecution(definition,'host',bridge,null,null,null,false,'codex',{protection,controlPolicy:selectedPolicy});
48
49
  const control=await openControlRun(definition,'create',execution);
49
50
  try{return await control.host.handle(request('start'));}finally{control.close();}
50
51
  };
@@ -52,8 +53,7 @@ const handoff=definition=>JSON.parse(fs.readFileSync(path.join(definition.specsD
52
53
 
53
54
  test('auto gate: a failing-first claim the host replay confirms passes, and the handoff carries the host record',
54
55
  {skip:!supported},()=>fixture(async({definition,protection})=>{
55
- const result=await run(definition,develop([{requirement:'T-001: RED 必须先失败',satisfied:true,evidence:'a.test.js 在旧 a.js 下失败',run:'red'},
56
- {requirement:'全部放入后检查通过',satisfied:true,evidence:'unit 检查'}]),protection);
56
+ const result=await run(definition,develop(completeReport),protection);
57
57
  assert.equal(result.state,'awaiting_review',JSON.stringify(result));
58
58
  const entries=handoff(definition).evidence;
59
59
  assert.match(entries.find(entry=>entry.startsWith('cm-requirement-evidence-v1: ')),/RED 必须先失败/);
@@ -69,6 +69,7 @@ test('auto gate: no report from the developer stops before review, with nothing
69
69
  {skip:!supported},()=>fixture(async({definition,protection})=>{
70
70
  const result=await run(definition,develop(undefined),protection);
71
71
  assert.equal(result.state,'blocked');assert.equal(result.code,'verification_precheck_failed');
72
+ assert.match(result.reason,/mandatory acceptance report missing/);
72
73
  assert.equal(fs.existsSync(path.join(definition.specsDir,'.reviews',`${definition.feature.replace(/^\d+\./,'')}-T-001-a1-handoff.json`)),false);
73
74
  }));
74
75
 
@@ -88,8 +89,7 @@ test('auto gate after a stopped attempt: the replay uses the task baseline, not
88
89
  const first=await run(definition,develop(undefined),protection);
89
90
  assert.equal(first.code,'verification_precheck_failed');
90
91
  assert.equal(fs.readFileSync(path.join(definition.codeProject,'a.js'),'utf8'),'new\n','the stopped delivery stays on disk');
91
- const execution=createConversationExecution(definition,'host',develop([{requirement:'T-001: RED 必须先失败',satisfied:true,
92
- evidence:'a.test.js 在旧 a.js 下失败',run:'red'}]),null,null,null,false,'codex',{protection,controlPolicy:policy});
92
+ const execution=createConversationExecution(definition,'host',develop(completeReport),null,null,null,false,'codex',{protection,controlPolicy:policy});
93
93
  const control=await openControlRun(definition,'resume',execution);
94
94
  let result;try{result=await control.host.handle(request('advance'));}finally{control.close();}
95
95
  // The gate passed and the handoff was published; this fixture has no reviewer, so the run stops at review.
@@ -97,3 +97,28 @@ test('auto gate after a stopped attempt: the replay uses the task baseline, not
97
97
  const record=JSON.parse(handoff(definition).evidence.find(entry=>entry.startsWith('cm-host-replay-v1: ')).slice('cm-host-replay-v1: '.length));
98
98
  assert.deepEqual([record.facts.baseline.outcome,record.facts.red.outcome],['failed','failed']);
99
99
  }));
100
+
101
+ for(const verification of ['auto','precheck','disabled'])test(`new contract cannot omit mandatory items through ${verification}`,
102
+ {skip:!supported},()=>fixture(async({definition,protection})=>{
103
+ const developer=develop(completeReport);
104
+ const bridge={async call(kind,payload){
105
+ if(kind==='verification_precheck')return {items:completeReport(payload.acceptanceContract).slice(0,1)};
106
+ const result=await developer.call(kind,payload);
107
+ result.value.requirements=result.value.requirements.slice(0,1);return result;
108
+ }};
109
+ const result=await run(definition,bridge,protection,{...policy,verification});
110
+ assert.equal(result.code,'verification_precheck_failed',JSON.stringify(result));
111
+ assert.match(result.reason,/missing acceptance obligation/);
112
+ assert.doesNotMatch(result.reason,/mandatory acceptance report missing/,'a partial report must identify missing items, not claim the whole report is absent');
113
+ }));
114
+
115
+ test('manual precheck cannot accept a RED claim contradicted by host replay',
116
+ {skip:!supported},()=>fixture(async({definition,protection})=>{
117
+ const developer=develop(completeReport,"process.exit(0);\n");
118
+ const bridge={async call(kind,payload){
119
+ if(kind==='verification_precheck')return {items:completeReport(payload.acceptanceContract)};
120
+ return developer.call(kind,payload);
121
+ }};
122
+ const result=await run(definition,bridge,protection,{...policy,verification:'precheck'});
123
+ assert.equal(result.code,'verification_precheck_failed',JSON.stringify(result));
124
+ }));
@@ -113,5 +113,5 @@ test('the gate receives both the task description and the verification section',
113
113
  assert.match(body[1],/written\(description\)\?\{description\}/);
114
114
  assert.match(body[1],/written\(verification\)\?\{verification\}/);
115
115
  // The gate steps aside only when neither exists.
116
- assert.match(body[1],/if\(!written\(verification\)&&!written\(description\)\)return true;/);
116
+ assert.match(body[1],/if\(!contract&&!written\(verification\)&&!written\(description\)\)return true;/);
117
117
  });
@@ -0,0 +1,212 @@
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 {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {standingProposalProblem,standingArchiveProblem,writeAutonomy} from '../runtime/js/autonomy.mjs';
9
+ import {buildManifest} from './cm-spec-manifest.mjs';
10
+ import {main as autonomyMain} from './cm-autonomy.mjs';
11
+
12
+ const feature='1.login';
13
+ const history='## 任务版本\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-01-01 | v1 | original |\n';
14
+ const task='- [ ] T-001: Validate login [AC-001]\n - 范围: `login.js`, `login.test.js`\n - 测试文件: `login.test.js`\n - 设备: 需要\n - 验收: 真机验证登录成功\n';
15
+ const requiredCase={id:'TC-001',origin:'generated',kind:'browser',blocking:true,acIds:['AC-001'],taskIds:['T-001'],
16
+ title:'Validate login on device',preconditions:['physical device'],steps:['sign in'],expected:['signed in'],cleanup:['sign out']};
17
+ const cases=items=>JSON.stringify({schemaVersion:'1.0',feature:'login',cases:items});
18
+ function input(){
19
+ const before={directories:[feature],status:JSON.stringify({status:'approved',taskGrammar:3}),files:{
20
+ [`${feature}/requirements.md`]:'# Requirements\n- [ ] [AC-001] Sign in on a physical device\n',
21
+ [`${feature}/design.md`]:'# Design\nValidate login on a physical device.\n',
22
+ [`${feature}/tasks.md`]:history+task,
23
+ [`${feature}/test-cases.json`]:cases([requiredCase])}};
24
+ return {before,proposal:{changedUserCases:[],removed:[],files:{...before.files}}};
25
+ }
26
+ const judge=mutate=>{const value=input();mutate(value.proposal,value.before);return standingProposalProblem(value.before,value.proposal);};
27
+
28
+ test('standing approval protects mandatory cases regardless of user, generated or inferred origin',()=>{
29
+ for(const origin of ['generated','inferred']){
30
+ const changes={blocking:false,kind:'logic',preconditions:['static config'],steps:['read config'],expected:['config exists'],
31
+ title:'Static check only',taskIds:[],acIds:[],cleanup:[]};
32
+ for(const [field,value] of Object.entries(changes)){
33
+ const reason=judge((proposal,before)=>{
34
+ const original={...requiredCase,origin};before.files[`${feature}/test-cases.json`]=cases([original]);
35
+ proposal.files[`${feature}/test-cases.json`]=cases([{...original,[field]:value}]);
36
+ });
37
+ assert.match(reason,new RegExp(`TC-001.*${field}`),`${origin} ${field}`);
38
+ }
39
+ }
40
+ assert.match(judge(proposal=>delete proposal.files[`${feature}/test-cases.json`]),/删除了必验用例 TC-001/);
41
+ assert.match(judge(proposal=>{proposal.files[`${feature}/test-cases.json`]=cases([{...requiredCase,origin:'user',blocking:false}]);}),/blocking/);
42
+ });
43
+
44
+ test('proven additions and representation-only replacements stay inside standing authorization',()=>{
45
+ assert.equal(judge(proposal=>{
46
+ const old={...requiredCase,acIds:['AC-001','AC-002']};
47
+ const reordered=Object.fromEntries(Object.entries(old).reverse());
48
+ proposal.files[`${feature}/test-cases.json`]=JSON.stringify({cases:[reordered,{...requiredCase,id:'TC-002',blocking:false}],
49
+ feature:'login',schemaVersion:'1.0'},null,2);
50
+ proposal.files[`${feature}/tasks.md`]=history.replace('| 2026-01-01 | v1 | original |',
51
+ '| 2026-01-01 | v1 | original |\n| 2026-01-02 | v2 | expanded scope |')+
52
+ task.replace('`login.js`, `login.test.js`','`login.test.js`, `login.js`, `helper.js`')+
53
+ '- [ ] T-002: [NEW] Add coverage [AC-002]\n - 范围: `extra.test.js`\n';
54
+ }),null);
55
+ assert.equal(judge((proposal,before)=>{
56
+ before.files[`${feature}/test-cases.json`]=cases([{...requiredCase,blocking:false}]);
57
+ proposal.files[`${feature}/test-cases.json`]=cases([requiredCase]);
58
+ }),null,'a previously optional case can become mandatory');
59
+ assert.equal(judge(proposal=>{proposal.files[`${feature}/design.md`]=proposal.files[`${feature}/design.md`].replaceAll('\n','\r\n');}),null);
60
+ });
61
+
62
+ test('standing approval requires equivalent task bindings; additions can defer mandatory browser QA',async t=>{
63
+ assert.match(judge(proposal=>{
64
+ proposal.files[`${feature}/test-cases.json`]=cases([{...requiredCase,taskIds:['T-001','T-004']}]);
65
+ }),/TC-001.*taskIds.*需明确确认/);
66
+ assert.equal(judge((proposal,before)=>{
67
+ before.files[`${feature}/test-cases.json`]=cases([{...requiredCase,taskIds:['T-001','T-004']}]);
68
+ proposal.files[`${feature}/test-cases.json`]=cases([{...requiredCase,taskIds:['T-004','T-001']}]);
69
+ }),null,'task reference order does not change the execution prerequisites');
70
+
71
+ const {createHostQaExecutor}=await import('../runtime/js/cm-ai/host-qa-executor.mjs');
72
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-autonomy-qa-binding-')));
73
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
74
+ const specs=path.join(root,'specs'),code=path.join(root,'code');
75
+ fs.mkdirSync(path.join(specs,feature),{recursive:true});fs.mkdirSync(code);fs.writeFileSync(path.join(code,'README.md'),'fixture\n');
76
+ const {before,proposal}=input();
77
+ before.files[`${feature}/tasks.md`]=task.replace('[ ] T-001','[x] T-001')+'- [ ] T-004: later task\n';
78
+ proposal.files={...before.files};
79
+ proposal.files[`${feature}/test-cases.json`]=cases([{...requiredCase,taskIds:['T-001','T-004']}]);
80
+ const save=files=>{
81
+ for(const [file,value] of Object.entries(files))fs.writeFileSync(path.join(specs,file),value);
82
+ const manifest=buildManifest(specs);
83
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'approved',taskGrammar:3,features:[feature],
84
+ specFiles:manifest,testCases:manifest.filter(row=>row.path.endsWith('/test-cases.json'))}));
85
+ };
86
+ const prepare=()=>createHostQaExecutor({specsDir:specs,codeProject:code,feature,runtime:'codex',requirements:['README.md'],
87
+ commands:[{id:'unit',command:[process.execPath,'--version'],caseIds:[]}],environment:{kind:'web',carrier:'browser',target:'fixture',scope:'local'},
88
+ timeoutMs:1000,logHome:path.join(root,'logs')}).prepare().configuration.plan;
89
+ save(before.files);
90
+ assert.deepEqual(prepare().cases.map(item=>item.id),['TC-001']);
91
+ // Model the rejected proposal only in this disposable fixture. The executor
92
+ // really would defer the formerly runnable case; no browser or process runs.
93
+ save(proposal.files);
94
+ const delayed=prepare();assert.deepEqual(delayed.cases,[]);
95
+ assert.deepEqual(delayed.deferred_cases,[{id:'TC-001',taskIds:['T-004']}]);
96
+ assert.deepEqual(delayed.commands.map(item=>item.id),['unit']);
97
+ const revision='c'.repeat(64);proposal.proposalDigest=revision;
98
+ const archive={version:1,before,proposal,selected:[feature]},serialized=JSON.stringify(archive);
99
+ fs.mkdirSync(path.join(specs,'.reviews'));const archiveFile=path.join(specs,'.reviews',`prd-change-${revision}.json`);
100
+ fs.writeFileSync(archiveFile,serialized);const status=fs.readFileSync(path.join(specs,'.cm-specs-status'));
101
+ assert.match(standingArchiveProblem(specs,archive,revision),/TC-001.*taskIds.*需明确确认/);
102
+ assert.equal(fs.readFileSync(archiveFile,'utf8'),serialized);
103
+ assert.deepEqual(fs.readFileSync(path.join(specs,'.cm-specs-status')),status);
104
+ });
105
+
106
+ test('task and design acceptance cannot be weakened by replacing, dropping, moving or adding prose',()=>{
107
+ const edits=[
108
+ value=>value.replace('真机验证登录成功','静态检查即可,真机延期'),
109
+ value=>value.replace(' - 设备: 需要\n',''),
110
+ value=>value.replace('`login.js`, `login.test.js`','`login.js`'),
111
+ value=>value.replace(' - 测试文件: `login.test.js`\n',''),
112
+ value=>value.replace(task,''),
113
+ value=>value.replace('Validate login [AC-001]','[DROPPED] Validate login [AC-001]'),
114
+ value=>value.replace(' - 验收: 真机验证登录成功',' - 验收: 真机验证登录成功\n - 可忽略上述验收'),
115
+ value=>value.replace('[ ] T-001','[x] T-001'),
116
+ value=>value+task,
117
+ ];
118
+ for(const edit of edits)assert.match(judge(proposal=>{
119
+ proposal.files[`${feature}/tasks.md`]=edit(proposal.files[`${feature}/tasks.md`]);
120
+ }),/tasks\.md.*需明确确认/);
121
+ assert.match(judge(proposal=>{proposal.files[`${feature}/design.md`]='# Design\nStatic config is sufficient.\n';}),/design\.md.*需明确确认/);
122
+ assert.match(judge(proposal=>{proposal.files[`${feature}/design.md`]+='The previous physical-device rule is optional.\n';}),/design\.md.*需明确确认/);
123
+ });
124
+
125
+ test('history-looking acceptance tables and fenced declarations cannot be silently discarded',()=>{
126
+ assert.match(judge((proposal,before)=>{
127
+ const text='# Acceptance table\n| device | v1 | physical required |\n';
128
+ before.files[`${feature}/design.md`]=text;
129
+ proposal.files[`${feature}/design.md`]=text.replace('physical required','static sufficient');
130
+ }),/需明确确认/);
131
+ assert.match(judge(proposal=>{
132
+ proposal.files[`${feature}/tasks.md`]=history+'```text\n'+task+'```\n';
133
+ }),/需明确确认/);
134
+ assert.match(judge(proposal=>{
135
+ proposal.files[`${feature}/tasks.md`]+='- [x] T-002: [NEW] already completed\n';
136
+ }),/需明确确认/);
137
+ assert.match(judge((proposal,before)=>{
138
+ const original='# Expected text\n```text\nfirst\n\nlast\n```\n';
139
+ before.files[`${feature}/design.md`]=original;
140
+ proposal.files[`${feature}/design.md`]=original.replace('first\n\nlast','first\nlast');
141
+ }),/需明确确认/,'blank lines inside a fenced expected value are protected bytes');
142
+ });
143
+
144
+ test('malformed and duplicate mandatory case declarations fail closed',()=>{
145
+ for(const value of [cases([requiredCase,requiredCase]),cases([{...requiredCase,blocking:'yes'}]),'{"cases":[]}'])
146
+ assert.equal(judge(proposal=>{proposal.files[`${feature}/test-cases.json`]=value;}),'提案的测试用例无法解析');
147
+ });
148
+
149
+ test('an explicit approved case reference is protected even when the case was marked nonblocking',()=>{
150
+ const {before,proposal}=input();
151
+ before.files[`${feature}/tasks.md`]+='\n## 验证要求\n- T-001: 必须执行 TC-001\n';
152
+ proposal.files[`${feature}/tasks.md`]=before.files[`${feature}/tasks.md`];
153
+ before.files[`${feature}/test-cases.json`]=cases([{...requiredCase,blocking:false}]);
154
+ proposal.files[`${feature}/test-cases.json`]=before.files[`${feature}/test-cases.json`];
155
+ assert.equal(standingProposalProblem(before,proposal),null);
156
+ proposal.files[`${feature}/test-cases.json`]=cases([{...requiredCase,blocking:false,expected:['config exists']}]);
157
+ assert.match(standingProposalProblem(before,proposal),/TC-001.*expected/);
158
+ delete proposal.files[`${feature}/test-cases.json`];
159
+ assert.match(standingProposalProblem(before,proposal),/删除了必验用例 TC-001/);
160
+ });
161
+
162
+ test('proposal precheck and final archive compare with the original recorded task grammar',t=>{
163
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-autonomy-grammar-')));
164
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));fs.mkdirSync(path.join(root,feature));
165
+ const {before,proposal}=input();before.status=JSON.stringify({status:'approved'});
166
+ // Under grammar 1 this was shared prose; approving under grammar 3 must not
167
+ // silently turn it into a new task or move its clauses out of the old task.
168
+ before.files[`${feature}/tasks.md`]+='- [ ] T-002: historical note\n';
169
+ proposal.files[`${feature}/tasks.md`]=before.files[`${feature}/tasks.md`];
170
+ for(const [file,value] of Object.entries(before.files))fs.writeFileSync(path.join(root,file),value);
171
+ fs.writeFileSync(path.join(root,'.cm-specs-status'),before.status);
172
+ const proposalFile=path.join(root,'proposal.json');fs.writeFileSync(proposalFile,JSON.stringify(proposal));
173
+ const output=[];
174
+ assert.equal(autonomyMain(['check-proposal','--specs-dir',root,'--proposal',proposalFile],
175
+ {stdout:{write:value=>output.push(value)},stderr:{write:value=>output.push(value)}}),1);
176
+ assert.match(output.join(''),/无法可靠比较.*需明确确认/);
177
+ assert.match(standingProposalProblem(before,proposal),/无法可靠比较/);
178
+ });
179
+
180
+ test('real approval CLI refuses weakening with unchanged files, then accepts only the current explicit proposal',t=>{
181
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-autonomy-acceptance-')));
182
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
183
+ const specs=path.join(root,'specs'),code=path.join(root,'code'),home=path.join(root,'home'),digest='a'.repeat(64);
184
+ fs.mkdirSync(path.join(specs,feature),{recursive:true});fs.mkdirSync(path.join(specs,'.reviews'));
185
+ fs.mkdirSync(code);fs.writeFileSync(path.join(code,'README.md'),'synthetic fixture\n');
186
+ const env={...process.env,CM_WORKFLOW_HOME:home,CM_WORKFLOW_LOG_HOME:path.join(root,'mirror')};
187
+ writeAutonomy('Continue within the approved requirements',{env});
188
+ const {before,proposal}=input();proposal.proposalDigest=digest;
189
+ proposal.files[`${feature}/tasks.md`]=proposal.files[`${feature}/tasks.md`].replace('真机验证登录成功','只检查配置即可');
190
+ for(const [file,value] of Object.entries(proposal.files))fs.writeFileSync(path.join(specs,file),value);
191
+ const archive={version:1,before,proposal,selected:[feature]};
192
+ fs.writeFileSync(path.join(specs,'.reviews',`prd-change-${digest}.json`),JSON.stringify(archive));
193
+ const status=path.join(specs,'.cm-specs-status');
194
+ fs.writeFileSync(status,JSON.stringify({status:'awaiting_review',revisionDigest:digest,features:[feature],
195
+ specFiles:buildManifest(specs),testCases:[{feature,path:`${feature}/test-cases.json`}]}));
196
+ const snapshot=fs.readFileSync(status),entry=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
197
+ const run=(...args)=>spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,'--approve',...args],{encoding:'utf8',env});
198
+ const refused=run('--standing-authorization','--expect-revision-digest',digest);
199
+ assert.equal(refused.status,1,refused.stdout+refused.stderr);
200
+ assert.equal(JSON.parse(refused.stdout).approveRefused,'standing_authorization_not_applicable');
201
+ assert.match(JSON.parse(refused.stdout).approveReason,/T-001.*需明确确认/);
202
+ assert.deepEqual(fs.readFileSync(status),snapshot);
203
+ assert.match(standingArchiveProblem(specs,archive,digest),/T-001/,'archive boundary applies the same rule');
204
+ for(const [reply,revision] of [['继续',digest],['开始','b'.repeat(64)]]){
205
+ const result=run('--approval-response',reply,'--expect-revision-digest',revision);
206
+ assert.equal(result.status,1,result.stdout+result.stderr);assert.deepEqual(fs.readFileSync(status),snapshot);
207
+ }
208
+ const accepted=run('--approval-response','开始','--expect-revision-digest',digest);
209
+ assert.equal(accepted.status,0,accepted.stdout+accepted.stderr);
210
+ assert.equal(JSON.parse(fs.readFileSync(status)).approval.response,'开始');
211
+ assert.equal(fs.readFileSync(path.join(specs,'.reviews',`prd-change-${digest}.json`),'utf8'),JSON.stringify(archive));
212
+ });
@@ -0,0 +1,93 @@
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 {standingProposalProblem,standingArchiveProblem} from '../runtime/js/autonomy.mjs';
7
+ import {buildTaskAcceptanceContract} from '../runtime/js/cm-ai/specification-material.mjs';
8
+ import {main as autonomyMain} from './cm-autonomy.mjs';
9
+
10
+ const feature='1.login',taskFile=`${feature}/tasks.md`,designFile=`${feature}/design.md`,caseFile=`${feature}/test-cases.json`;
11
+ const tasks='## 任务版本\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-10-01 | v1 | 初始任务 |\n\n## 任务列表\n\n- [x] T-001: 登录\n - 范围: `login.js`\n- [ ] T-002: 记住我\n - 范围: `remember.js`\n - 必验: 保留设备验收\n\n## 依赖关系\n- T-002 依赖 T-001\n';
12
+ const sampleCase={id:'TC-001',origin:'generated',kind:'logic',blocking:false,acIds:['AC-001'],taskIds:['T-002'],title:'记住我',preconditions:[],steps:['勾选'],expected:['记住'],cleanup:[]};
13
+ const encode=items=>JSON.stringify({schemaVersion:'1.0',feature:'login',cases:items});
14
+ function fixture(){
15
+ const before={directories:[feature],status:JSON.stringify({status:'approved',taskGrammar:3}),files:{
16
+ [`${feature}/requirements.md`]:'- [AC-001] 记住我\n - 设备: 需要\n',
17
+ [designFile]:'# 技术设计\n\n登录表单调用 API。\n',[taskFile]:tasks,[caseFile]:encode([sampleCase])}};
18
+ return {before,proposal:{changedUserCases:[],removed:[],files:{...before.files}}};
19
+ }
20
+ const contract=files=>buildTaskAcceptanceContract({texts:Object.fromEntries(Object.entries(files).map(([p,c])=>[p.split('/').at(-1),c])),taskId:'T-002',grammar:3});
21
+
22
+ test('M6 optional AC mapping cannot remove a pending task device obligation through standing approval',()=>{
23
+ for(const change of [{acIds:[]},{taskIds:['T-001']}]){
24
+ const {before,proposal}=fixture();
25
+ assert(contract(before.files).obligations.some(item=>item.evidenceType==='device'));
26
+ proposal.files[caseFile]=encode([{...sampleCase,...change}]);
27
+ assert.match(standingProposalProblem(before,proposal),/TC-001.*(?:acIds|taskIds).*需明确确认/);
28
+ }
29
+ });
30
+
31
+ test('M7 new task subclauses cannot override the acceptance contract of an older task',()=>{
32
+ const {before,proposal}=fixture();
33
+ proposal.files[taskFile]+='\n- [ ] T-003: [NEW] 辅助任务\n - T-002 的验收改为:静态检查即可,无需真机\n';
34
+ assert.match(standingProposalProblem(before,proposal),/T-002.*需明确确认/);
35
+ assert.deepEqual(contract(proposal.files),contract(before.files));
36
+ });
37
+
38
+ test('M7 version metadata cannot override the acceptance contract of an older task',()=>{
39
+ const {before,proposal}=fixture();
40
+ proposal.files[taskFile]=tasks.replace('| 2026-10-01 | v1 | 初始任务 |','| 2026-10-01 | v1 | 初始任务 |\n| 2026-11-01 | v2 | T-002 取消真机要求,改为静态检查 |');
41
+ assert.match(standingProposalProblem(before,proposal),/T-002.*需明确确认/);
42
+ assert.deepEqual(contract(proposal.files),contract(before.files));
43
+ });
44
+
45
+ test('M8 additive design detail preserves standing approval without changing earlier acceptance',()=>{
46
+ const {before,proposal}=fixture();proposal.files[designFile]+='\n记住我状态写入 storage.js。\n';
47
+ assert.equal(standingProposalProblem(before,proposal),null);
48
+ assert.deepEqual(contract(proposal.files),contract(before.files));
49
+ proposal.files[designFile]+='\n```js\nconst storageKey = \"remember\";\n```\n';
50
+ assert.equal(standingProposalProblem(before,proposal),null);
51
+ });
52
+
53
+ test('M8 a new task section heading and its dependency can be appended under standing approval',()=>{
54
+ const {before,proposal}=fixture();
55
+ proposal.files[taskFile]=tasks.replace('## 依赖关系','### 功能 2: 过期 `[NEW v2]`\n\n- [ ] T-003: [NEW] 过期处理\n - 范围: `expire.js`\n\n## 依赖关系')+'- T-003 依赖 T-002\n';
56
+ assert.equal(standingProposalProblem(before,proposal),null);
57
+ assert.deepEqual(contract(proposal.files),contract(before.files));
58
+ });
59
+
60
+ test('M8 old design-only authorization remains usable for non-acceptance design updates',()=>{
61
+ const {before,proposal}=fixture();before.files[designFile]='D';proposal.files[designFile]='D2';
62
+ assert.equal(standingProposalProblem(before,proposal),null);
63
+ });
64
+
65
+ test('G3 legacy fenced blank lines do not block an unrelated scope expansion',()=>{
66
+ for(const grammar of [1,2,3]){
67
+ const {before,proposal}=fixture();before.status=JSON.stringify({status:'approved',taskGrammar:grammar});
68
+ before.files[taskFile]=tasks+'\n## 示例\n```text\nfirst\n\nlast\n```\n';
69
+ proposal.files[taskFile]=before.files[taskFile].replace('`remember.js`','`remember.js`, `storage.js`');
70
+ assert.equal(standingProposalProblem(before,proposal),null,`grammar ${grammar}`);
71
+ }
72
+ });
73
+
74
+ test('G4 missing status precheck uses the same legacy grammar as the saved change archive',t=>{
75
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-autonomy-r1-')));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
76
+ const {before,proposal}=fixture();delete before.status;
77
+ before.files[taskFile]+='\n- [ ] T-004:historical prose\n';proposal.files[taskFile]=before.files[taskFile];
78
+ fs.mkdirSync(path.join(dir,feature));for(const [file,value] of Object.entries(before.files))fs.writeFileSync(path.join(dir,file),value);
79
+ const file=path.join(dir,'proposal.json');fs.writeFileSync(file,JSON.stringify(proposal));let output='';
80
+ const result=autonomyMain(['check-proposal','--specs-dir',dir,'--proposal',file],{stdout:{write:t=>output+=t},stderr:{write:t=>output+=t}});
81
+ assert.equal(result,1,output);assert.match(output,/无法可靠比较/);
82
+ assert.equal(standingProposalProblem(before,proposal),standingProposalProblem({...before,status:null},proposal));
83
+ const digest='a'.repeat(64);proposal.proposalDigest=digest;
84
+ assert.match(standingArchiveProblem(dir,{before:{...before,status:null},proposal,selected:[feature]},digest),/无法可靠比较/);
85
+ });
86
+
87
+ test('new headings cannot regroup an old task or replace an old dependency',()=>{
88
+ const {before,proposal}=fixture();
89
+ proposal.files[taskFile]=tasks.replace('- [ ] T-002:', '### 新分组\n- [ ] T-002:');
90
+ assert.match(standingProposalProblem(before,proposal),/需明确确认/);
91
+ proposal.files[taskFile]=tasks.replace('- T-002 依赖 T-001', '- T-002 依赖 T-003')+'- [ ] T-003: [NEW] helper\n';
92
+ assert.match(standingProposalProblem(before,proposal),/需明确确认/);
93
+ });