@aibyzero/cm-workflow 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +8 -1
  4. package/VERSION +1 -1
  5. package/docs/installation.md +1 -1
  6. package/docs/js-workflow-control.md +1 -1
  7. package/docs/proposals/spec-amendment-tiers.md +100 -0
  8. package/package.json +1 -1
  9. package/runtime/js/acceptance-language.mjs +32 -0
  10. package/runtime/js/autonomy.mjs +15 -6
  11. package/runtime/js/cm-ai/acceptance-contract.mjs +8 -3
  12. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +35 -2
  14. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  15. package/runtime/js/cm-ai/drive-core.mjs +9 -2
  16. package/runtime/js/cm-ai/durable-runner-state.mjs +8 -4
  17. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  18. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  19. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  20. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  21. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  22. package/runtime/js/cm-ai/review-package.mjs +20 -6
  23. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  24. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  25. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  26. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  27. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  28. package/runtime/js/cm-ai/task-runner.mjs +26 -9
  29. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  30. package/runtime/js/cm-prd/change.mjs +35 -4
  31. package/runtime/js/cm-prd/self-check.mjs +36 -6
  32. package/runtime/js/cm-prd/session.mjs +8 -3
  33. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  34. package/runtime/js/task-scope.mjs +4 -1
  35. package/runtime/test-contract.md +1 -0
  36. package/scripts/cm-ai-acceptance-contract.test.mjs +10 -0
  37. package/scripts/cm-ai-admission.mjs +8 -2
  38. package/scripts/cm-ai-admission.test.mjs +15 -2
  39. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  40. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  41. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  42. package/scripts/cm-ai-drive.mjs +18 -11
  43. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  44. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  45. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  46. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  47. package/scripts/cm-autonomy-review-r1.test.mjs +49 -0
  48. package/scripts/cm-check-runtime.sh +4 -1
  49. package/scripts/cm-drive-liveness.test.mjs +8 -0
  50. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  51. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  52. package/scripts/cm-journal-limit.test.mjs +69 -0
  53. package/scripts/cm-prd-completion.test.mjs +37 -0
  54. package/scripts/cm-prd-drive.mjs +1 -1
  55. package/scripts/cm-prd-host.test.mjs +1 -1
  56. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  57. package/scripts/cm-prd-self-check.test.mjs +24 -1
  58. package/scripts/cm-prd-summary.test.mjs +6 -0
  59. package/scripts/cm-review-inventory.test.mjs +5 -1
  60. package/scripts/cm-spec-amend.mjs +68 -0
  61. package/scripts/cm-spec-amend.test.mjs +510 -0
  62. package/scripts/cm-specs-status.test.mjs +6 -0
  63. package/scripts/cm-start-check.mjs +82 -2
  64. package/scripts/cm-start-check.test.mjs +64 -1
  65. package/scripts/cm-task-scope.test.mjs +3 -2
  66. package/scripts/test-journal-limit-1mib.mjs +4 -0
  67. package/scripts/validate-public-repo.py +4 -0
  68. package/skills/cm-ai/references/N1-init.md +23 -1
  69. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  70. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  71. package/skills/cm-ai/references/js-host.md +2 -1
  72. package/skills/cm-prd/references/js-change-recovery.md +1 -0
@@ -8,7 +8,7 @@ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs'
8
8
  import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
9
9
  import {captureReviewBaseline,createReviewPackage,readReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
10
10
  import * as presentation from '../runtime/js/cm-ai/review-presentation.mjs';
11
- import {digest,requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ import {digest,requestFor,JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
12
12
 
13
13
  const MiB=1024*1024,STATE_LIMIT=16*MiB,workflow='cm-fix-stages-v1';
14
14
  const copy=value=>JSON.parse(JSON.stringify(value));
@@ -120,13 +120,23 @@ test('a real CM-fix journal stores a repeated canonical review larger than one M
120
120
  assert.deepEqual(JSON.parse(fs.readFileSync(f.stateFile,'utf8')).records[prepared.seq-1],prepared);
121
121
  });
122
122
 
123
- test('ordinary large data, non-fix workflows and false workflow fingerprints retain the one MiB limit',t=>{
123
+ test('the fix workflow keeps its one MiB physical limit for data it cannot compress',t=>{
124
124
  const f=fixture(t);rejectAppend(f,'large-ordinary',{ordinary:'x'.repeat(MiB)});
125
125
  const {reviewPackage}=material(f,64);rejectAppend(f,'small-package-large-ordinary',{reviewPackage,ordinary:'x'.repeat(MiB)});
126
126
  rejectAppend(f,'arbitrary-nested-review',{arbitrary:{reviewPackage:material(f).reviewPackage}});
127
+ });
128
+
129
+ // Ordinary runs store large records as they are, up to the journal record limit
130
+ // (Wue specs8 T-001: a 1.17 MB develop checkpoint). They are never compressed or
131
+ // marked, so the fix workflow's encoding rules above do not apply to them.
132
+ test('non-fix workflows and false workflow fingerprints store large records unencoded up to the journal limit',t=>{
127
133
  for(const mode of ['cm-ai-stages-v1','cm-ai-batch-v1','wrong-fingerprint']){
128
- const other=fixture(t,{mode}),large=material(other).reviewPackage;
129
- rejectAppend(other,'large-review',{reviewPackage:large});
134
+ const other=fixture(t,{mode}),large=material(other).reviewPackage,input=entry(other,'large-review',{reviewPackage:large});
135
+ assert.ok(Buffer.byteLength(JSON.stringify(input.payload))>MiB,mode);
136
+ assert.equal(appendFits(other.store().snapshot(),input),true,mode);
137
+ const saved=other.store().append(input);assert.deepEqual(saved.records.at(-1).payload,input.payload);
138
+ assert.equal(Object.hasOwn(JSON.parse(fs.readFileSync(other.stateFile,'utf8')),'storageEncoding'),false,mode);
139
+ rejectAppend(other,'over-journal-limit',{ordinary:'x'.repeat(JOURNAL_PAYLOAD_LIMIT)});
130
140
  }
131
141
  });
132
142
 
@@ -0,0 +1,69 @@
1
+ // 存档单条上限 4 MiB(Wue specs8 T-001 的审查包约 1.17 MB,1 MiB 时装不下):
2
+ // 默认值、只许调小的测试开关、普通运行的大记录写入与读回、cm-fix 压缩标记不误打。
3
+ import test,{after} from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {spawnSync} from 'node:child_process';
9
+ import {fileURLToPath} from 'node:url';
10
+ import {JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
12
+ import {appendFits} from '../runtime/js/cm-ai/execution-store-limits.mjs';
13
+ import {packFixJournalState} from '../runtime/js/cm-ai/review-presentation.mjs';
14
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
15
+
16
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
17
+ const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-journal-limit-'));
18
+ after(()=>fs.rmSync(isolated,{recursive:true,force:true}));
19
+ const limitWith=value=>{
20
+ const env={...process.env};delete env.CM_JOURNAL_PAYLOAD_LIMIT_TEST;if(value!==undefined)env.CM_JOURNAL_PAYLOAD_LIMIT_TEST=value;
21
+ const run=spawnSync(process.execPath,['--input-type=module','-e',`import {JOURNAL_PAYLOAD_LIMIT} from ${JSON.stringify(path.join(root,'runtime/js/cm-ai/effect-contract.mjs'))};process.stdout.write(String(JOURNAL_PAYLOAD_LIMIT));`],{encoding:'utf8',env});
22
+ assert.equal(run.status,0,run.stderr);return Number(run.stdout);
23
+ };
24
+
25
+ test('默认 4 MiB;测试开关只许调小,调大与非法值忽略',()=>{
26
+ const MiB=1024*1024;
27
+ assert.equal(limitWith(undefined),4*MiB);
28
+ assert.equal(limitWith(String(MiB)),MiB);
29
+ for(const bad of [String(8*MiB),String(4*MiB),'abc','-1',String(1024),'1.5'])assert.equal(limitWith(bad),4*MiB,bad);
30
+ assert.equal(JOURNAL_PAYLOAD_LIMIT,4*MiB,'本测试进程没有设开关');
31
+ });
32
+
33
+ test('普通运行:1.2 MB 的记录写得进、读得回,不被打上 cm-fix 压缩标记',()=>{
34
+ const specsRoot=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'store-')));
35
+ const options={specsRoot,identity:{repositoryId:'size',runId:'size-run'},fingerprints:{workflow:'a'.repeat(64),config:'b'.repeat(64),inputs:'c'.repeat(64)}};
36
+ let store=openExecutionStore({...options,create:true});
37
+ const payload={s:'x'.repeat(1200*1024)};
38
+ try{
39
+ const input={id:'big',kind:'result',payload,expectedRevision:store.snapshot().revision};
40
+ assert.equal(appendFits(store.snapshot(),input),true);
41
+ store.append(input);
42
+ }finally{store.close();}
43
+ store=openExecutionStore({...options,create:false});
44
+ try{assert.deepEqual(store.snapshot().records.at(-1).payload,payload);}finally{store.close();}
45
+ const file=fs.readdirSync(path.join(specsRoot,'.reviews','.execution','size-run')).find(name=>name==='state.json');
46
+ const physical=JSON.parse(fs.readFileSync(path.join(specsRoot,'.reviews','.execution','size-run',file),'utf8'));
47
+ assert.equal(Object.hasOwn(physical,'storageEncoding'),false);
48
+ // 只读发现路径(驾驶员 status/advance 先走它)按同一上限读回,不再写死 1 MiB(Wue specs8 T-001 第 2 轮 limit_exceeded)
49
+ assert.deepEqual(readExecutionSnapshot({specsRoot,identity:{repositoryId:'size',runId:'size-run'}}).records.at(-1).payload,payload);
50
+ });
51
+
52
+ test('整份状态打包:非 cm-fix 运行的大记录不打压缩标记',()=>{
53
+ const state={version:1,identity:{repositoryId:'r',runId:'r'},fingerprints:{workflow:'a'.repeat(64)},revision:'0'.repeat(64),
54
+ records:[{version:1,seq:1,id:'init',kind:'intent',payload:{s:'x'.repeat(1100*1024)},previousDigest:null,digest:'0'.repeat(64)}]};
55
+ assert.equal(Object.hasOwn(packFixJournalState(state),'storageEncoding'),false);
56
+ });
57
+
58
+ // Wue specs8 T-001: the store accepted a 1.2 MB develop checkpoint but the runner's
59
+ // own payload builder still used json()'s 1 MiB default, failed inside the store
60
+ // operation and poisoned the run as store_failure.
61
+ test('the runner builds and bounds a record between 1 MiB and the journal limit, and refuses one above it', async () => {
62
+ const {runnerPayload,runnerPayloadV3,boundRunnerRecord}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
63
+ const big={effectId:'develop-1',blob:'x'.repeat(1200*1024)};
64
+ for(const payload of [runnerPayloadV3('effect-checkpoint',big),runnerPayload('effect-checkpoint',big,2)]){
65
+ assert.ok(Buffer.byteLength(JSON.stringify(payload))>1024*1024);
66
+ assert.doesNotThrow(()=>boundRunnerRecord({id:'runner.000002',kind:'result',payload},2));
67
+ }
68
+ assert.throws(()=>runnerPayloadV3('effect-checkpoint',{blob:'x'.repeat(JOURNAL_PAYLOAD_LIMIT)}));
69
+ });
@@ -352,3 +352,40 @@ for(const recoveryMode of ['process-loss','mode-mismatch','publication-conflict'
352
352
  assert.ok(fs.readFileSync(path.join(dir,'.reviews/prd-new-guide-split-r1.md')).equals(evidence));
353
353
  assert.equal(fs.existsSync(path.join(dir,'.reviews/prd-new-guide-split-r2.md')),false);assert.equal(calls,4);await c.close();
354
354
  });
355
+ // A feature whose four documents exceed 64 KiB could not take even a format-only
356
+ // change: every change_tasks reply had to resend requirements/design (wue 8.todo-inbox, ~94 KB).
357
+ // Omitted documents of an existing feature mean byte-identical and are restored; the limit counts what is sent.
358
+ test('change_tasks may omit unchanged documents of an existing feature; the 64 KiB limit counts only sent ones',t=>{
359
+ const dir=fixture(t),config=loadConfig({projectRoot:dir}),pad='\n'+'x'.repeat(40*1024)+'\n';
360
+ const big=docs().map(doc=>doc.path==='tasks.md'?doc:{...doc,content:doc.content+pad});
361
+ for(const doc of big)fs.writeFileSync(path.join(dir,'1.guide',doc.path),doc.content,{mode:0o600});
362
+ const contract={schemaVersion:'1.0',feature:'guide',cases:[{id:'TC-001',origin:'generated',kind:'logic',blocking:true,
363
+ acIds:['AC-001'],taskIds:['T-002'],title:'Existing case',preconditions:[],steps:['Read guide'],expected:['Guide available'],cleanup:[]}]};
364
+ fs.writeFileSync(path.join(dir,'1.guide/test-cases.json'),JSON.stringify(contract),{mode:0o600});
365
+ const before=inspectPrdChangeSnapshot(dir);
366
+ const tasks=big[2].content.replace('| 2026-09-08 | v1 | original |','| 2026-09-08 | v1 | original |\n| 2026-09-08 | v2 | format |');
367
+ const full={status:'draft',summary:'Format',removed:[],features:[{directory:'1.guide',testCasesReason:null,
368
+ documents:[...big.slice(0,2),{path:'tasks.md',content:tasks},{path:'test-cases.json',content:JSON.stringify(contract)}]}]};
369
+ assert.throws(()=>inspectPrdChangeProposal(before,full,['1.guide'],config),/limit_exceeded/);
370
+ const sent={...full,features:[{...full.features[0],documents:[{path:'tasks.md',content:tasks}]}]};
371
+ const proposal=inspectPrdChangeProposal(before,sent,['1.guide'],config);
372
+ assert.equal(proposal.files['1.guide/requirements.md'],big[0].content);
373
+ assert.equal(proposal.files['1.guide/design.md'],big[1].content);
374
+ assert.equal(proposal.files['1.guide/tasks.md'],tasks);
375
+ assert.equal(proposal.files['1.guide/test-cases.json'],JSON.stringify(contract));
376
+ // Same proposal whichever unchanged documents the reply carried.
377
+ const partial={...full,features:[{...full.features[0],documents:[big[0],{path:'tasks.md',content:tasks}]}]};
378
+ assert.equal(inspectPrdChangeProposal(before,partial,['1.guide'],config).proposalDigest,proposal.proposalDigest);
379
+ // Requirements/design are restored from the accepted parts, not the disk original, when an earlier phase changed them.
380
+ const accepted={features:[{directory:'1.guide',documents:[{path:'requirements.md',content:big[0].content.replace('| 2026-09-08 | v1 | original |','| 2026-09-08 | v1 | original |\n| 2026-09-08 | v2 | format |')},big[1]]}],removed:[]};
381
+ assert.equal(inspectPrdChangeProposal(before,sent,['1.guide'],config,{parts:accepted}).files['1.guide/requirements.md'],accepted.features[0].documents[0].content);
382
+ // A non-null testCasesReason still removes the contract: omission never resurrects it.
383
+ const dropped={...full,features:[{directory:'1.guide',testCasesReason:'no_observable_behavior',documents:[{path:'tasks.md',content:tasks}]}]};
384
+ assert.equal(inspectPrdChangeProposal(before,dropped,['1.guide'],config).files['1.guide/test-cases.json'],undefined);
385
+ // The reply as sent is still bounded at 64 KiB, and a new feature is never filled in.
386
+ const oversent={...sent,features:[{...sent.features[0],documents:[{path:'tasks.md',content:tasks+'\n'+'y'.repeat(70*1024)}]}]};
387
+ assert.throws(()=>inspectPrdChangeProposal(before,oversent,['1.guide'],config),/limit_exceeded/);
388
+ const fresh={status:'draft',summary:'New',removed:[],features:[...sent.features,{directory:'2.extra',testCasesReason:'no_observable_behavior',
389
+ documents:[{path:'tasks.md',content:'## 任务版本'+'\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-09-08 | v1 | new |\n- [ ] T-001: [NEW] Extra\n'}]}]};
390
+ assert.throws(()=>inspectPrdChangeProposal(before,fresh,['1.guide'],config),/prd_draft_triad_missing|prd_change/);
391
+ });
@@ -252,7 +252,7 @@ function validate(kind,value,ctx){
252
252
  // Same rule the host applies: a resumed operation keeps the rule it began
253
253
  // under (none recorded = rule 1); a new operation uses the one its session bound.
254
254
  const rules=ctx.operation==='resume'?ctx.state.active?.selfCheckRules??1:prdSessionVersions(ctx.state,ctx.specs).selfCheckRules;
255
- try{inspectPrdChangeProposal(inspectPrdChangeSnapshot(ctx.specs),value,ctx.state.checkpoint.change.selected,ctx.config,{rules});}
255
+ try{inspectPrdChangeProposal(inspectPrdChangeSnapshot(ctx.specs),value,ctx.state.checkpoint.change.selected,ctx.config,{rules,parts:ctx.state.checkpoint.change.parts??null});}
256
256
  catch(e){fail('generate.json 不符合变更草稿或 scope',e.code??e.message);}
257
257
  }else{
258
258
  check(value.status==='documents'&&nonempty(value.summary)&&Array.isArray(value.features)&&Array.isArray(value.removed),'generate.json');
@@ -107,7 +107,7 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
107
107
  }else if(message.requestId==='save'){
108
108
  assert.equal(message.result.status,'draft_saved');assert.equal(message.result.artifacts.length,3);
109
109
  // The save keeps its operation's rule, so later re-checks of these files use it.
110
- assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-guide-task-scope.json'),'utf8')).selfCheckRules,4);
110
+ assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-guide-task-scope.json'),'utf8')).selfCheckRules,5);
111
111
  assert.equal(fs.existsSync(path.join(dir,'.cm-specs-status')),false);
112
112
  send({requestId:'package',operation:'final_review_package',stage:'split',feature:'1.guide'});
113
113
  }else if(message.requestId==='package'){
@@ -67,7 +67,7 @@ test('the host binds both draft entries to the operation rule',()=>{
67
67
  assert.match(drive,/ctx\.state\.active\?\.selfCheckRules\?\?1:prdSessionVersions\(ctx\.state,ctx\.specs\)\.selfCheckRules/);
68
68
  assert.equal([...host.matchAll(/selfCheckRules:\(\)=>session\.selfCheckRules\(\)/g)].length,2);
69
69
  const change=fs.readFileSync(path.join(root,'runtime/js/cm-prd/change.mjs'),'utf8');
70
- assert.match(change,/inspectPrdChangeProposal\(state\.before,response,state\.selected,config,\{rules:selfCheckRules\(\)\}\)/);
70
+ assert.match(change,/inspectPrdChangeProposal\(state\.before,response,state\.selected,config,\{rules:selfCheckRules\(\),parts:state\.parts\}\)/);
71
71
  });
72
72
 
73
73
  // Design 3.7: a session binds the task grammar and self-check rule when it is created;
@@ -108,7 +108,7 @@ test('a session binding outside the known versions is refused',t=>{
108
108
  const {dir,entry}=specs(t),sessionId='prd-invalid-fixture',open=()=>openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
109
109
  created(open);
110
110
  for(const change of [state=>{delete state.taskGrammar;},state=>{state.taskGrammar=1;},state=>{state.taskGrammar=TASK_GRAMMAR+1;},
111
- state=>{state.selfCheckRules=PRD_SELF_CHECK_RULES+1;},state=>{state.selfCheckRules='3';}]){
111
+ state=>{state.selfCheckRules=7;},state=>{state.selfCheckRules='3';},state=>{state.selfCheckRules=6;}]){
112
112
  const file=stateFile(dir,sessionId),bytes=fs.readFileSync(file);edit(file,change);
113
113
  assert.throws(open,/prd_session_versions_invalid/);fs.writeFileSync(file,bytes,{mode:0o600});
114
114
  }
@@ -118,25 +118,26 @@ test('the historical rule set lists rule 3 explicitly, so raising the current ru
118
118
  for(const rules of [3,2,1,PRD_SELF_CHECK_RULES])assert.ok(PRD_SELF_CHECK_RULE_VERSIONS.includes(rules));
119
119
  assert.equal(new Set(PRD_SELF_CHECK_RULE_VERSIONS).size,PRD_SELF_CHECK_RULE_VERSIONS.length);
120
120
  const source=fs.readFileSync(path.join(root,'runtime/js/cm-prd/self-check.mjs'),'utf8');
121
- assert.match(source,/new Set\(\[PRD_SELF_CHECK_RULES,3,2,1\]\)/);
121
+ assert.match(source,/new Set\(\[PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES,4,3,2,1\]\)/);
122
122
  assert.doesNotMatch(source,/\[PRD_SELF_CHECK_RULES,2,1\]|\[1,2,PRD_SELF_CHECK_RULES\]/);
123
123
  });
124
124
 
125
- test('a new session binds grammar 3 only where the specs directory has none or grammar 3; earlier grammars keep 2/3',t=>{
125
+ test('a new session binds grammar 3 only where the specs directory has none or grammar 3; earlier grammars keep 2 with rule 6',t=>{
126
126
  const write=(dir,status)=>fs.writeFileSync(path.join(dir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[],specFiles:[],approval:{response:'开始',at:'2026-10-27T00:00:00.000Z'},...status})+'\n');
127
127
  const fresh=specs(t).dir;
128
128
  assert.deepEqual(prdSessionVersions(null,fresh),{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES});
129
129
  const g3=specs(t).dir;write(g3,{taskGrammar:3});
130
130
  assert.deepEqual(prdSessionVersions(null,g3),{taskGrammar:3,selfCheckRules:PRD_SELF_CHECK_RULES});
131
131
  const g2=specs(t).dir;write(g2,{taskGrammar:2});
132
- assert.deepEqual(prdSessionVersions(null,g2),{taskGrammar:2,selfCheckRules:3});
132
+ assert.deepEqual(prdSessionVersions(null,g2),{taskGrammar:2,selfCheckRules:6});
133
133
  const g1=specs(t).dir;write(g1,{});
134
- assert.deepEqual(prdSessionVersions(null,g1),{taskGrammar:2,selfCheckRules:3});
134
+ assert.deepEqual(prdSessionVersions(null,g1),{taskGrammar:2,selfCheckRules:6});
135
135
  const {dir,entry}=specs(t);write(dir,{taskGrammar:2});
136
136
  const session=openPrdSession({specs:dir,sessionId:'prd-g2-fixture',identity:{entry,runtime:'codex'}});
137
137
  session.checkpoint(null);
138
138
  const state=JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-sessions/prd-g2-fixture/state.json'),'utf8'));
139
- assert.deepEqual([state.taskGrammar,state.selfCheckRules],[2,3]);
139
+ assert.deepEqual([state.taskGrammar,state.selfCheckRules],[2,6]);
140
+ // A state recorded before rule 6 keeps rule 3 (no exemption) and still opens.
140
141
  });
141
142
  test('rule 4 refuses a task that waits for the session task, directly or transitively',()=>{
142
143
  const draft=deps=>({draftDigest:'d'.repeat(64),features:[{directory:'1.walk',name:'walk',documents:[
@@ -200,7 +201,7 @@ test('a sessionTasks-only re-check reports a bad, repeated or stray developer li
200
201
 
201
202
  // R1-03: re-checks of saved files (correction, disposition, summary, driver) run
202
203
  // outside the saving operation; the task-scope record carries a rule-4 save's rule.
203
- test('a save records rule 4 for the re-checks; an earlier rule or an operation without a rule keeps the old record',t=>{
204
+ test('a save records the session rule (4 or later) for the re-checks; an earlier rule or an operation without a rule keeps the old record',t=>{
204
205
  const {dir,entry}=specs(t),sessionId='prd-record-fixture',open=()=>openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
205
206
  const tasks=['- [ ] T-001: Build',' - 范围: `src/a.js`','- [ ] T-002: Walk',' - 范围: `docs/qa.md`',' - 开发: 会话',''].join('\n');
206
207
  const feature=content=>({directory:'1.walk',name:'walk',documents:[
@@ -215,8 +216,8 @@ test('a save records rule 4 for the re-checks; an earlier rule or an operation w
215
216
  let session=open();
216
217
  try{session.begin({requestId:'r1',operation:'save_draft'},null,{selfCheckRules:session.versions().selfCheckRules});}finally{session.close();}
217
218
  save();
218
- assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')),{version:1,enforced:true,exempt:[],selfCheckRules:4});
219
- assert.deepEqual(prdTaskScopeOptions(dir,'1.walk'),{scopes:{'1.walk':{exempt:[]}},sessionTasks:['1.walk']});
219
+ assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')),{version:1,enforced:true,exempt:[],selfCheckRules:PRD_SELF_CHECK_RULES});
220
+ assert.deepEqual(prdTaskScopeOptions(dir,'1.walk'),{scopes:{'1.walk':{exempt:[]}},sessionTasks:['1.walk'],inapplicableAcceptance:['1.walk']});
220
221
  assert.deepEqual(recheck(tasks),[]);
221
222
  assert.deepEqual(recheck(moved),['session_task_not_final']);
222
223
  assert.deepEqual(recheck(second),['session_task_multiple']);
@@ -232,8 +233,19 @@ test('a save records rule 4 for the re-checks; an earlier rule or an operation w
232
233
  // Rule 3 adds nothing beyond the scope record, so its save keeps the old bytes too.
233
234
  recordPrdTaskScopes(dir,[feature(tasks)],{},{selfCheckRules:3});
234
235
  assert.equal(fs.readFileSync(record,'utf8'),JSON.stringify({version:1,enforced:true,exempt:[]})+'\n');
235
- for(const value of [3,5,'4']){
236
+ for(const value of [3,7,'4']){
236
237
  fs.writeFileSync(record,JSON.stringify({version:1,enforced:true,exempt:[],selfCheckRules:value})+'\n',{mode:0o600});
237
238
  assert.throws(()=>prdTaskScopeOptions(dir,'1.walk'),/prd_task_scope_record_invalid/);
238
239
  }
239
240
  });
241
+ // Rule 6 is rule 3 plus the NOT_APPLICABLE exemption only: a `开发:` line stays prose, exactly as under rule 3
242
+ // (Codex review a9babbb, minor: a rule-6 grammar-3 reading would otherwise pass every other test).
243
+ test('rule 6 keeps 开发 lines as prose and otherwise reports exactly what rule 3 reports',()=>{
244
+ const docs=tasks=>({draftDigest:'e'.repeat(64),features:[{directory:'1.walk',name:'walk',documents:[
245
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Walk\n- [ ] [AC-001] Walk it.'},{path:'design.md',content:'## 方案摘要\nx'},{path:'tasks.md',content:tasks}]}]});
246
+ const misplaced=['- [ ] T-001: Build',' - 范围: `src/a.js`',' - 开发: 会话','- [ ] T-002: Walk',' - 范围: `docs/qa.md`',''].join('\n');
247
+ const codes=rules=>checkPrdDraftMechanics(docs(misplaced),{rules}).findings.map(item=>item.code).sort();
248
+ assert.deepEqual(codes(6),codes(3));
249
+ assert.ok(!codes(6).includes('session_task_not_final'));
250
+ assert.ok(codes(5).includes('session_task_not_final'));
251
+ });
@@ -75,7 +75,7 @@ test('an ordinary draft gets the same report under both rules; records match onl
75
75
  assert.ok(matchesPrdDraftMechanics(odd,legacy));
76
76
  assert.ok(matchesPrdDraftMechanics(odd,checkPrdDraftMechanics(odd,R2)));
77
77
  assert.ok(!matchesPrdDraftMechanics(odd,{...legacy,status:'failed'}));
78
- assert.throws(()=>checkPrdDraftMechanics(odd,{rules:5}),{code:'prd_self_check_rules_invalid'});
78
+ assert.throws(()=>checkPrdDraftMechanics(odd,{rules:7}),{code:'prd_self_check_rules_invalid'});
79
79
  });
80
80
  test('a self-check revision recorded under rule 1 still verifies after rule 2',()=>{
81
81
  const sha=value=>createHash('sha256').update(value).digest('hex');
@@ -127,3 +127,26 @@ test('a rule-3 report recorded with the earlier missing-scope hint still matches
127
127
  const forged={...current,findings:current.findings.map(item=>({...item,reason:{...item.reason,expected:'other'}}))};
128
128
  assert.equal(matchesPrdDraftMechanics(missing,forged),false);
129
129
  });
130
+ // An acceptance item marked NOT_APPLICABLE right after its id has no executable expectation, so from
131
+ // rule 5 it needs no case. Rules 1-4 keep their exact old reports; a passing mention, a marker inside a
132
+ // strict fence, or another plain declaration of the same id still requires coverage (Wue specs8 AC-012).
133
+ test('rule 5: an acceptance item marked NOT_APPLICABLE after its id needs no covering case',()=>{
134
+ const withRequirements=content=>{const value=draft();value.features[0].documents[0]={path:'requirements.md',content};return value;};
135
+ const codes=(content,options={rules:PRD_SELF_CHECK_RULES})=>checkPrdDraftMechanics(withRequirements(content),options).findings.map(x=>x.code);
136
+ const base='- [ ] [AC-001] Behavior works.\n';
137
+ for(const line of ['- [ ] [AC-002] NOT_APPLICABLE:本期不做(依据)','- [ ] [AC-002]: NOT_APPLICABLE','- AC-002 NOT_APPLICABLE'])
138
+ assert.ok(!codes(base+line).includes('acceptance_test_coverage_missing'),line);
139
+ for(const line of ['- [ ] [AC-002] Later work, not NOT_APPLICABLE','- [ ] [AC-002] NOT_APPLICABLEX','- [ ] [AC-002] Real behavior',
140
+ '- [ ] [AC-002] Real behavior\n- [ ] [AC-002] NOT_APPLICABLE:冲突声明',
141
+ '- [ ] [AC-002] Actual behavior must work.\n```md\n```not-a-closing-fence\n- [ ] [AC-002] NOT_APPLICABLE:仅为围栏中的示例\n```',
142
+ // Strict fences alone (no plain AC-002 to fall back on): a marker still inside a fence is no declaration.
143
+ '```md\n```not-a-closing-fence\n- [ ] [AC-002] NOT_APPLICABLE:仅为围栏中的示例\n```',
144
+ '```md\n```\u00a0\n- [ ] [AC-002] NOT_APPLICABLE:仅为围栏中的示例\n```'])
145
+ assert.ok(codes(base+line).includes('acceptance_test_coverage_missing'),line);
146
+ for(const rules of [1,2,3,4])assert.ok(codes(base+'- [ ] [AC-002] NOT_APPLICABLE:依据',{rules}).includes('acceptance_test_coverage_missing'),`rule ${rules}`);
147
+ // A saved rule-5 record carries the exemption into re-checks that pass no rule.
148
+ assert.ok(!codes(base+'- [ ] [AC-002] NOT_APPLICABLE:依据',{inapplicableAcceptance:['1.sample']}).includes('acceptance_test_coverage_missing'));
149
+ const referencing=structuredClone(contract);referencing.cases[0].acIds=['AC-001','AC-002'];
150
+ const value=draft(undefined,referencing);value.features[0].documents[0].content=base+'- [ ] [AC-002] NOT_APPLICABLE:依据';
151
+ assert.equal(checkPrdDraftMechanics(value,{rules:PRD_SELF_CHECK_RULES}).status,'mechanical_subset_passed');
152
+ });
@@ -15,6 +15,12 @@ import {approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
15
15
  import {loadConfig} from './cm-workflow-config.mjs';
16
16
  import {TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
17
17
  import {writeSpecsStatus} from '../runtime/js/specs-status.mjs';
18
+ // Spec approvals write a round ledger under CM_WORKFLOW_HOME; keep it off the real home.
19
+ if(!process.env.CM_WORKFLOW_HOME){
20
+ const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-approval-home-'));
21
+ process.env.CM_WORKFLOW_HOME=isolatedHome;
22
+ process.on('exit',()=>fs.rmSync(isolatedHome,{recursive:true,force:true}));
23
+ }
18
24
  const sha=content=>createHash('sha256').update(content).digest('hex');
19
25
  function fixture(t,{pendingCorrection=false,mandatory=false}={}){
20
26
  const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-summary-marks-')));
@@ -534,8 +534,12 @@ for(const size of [65536,65537,1024*1024+4])test(`design byte limit ${size} pres
534
534
 
535
535
  test('new specification requires bound acceptance evidence while legacy receipt eligibility is retained',t=>{
536
536
  const f=specificationFixture(t);
537
- f.writeSpec('tasks.md',fs.readFileSync(path.join(f.specsRoot,f.feature,'tasks.md'),'utf8').replace('T-001: implement','T-001: 必验: implement'));f.approve();
537
+ // Commands count only under an explicit declaration (acceptance-contract.mjs
538
+ // commandDeclaration); the shared fixture's bare verification line is prose.
539
+ f.writeSpec('tasks.md',fs.readFileSync(path.join(f.specsRoot,f.feature,'tasks.md'),'utf8').replace('T-001: implement','T-001: 必验: implement')
540
+ .replace('- T-001: node --test priority.test.mjs','- T-001: 运行:node --test priority.test.mjs'));f.approve();
538
541
  const baseline=f.capture();
542
+ assert.deepEqual(baseline.specification.acceptanceContract.requiredCommands,[['node','--test','priority.test.mjs']]);
539
543
  const legacyBaseline=captureReviewBaseline({root:f.code,identity,scope:['code.js'],requirements:['requirements.md']});
540
544
  write(f.code,'code.js','after');
541
545
  const contract=baseline.specification.acceptanceContract;
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ // Tiered re-approval of in-flight spec corrections; see runtime/js/cm-ai/spec-amendment.mjs.
3
+ // inspect 只读:给出 0/1/2 级与原因
4
+ // prepare 1 级时把批准时与现在的规格副本、审查提示写到 --out 目录
5
+ // apply 0 级直接换绑;1 级需独立审查输出(--review-output)与审查者(--reviewer)
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {inspectSpecAmendment,publicAmendment,prepareSpecAmendment,applySpecAmendment} from '../runtime/js/cm-ai/spec-amendment.mjs';
10
+
11
+ const usage=`usage: cm-spec-amend.mjs inspect --specs-dir PATH
12
+ cm-spec-amend.mjs prepare --specs-dir PATH --out EMPTY_DIR
13
+ cm-spec-amend.mjs apply --specs-dir PATH --reason TEXT [--review-output FILE --reviewer TEXT]`;
14
+
15
+ const NEXT={
16
+ null:'规格与批准时相同,不需要换绑。',
17
+ 0:'0 级:只追加了版本记录行。运行 apply --reason 直接换绑,不需要审查,也不需要用户回复「开始」。',
18
+ 1:'1 级:执行中补正。先 prepare,把 review-prompt.md 交给另一个新上下文的审查者(不是写补正的人),保存其完整输出,再 apply --review-output --reviewer。生效后在下一条消息里告诉用户改了什么,不必等回复。',
19
+ 2:'2 级:要用户本人批准。展示改动摘要,请用户回复「开始」,再走 cm-ai-admission.mjs --approve。',
20
+ };
21
+
22
+ function parse(argv){
23
+ const [command,...rest]=argv;
24
+ if(!command||command==='--help'||command==='-h')return {help:true};
25
+ if(!['inspect','prepare','apply'].includes(command))throw new Error('unknown command');
26
+ const flags={'--specs-dir':'specsDir','--out':'outDir','--reason':'reason','--review-output':'reviewOutput','--reviewer':'reviewer'};
27
+ const allowed={inspect:['specsDir'],prepare:['specsDir','outDir'],apply:['specsDir','reason','reviewOutput','reviewer']}[command];
28
+ const result={command};
29
+ for(let index=0;index<rest.length;index++){
30
+ const key=flags[rest[index]];
31
+ if(!key||!allowed.includes(key)||index+1>=rest.length||Object.hasOwn(result,key))throw new Error('invalid arguments');
32
+ result[key]=rest[++index];
33
+ }
34
+ if(!result.specsDir)throw new Error('--specs-dir is required');
35
+ if(command==='prepare'&&!result.outDir)throw new Error('--out is required');
36
+ if(command==='apply'&&!result.reason)throw new Error('--reason is required');
37
+ return result;
38
+ }
39
+
40
+ export function main(argv=process.argv.slice(2),{stdout=process.stdout,stderr=process.stderr}={}){
41
+ let input;
42
+ try{input=parse(argv);}catch(error){stderr.write(`${usage}\nERROR: ${error.message}\n`);return 2;}
43
+ if(input.help){stdout.write(`${usage}\n`);return 0;}
44
+ const specsDir=path.resolve(input.specsDir);
45
+ try{
46
+ if(input.command==='inspect'){
47
+ const result=publicAmendment(inspectSpecAmendment(specsDir));
48
+ stdout.write(`${JSON.stringify({...result,next:NEXT[result.tier]})}\n`);return 0;
49
+ }
50
+ if(input.command==='prepare'){
51
+ const result=prepareSpecAmendment(specsDir,{outDir:input.outDir});
52
+ stdout.write(`${JSON.stringify({...result,next:NEXT[result.tier]})}\n`);return result.tier===1?0:1;
53
+ }
54
+ let reviewOutput;
55
+ if(input.reviewOutput!==undefined)reviewOutput=fs.readFileSync(path.resolve(input.reviewOutput),'utf8');
56
+ const result=applySpecAmendment(specsDir,{reason:input.reason,reviewOutput,reviewer:input.reviewer});
57
+ stdout.write(`${JSON.stringify({...result,...(result.applied?{}:{next:NEXT[result.tier]})})}\n`);
58
+ return result.applied?0:1;
59
+ }catch(error){
60
+ stderr.write(`${JSON.stringify({error:{code:error.code??error.message}})}\n`);return 1;
61
+ }
62
+ }
63
+
64
+ function isMain(entry){
65
+ if(!entry)return false;
66
+ try{return fs.realpathSync(entry)===fileURLToPath(import.meta.url);}catch{return path.resolve(entry)===fileURLToPath(import.meta.url);}
67
+ }
68
+ if(isMain(process.argv[1]))process.exitCode=main();