@aibyzero/cm-workflow 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +38 -0
  4. package/README.md +15 -1
  5. package/VERSION +1 -1
  6. package/docs/architecture.md +3 -0
  7. package/docs/cm-acceptance-completion.md +185 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +1 -1
  10. package/docs/proposals/spec-amendment-tiers.md +100 -0
  11. package/package.json +1 -1
  12. package/runtime/js/acceptance-language.mjs +32 -0
  13. package/runtime/js/autonomy.mjs +168 -3
  14. package/runtime/js/check-coverage.mjs +130 -0
  15. package/runtime/js/cm-ai/acceptance-contract.mjs +257 -0
  16. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +49 -8
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  21. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  22. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  24. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  25. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  27. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  28. package/runtime/js/cm-ai/drive-core.mjs +15 -4
  29. package/runtime/js/cm-ai/durable-runner-state.mjs +10 -6
  30. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  32. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  33. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  34. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  35. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  36. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  37. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  38. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  39. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  40. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  41. package/runtime/js/cm-ai/review-package.mjs +22 -8
  42. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  43. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  44. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  45. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  46. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  47. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  48. package/runtime/js/cm-ai/task-runner.mjs +64 -22
  49. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  50. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  51. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  52. package/runtime/js/cm-prd/change.mjs +52 -5
  53. package/runtime/js/cm-prd/self-check.mjs +36 -6
  54. package/runtime/js/cm-prd/session.mjs +8 -3
  55. package/runtime/js/cm-prd/summary.mjs +5 -0
  56. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  57. package/runtime/js/node-test-selection.mjs +38 -0
  58. package/runtime/js/run-analysis.mjs +153 -0
  59. package/runtime/js/session-boundary.mjs +17 -5
  60. package/runtime/js/session-handoff.mjs +5 -2
  61. package/runtime/js/task-scope.mjs +4 -1
  62. package/runtime/test-contract.md +1 -0
  63. package/scripts/cm-acceptance-preview.mjs +26 -0
  64. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  65. package/scripts/cm-ai-acceptance-contract.test.mjs +195 -0
  66. package/scripts/cm-ai-admission.mjs +8 -2
  67. package/scripts/cm-ai-admission.test.mjs +20 -4
  68. package/scripts/cm-ai-blockage.test.mjs +120 -0
  69. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  70. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  71. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  72. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  73. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  74. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  75. package/scripts/cm-ai-drive.mjs +18 -11
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  77. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  78. package/scripts/cm-ai-progress.test.mjs +7 -0
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  80. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  81. package/scripts/cm-ai-run.test.mjs +23 -1
  82. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  83. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  84. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  85. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  86. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  87. package/scripts/cm-autonomy-review-r1.test.mjs +142 -0
  88. package/scripts/cm-autonomy.mjs +3 -1
  89. package/scripts/cm-autonomy.test.mjs +10 -9
  90. package/scripts/cm-check-runtime.sh +5 -2
  91. package/scripts/cm-delivery-evidence.mjs +59 -0
  92. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  93. package/scripts/cm-drive-liveness.test.mjs +14 -0
  94. package/scripts/cm-driver-light-import.test.mjs +32 -0
  95. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  96. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  97. package/scripts/cm-journal-limit.test.mjs +69 -0
  98. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  99. package/scripts/cm-node-test-selection.test.mjs +108 -0
  100. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  101. package/scripts/cm-prd-completion.test.mjs +49 -0
  102. package/scripts/cm-prd-drive.mjs +1 -1
  103. package/scripts/cm-prd-host.mjs +3 -1
  104. package/scripts/cm-prd-host.test.mjs +19 -2
  105. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  106. package/scripts/cm-prd-self-check.test.mjs +24 -1
  107. package/scripts/cm-prd-summary.test.mjs +25 -4
  108. package/scripts/cm-review-inventory.test.mjs +25 -6
  109. package/scripts/cm-run-analysis.mjs +21 -0
  110. package/scripts/cm-run-analysis.test.mjs +120 -0
  111. package/scripts/cm-spec-amend.mjs +68 -0
  112. package/scripts/cm-spec-amend.test.mjs +510 -0
  113. package/scripts/cm-specs-status.test.mjs +6 -0
  114. package/scripts/cm-start-check.mjs +140 -53
  115. package/scripts/cm-start-check.test.mjs +139 -1
  116. package/scripts/cm-task-scope.test.mjs +3 -2
  117. package/scripts/cm-usage-report.py +8 -3
  118. package/scripts/cm019-r1-contract.test.mjs +137 -0
  119. package/scripts/cm019-review-gates.test.mjs +97 -0
  120. package/scripts/test-journal-limit-1mib.mjs +4 -0
  121. package/scripts/validate-public-repo.py +4 -0
  122. package/skills/cm-ai/references/N1-init.md +23 -1
  123. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  124. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  125. package/skills/cm-ai/references/js-host.md +7 -2
  126. package/skills/cm-prd/references/js-change-recovery.md +2 -1
  127. package/skills/cm-prd/references/js-host.md +1 -0
@@ -0,0 +1,154 @@
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 {buildManifest} from './cm-spec-manifest.mjs';
7
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
8
+ import {completionSummary,completionLines,taskCompletion} from '../runtime/js/cm-ai/completion-summary.mjs';
9
+ import {cmAiSessionBoundary} from '../runtime/js/session-boundary.mjs';
10
+ import {handoffText} from '../runtime/js/session-handoff.mjs';
11
+
12
+ const identity={repositoryId:'completion-fixture',runId:'current',taskId:'T-001',attempt:1},packageDigest='a'.repeat(64);
13
+ function project(t){
14
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-completion-')));
15
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
16
+ for(const [feature,tasks] of [['1.first','- [x] T-001: done\n- [ ] T-002: open\n'],['2.next','- [ ] T-003: open\n']]){
17
+ fs.mkdirSync(path.join(root,feature));
18
+ for(const [name,body] of [['tasks.md',tasks],['requirements.md','# R\n'],['design.md','# D\n']])
19
+ fs.writeFileSync(path.join(root,feature,name),body);
20
+ }
21
+ const approve=()=>fs.writeFileSync(path.join(root,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.first','2.next'],
22
+ taskGrammar:2,specFiles:buildManifest(root)}));
23
+ approve();
24
+ const receipt={kind:'cm-review-receipt',identity,packageDigest,result:{verdict:'approved'}};
25
+ const source={identity,packageDigest,state:'fixture_completed',code:null,receipt:{...receipt,receiptDigest:digest(receipt)}};
26
+ const result={workflow:'cm-ai',...source,completion:{task:taskCompletion(source)}};
27
+ const log=path.join(root,'运行日志.jsonl');
28
+ const qa=(status,more={})=>({schema_version:1,workflow:'cm-ai',event:'qa',node:'N6',event_id:'qa-event',feature:'1.first',
29
+ repository_id:identity.repositoryId,run_id:identity.runId,task:identity.taskId,attempt:1,package_digest:packageDigest,
30
+ decision_id:'qa-current',status,reason:'feature_complete',score:null,at:'2026-11-01T00:00:00Z',...more});
31
+ const writeRows=rows=>fs.writeFileSync(log,rows.map(row=>JSON.stringify(row)+'\n').join(''));
32
+ const summary=()=>completionSummary({specsDir:root,feature:'1.first',result});
33
+ return {root,approve,source,result,log,qa,writeRows,summary};
34
+ }
35
+
36
+ test('a reported task completion without durable owner evidence cannot complete its feature or project',t=>{
37
+ const p=project(t);fs.writeFileSync(path.join(p.root,'.cm-status.json'),JSON.stringify({state:'run_done'}));
38
+ const value=p.summary();
39
+ assert.equal(taskCompletion(p.source).status,'completed');
40
+ assert.equal(value.task.status,'unknown');assert.equal(value.task.historicalCompleted,true);assert.equal(value.task.review.status,'passed');
41
+ assert.deepEqual(value.project.scope,['1.first','2.next']);assert.equal(value.project.pendingTasks,2);
42
+ assert.equal(value.feature.tasks.completed,1);assert.equal(value.feature.tasks.total,2);
43
+ assert.equal(value.feature.status,'unknown');assert.equal(value.feature.qa.status,'unknown');
44
+ assert.equal(value.project.status,'unknown');assert.equal(value.run.status,'unknown');
45
+ assert.equal(value.productAcceptance.status,'unknown');assert.equal(value.deployment.status,'unknown');
46
+ });
47
+
48
+ for(const [decision,expected] of [['skipped','skipped'],['blocked','blocked'],['triggered','unknown']]){
49
+ test(`terminal task list keeps QA ${decision} distinct from PASS`,t=>{
50
+ const p=project(t);fs.writeFileSync(path.join(p.root,'1.first','tasks.md'),'- [x] T-001: done\n');p.approve();
51
+ p.writeRows([p.qa(decision)]);const value=p.summary();
52
+ assert.equal(value.feature.qa.status,expected);assert.notEqual(value.feature.status,'passed');
53
+ assert.notEqual(value.project.status,'completed');
54
+ if(decision==='skipped')assert.equal(value.feature.qa.reason,'terminal_feature_qa_required');
55
+ });
56
+ }
57
+
58
+ test('a row claiming old QA PASS is not accepted without the strict owner evidence, and a different current candidate is blocked',t=>{
59
+ const p=project(t);p.writeRows([p.qa('triggered'),{...p.qa('triggered'),event:'test_run',phase:'start',operation_id:'qa-1'},
60
+ {...p.qa('triggered'),event:'test_run',phase:'complete',operation_id:'qa-1',result:'PASS'}]);
61
+ assert.notEqual(p.summary().feature.qa.status,'passed');
62
+ p.writeRows([p.qa('triggered',{package_digest:'b'.repeat(64)})]);
63
+ const value=p.summary();assert.equal(value.feature.qa.status,'blocked');assert.equal(value.feature.qa.reason,'qa_candidate_changed');
64
+ p.writeRows([p.qa('triggered',{run_id:'older-run'})]);
65
+ const older=p.summary();assert.equal(older.feature.qa.status,'blocked');assert.equal(older.feature.qa.reason,'qa_candidate_changed');
66
+ });
67
+
68
+ test('historical task completion survives correction while current eligibility remains blocked',t=>{
69
+ const p=project(t);const source={...p.source,code:'correction_review_required'};
70
+ const value=completionSummary({specsDir:p.root,feature:'1.first',result:{...p.result,code:source.code,completion:{task:taskCompletion(source)}}});
71
+ assert.equal(value.task.historicalCompleted,true);assert.equal(value.task.status,'blocked');
72
+ assert.equal(value.task.review.status,'passed');assert.equal(value.project.status,'blocked');
73
+ assert.equal(value.feature.status,'blocked');assert.equal(value.run.status,'blocked');
74
+ });
75
+
76
+ test('a wider QA or closeout block does not undo the task completion gate',t=>{
77
+ const p=project(t),source={...p.source,code:'project_qa_not_passed'};
78
+ const value=completionSummary({specsDir:p.root,feature:'1.first',result:{...p.result,code:source.code,completion:{task:taskCompletion(source)}}});
79
+ assert.equal(taskCompletion(source).status,'completed');assert.equal(value.task.historicalCompleted,true);
80
+ assert.equal(value.task.status,'unknown','this fixture has no durable completion owner');assert.equal(value.run.status,'blocked');
81
+ assert.equal(value.project.status,'unknown');
82
+ });
83
+
84
+ test('old durable baselines are explicitly reported as unprotected and are never rewritten',t=>{
85
+ const p=project(t),directory=path.join(p.root,'.reviews','.execution',identity.runId);
86
+ fs.mkdirSync(directory,{recursive:true,mode:0o700});
87
+ const body={version:1,seq:1,id:'runner.000001',kind:'result',payload:{type:'init',baseline:{}},previousDigest:null};
88
+ const state={version:1,identity:{repositoryId:identity.repositoryId,runId:identity.runId},
89
+ fingerprints:{workflow:'1'.repeat(64),config:'2'.repeat(64),inputs:'3'.repeat(64)},records:[{...body,digest:digest(body)}]};
90
+ const file=path.join(directory,'state.json'),bytes=JSON.stringify({...state,revision:digest(state)})+'\n';
91
+ fs.writeFileSync(file,bytes,{mode:0o600});const before=fs.statSync(file).mtimeMs;
92
+ const value=p.summary();assert.equal(value.task.acceptanceProtection,'legacy_unprotected');
93
+ assert(completionLines(value)[0].includes('未受新合同保护'));
94
+ assert.equal(fs.readFileSync(file,'utf8'),bytes);assert.equal(fs.statSync(file).mtimeMs,before);
95
+ });
96
+
97
+ test('run_done proves only its recorded scope, without completing pending project tasks or proving external acceptance',t=>{
98
+ const p=project(t);p.writeRows([{schema_version:1,workflow:'cm-ai',event:'run_done',node:'N8',event_id:'done-current',
99
+ repository_id:identity.repositoryId,run_id:identity.runId,task:identity.taskId,feature:'1.first',package_digest:packageDigest,
100
+ context_digest:'c'.repeat(64),documentation_sync_id:'docs-current',scope_features:['1.first']}]);
101
+ const value=p.summary();assert.equal(value.run.historicalFinalized,true);assert.equal(value.run.status,'unknown');
102
+ assert.deepEqual(value.run.scope,['1.first']);
103
+ assert.equal(value.project.status,'unknown');assert.equal(value.project.historicalFinalized,false);
104
+ assert.equal(value.productAcceptance.status,'unknown');assert.equal(value.deployment.status,'unknown');
105
+ });
106
+
107
+ test('legacy run_done without repository binding remains historical evidence with UNKNOWN current eligibility',t=>{
108
+ const p=project(t);p.writeRows([{schema_version:1,workflow:'cm-ai',event:'run_done',node:'N8',event_id:'legacy-done',
109
+ run_id:identity.runId,task:identity.taskId,feature:'1.first',package_digest:packageDigest,
110
+ context_digest:'c'.repeat(64),documentation_sync_id:'legacy-docs'}]);
111
+ const value=p.summary();assert.equal(value.run.status,'unknown');assert.equal(value.run.historicalFinalized,true);
112
+ assert.equal(value.run.reason,'legacy_closeout_binding_unknown');assert(value.run.evidence.includes('运行日志.jsonl#legacy-done'));
113
+ });
114
+
115
+ test('missing approval or source drift stays UNKNOWN instead of synthesizing completion',t=>{
116
+ const p=project(t);fs.writeFileSync(path.join(p.root,'2.next','tasks.md'),'- [x] T-003: silently weakened\n');
117
+ const value=p.summary();assert.equal(value.project.status,'unknown');assert.equal(value.feature.status,'unknown');
118
+ fs.writeFileSync(path.join(p.root,'.cm-specs-status'),'{}');assert.equal(p.summary().project.status,'unknown');
119
+ });
120
+
121
+ test('a change during QA inspection invalidates the composed snapshot',t=>{
122
+ const p=project(t);p.writeRows([p.qa('skipped')]);
123
+ const original=fs.existsSync;let changed=false;
124
+ fs.existsSync=function(file){
125
+ if(file===p.log&&!changed){changed=true;fs.appendFileSync(path.join(p.root,'1.first','tasks.md'),'- [ ] T-004: new\n');}
126
+ return original.apply(this,arguments);
127
+ };
128
+ let value;try{value=p.summary();}finally{fs.existsSync=original;}
129
+ assert(changed);assert.equal(value.project.status,'unknown');assert.equal(value.feature.status,'unknown');
130
+ });
131
+
132
+ test('summary reads write no files; the same structured result supplies boundary and handoff text',t=>{
133
+ const p=project(t),snapshot=()=>{
134
+ const files=[...fs.readdirSync(p.root,{recursive:true})].filter(name=>fs.statSync(path.join(p.root,name)).isFile()).sort();
135
+ return files.map(name=>{const file=path.join(p.root,name);return [name,fs.readFileSync(file,'utf8'),fs.statSync(file).mtimeMs];});
136
+ };
137
+ const before=snapshot(),completion=p.summary();assert.deepEqual(snapshot(),before);
138
+ const boundary=cmAiSessionBoundary({workflow:'cm-ai',state:'run_done',completion},{specsDir:p.root,feature:'1.first'});
139
+ const handoff=handoffText({workflow:'cm-ai',at:'2026-11-01T00:00:00Z',runId:'current',done:[],todo:[],next:'next',completion});
140
+ for(const line of completionLines(completion)){assert(boundary.includes(line));assert(handoff.includes(line));}
141
+ assert.deepEqual(snapshot(),before,'formatting without an explicit handoff writer stays read-only');
142
+ });
143
+
144
+ test('R1 G7 admission without a current identity leaves prior QA unknown rather than candidate-blocked',t=>{
145
+ const p=project(t);p.writeRows([p.qa('triggered')]);
146
+ const value=completionSummary({specsDir:p.root,feature:'1.first',result:{state:'blocked',code:'specs_unapproved'}});
147
+ assert.equal(value.feature.qa.status,'unknown');assert.equal(value.feature.qa.reason,'current_candidate_unavailable');
148
+ });
149
+
150
+ test('R1 G10 completion refuses oversized logs before scanning them',t=>{
151
+ const p=project(t),row=JSON.stringify({workflow:'other',padding:'x'.repeat(2048)})+'\n';
152
+ fs.writeFileSync(p.log,row.repeat(Math.ceil(33*1024*1024/Buffer.byteLength(row))));
153
+ const value=p.summary();assert.equal(value.project.status,'unknown');assert.equal(value.project.reason,'completion_log_invalid');
154
+ });
@@ -115,7 +115,9 @@ test('context_refresh requires a completed task and returns its bound context su
115
115
  assert.equal((await f.entry().handle(request)).code,'context_not_ready');
116
116
  f.complete();f.seedQa();
117
117
  const result=await f.entry().handle(request);
118
- assert.deepEqual(result,{version:1,workflow:'cm-ai',operation:'context_refresh',requestDigest:digest(request),
118
+ const {completion,...operationResult}=result;
119
+ assert.equal(completion.project.status,'unknown');assert.equal(completion.task.review.status,'unknown');
120
+ assert.deepEqual(operationResult,{version:1,workflow:'cm-ai',operation:'context_refresh',requestDigest:digest(request),
119
121
  identity,outcome:'refreshed',state:'fixture_completed',code:'context_complete',packageDigest,
120
122
  pendingAction:'finish',nextTask:null,contextDigest:result.contextDigest,contextFiles:result.contextFiles});
121
123
  assert.match(result.contextDigest,/^[a-f0-9]{64}$/);
@@ -150,7 +152,11 @@ test('run_finalize requires documentation sync and returns the final outcome wit
150
152
  const documentationResult={syncId:'docs-completed',identity,packageDigest,contextDigest:refresh.contextDigest,
151
153
  status:'completed',reason:'documentation synced',at:'2026-09-04T15:20:00-07:00'};
152
154
  const result=await f.entry({documentationResult,qaLogHome:path.join(f.root,'logs')}).handle(request);
153
- assert.deepEqual(result,{version:1,workflow:'cm-ai',operation:'run_finalize',requestDigest:digest(request),
155
+ const {completion,...operationResult}=result;
156
+ assert.equal(completion.task.status,'unknown','a synthetic runner without a registered receipt does not prove task acceptance');
157
+ assert.equal(completion.project.status,'unknown','a legacy approval without a manifest does not prove project completion');
158
+ assert.equal(completion.productAcceptance.status,'unknown');assert.equal(completion.deployment.status,'unknown');
159
+ assert.deepEqual(operationResult,{version:1,workflow:'cm-ai',operation:'run_finalize',requestDigest:digest(request),
154
160
  identity,outcome:'finalized',state:'run_done',code:'run_done',packageDigest,pendingAction:'none',
155
161
  contextDigest:refresh.contextDigest,deduplicated:false,degraded:false});
156
162
  assert.equal(f.effects(),0);
@@ -1,6 +1,7 @@
1
1
  // Develop answers and driver gaps found in the pre-release audit. Every test here
2
2
  // drives the real driver/host processes; none needs the Codex sandbox, so CI runs them.
3
3
  // Protected-mode flows that do reach the sandbox live in cm-ai-host.test.mjs.
4
+ import './test-journal-limit-1mib.mjs'; // 第一条 import:这些边界场景按 1 MiB 记录上限构造
4
5
  import test,{after} from 'node:test';
5
6
  import assert from 'node:assert/strict';
6
7
  import fs from 'node:fs';
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {packageMaterialEligible,checkpointPackageBudget} from '../runtime/js/cm-ai/checkpoint-package-material.mjs';
2
+ import {packageMaterialEligible,checkpointPackageBudget,INLINE_PACKAGE_LIMIT} from '../runtime/js/cm-ai/checkpoint-package-material.mjs';
3
3
  // cm-ai host 的单步驾驶员。PLAN 路径相对 PLAN 文件;命令仅在 codeProject 内执行。
4
4
  // 请求表来自 host-session.mjs operationNames(传输允许集)、host-conversation-execution.mjs
5
5
  // developer/check/verificationGate、host-workflow-capabilities.mjs QA/文档接线、
@@ -257,9 +257,10 @@ function diskScopeEntry(codeProject,target){
257
257
  sha256:stat.size<=REVIEW_MATERIAL_LIMITS.file?sha256(fs.readFileSync(file)):null};
258
258
  }
259
259
  const kib=bytes=>`${bytes} 字节`;
260
- // Everything the runner would refuse only after the answer is written and the
260
+ // Most of what the runner would refuse only after the answer is written and the
261
261
  // checks have run is refused here instead, with the path and the limit. The
262
- // runner stays the authority; this is the same rule applied earlier.
262
+ // runner stays the authority: the reviewer's input limit, for one, is checked
263
+ // only by the runner, on the exact review prompt.
263
264
  // What the next develop starts from, read the way the runner will read it: the
264
265
  // baseline (the one the host is about to capture for a new run, or the run's own
265
266
  // journaled one), the material the review package snapshot selects from the
@@ -441,14 +442,15 @@ export function preflightDevelopDeliveries({deliveries,answersRoot,codeProject,s
441
442
  +FRAME_ALLOWANCE+CHECK_EVIDENCE_ALLOWANCE*checks.length;
442
443
  const reserve=developCheckpointReserve({examinedPathsBytes:size(reviewPaths(pkg)),receiptsBytes:preview.receiptsBytes,
443
444
  callsBytes:preview.callsBytes+1024,writebackBytes:1024});
444
- const budget=JOURNAL_PAYLOAD_LIMIT-reserve;
445
445
  const enabled=preview.packageMaterialEnabled===true;
446
- const capacity=enabled?checkpointPackageBudget({inlineBytes:bytes,packageBytes,reserve,enabled,
447
- referenced:preview.archivedPackageDigests.includes(pkg.packageDigest)}):{fits:bytes<=budget};
446
+ // Same budget as the runner (checkpointPackageBudget), archive or not.
447
+ const capacity=checkpointPackageBudget({inlineBytes:bytes,packageBytes,reserve,enabled,
448
+ referenced:enabled&&preview.archivedPackageDigests.includes(pkg.packageDigest)});
449
+ const budget=capacity.budget;
448
450
  if(!capacity.fits){
449
451
  const largest=pkg.changes.filter(change=>change.after).map(change=>change.after).sort((a,b)=>b.size-a.size).slice(0,3)
450
452
  .map(file=>`${file.path} ${kib(file.size)}`).join(',');
451
- stop(2,`${label}: 交付后的开发检查点约 ${kib(bytes)}(其中审查包 ${kib(packageBytes)},含 handoff),超过运行存档单条记录上限 ${JOURNAL_PAYLOAD_LIMIT} `
453
+ stop(2,`${label}: 交付后的开发检查点约 ${kib(bytes)}(其中审查包 ${kib(packageBytes)},含 handoff),超过${enabled?`运行存档单条记录上限 ${JOURNAL_PAYLOAD_LIMIT}`:`未归档审查包的内联上限 ${Math.min(JOURNAL_PAYLOAD_LIMIT,INLINE_PACKAGE_LIMIT)}`} `
452
454
  +`减去为有界审查与完成记录预留的 ${reserve}(即 ${budget});最大的改动文件是 ${largest};请缩小这些文件或移出 scope`);
453
455
  }
454
456
  }
@@ -817,11 +819,16 @@ function load(){
817
819
  preview:developPreview({definition,journal:plan.mode==='create'?null:journal,controlPolicy:control?.policy??null,
818
820
  exact:!permissions.includes('--bootstrap-config')})});
819
821
  const unique=[...new Set(asks.filter(kind=>FILES[kind]&&kind!=='develop'))];
822
+ // A rediagnosis is a new conclusion; never reuse the first diagnosis file (same as cm-fix-drive).
823
+ const answerFile=kind=>answerPath(answers??'',operation==='fix_action'&&plan.fixOperation==='rediagnose'&&kind==='fix_diagnose'
824
+ ?'diagnosis-rediagnosis.json':FILES[kind]);
825
+ // Report every missing answer at once: stopping at the first one made each
826
+ // advance reveal a single file (Wue specs8 T-001: qa-assess, then
827
+ // documentation-inspect, one stopped advance each).
828
+ const missingAnswers=unique.filter(kind=>!answers||!fs.existsSync(answerFile(kind)));
829
+ if(missingAnswers.length)stop(2,missingAnswers.map(kind=>`步骤 ${operation} 会反问 ${kind},但答案文件不存在: ${answerFile(kind)}`).join(';'));
820
830
  const answer=preflightAnswers(unique,kind=>{
821
- // A rediagnosis is a new conclusion; never reuse the first diagnosis file (same as cm-fix-drive).
822
- const file=answerPath(answers??'',operation==='fix_action'&&plan.fixOperation==='rediagnose'&&kind==='fix_diagnose'
823
- ?'diagnosis-rediagnosis.json':FILES[kind]);
824
- if(!answers||!fs.existsSync(file))stop(2,`步骤 ${operation} 会反问 ${kind},但答案文件不存在: ${file}`);
831
+ const file=answerFile(kind);
825
832
  const value=readJson(file,kind);validateCmAiAnswer(kind,value,answers);return value;
826
833
  });
827
834
  if(answer.documentation_sync)for(const target of Object.keys(answer.documentation_sync.edits))
@@ -14,7 +14,7 @@ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
14
14
  import {qaFixIdentity} from '../runtime/js/cm-fix/qa-source.mjs';
15
15
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
16
16
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
17
- import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
17
+ import {digest,JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
18
18
  import {readProjectInstructionContext} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
19
19
  import {attemptBaseline,readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
20
20
  import {validateAcceptedFix} from '../runtime/js/cm-ai/accepted-fix.mjs';
@@ -371,7 +371,7 @@ test('#18 the accepted-fix size check mirrors the store exactly: a record one by
371
371
  let store=openExecutionStore({...options,create:true});
372
372
  try{
373
373
  const input=(id,n)=>({id,kind:'result',payload:{s:'x'.repeat(n)},expectedRevision:store.snapshot().revision});
374
- const limit=1024*1024-Buffer.byteLength(JSON.stringify({s:''}));
374
+ const limit=JOURNAL_PAYLOAD_LIMIT-Buffer.byteLength(JSON.stringify({s:''}));
375
375
  assert.equal(appendFits(store.snapshot(),input('fits',limit)),true);
376
376
  store.append(input('fits',limit));
377
377
  assert.equal(appendFits(store.snapshot(),input('over',limit+1)),false);
@@ -0,0 +1,102 @@
1
+ // AI潮 specs7 (2026-11-03): every feature numbers its tasks from T-001, so a
2
+ // later reviewed delivery of another feature's T-005 was mistaken for a rerun of
3
+ // this run's own T-005 and dropped. The completed run then reported its shared
4
+ // files as unreviewed (correction_review_required) once QA was attached.
5
+ import test,{after} from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
11
+ import {openControlRun} from './cm-ai-run.mjs';
12
+ import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
13
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
14
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
15
+ import {completedReviewedDeliveries,sameDeliveryTask} from '../runtime/js/cm-ai/reviewed-deliveries.mjs';
16
+
17
+ const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-later-delivery-feature-'));
18
+ const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
19
+ process.env.CM_WORKFLOW_HOME=path.join(isolated,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(isolated,'logs');
20
+ after(()=>{
21
+ for(const [key,value] of Object.entries(saved)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
22
+ fs.rmSync(isolated,{recursive:true,force:true});
23
+ });
24
+ const events=(onEvent,thread)=>{
25
+ for(const event of [{event:'thread.started',provider_thread:thread},{event:'turn.started',item_type:null},
26
+ {event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},
27
+ {event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
28
+ };
29
+
30
+ test('a later reviewed delivery of another feature\'s same-numbered task is adopted; a same-feature rerun is not',async()=>{
31
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'project-')));
32
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs');fs.mkdirSync(codeProject);
33
+ for(const feature of ['1.value','2.more']){
34
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
35
+ for(const name of ['requirements','design'])fs.writeFileSync(path.join(specsDir,feature,`${name}.md`),'# Synthetic fixture');
36
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement\n');
37
+ }
38
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.value','2.more'],specFiles:buildManifest(specsDir)}));
39
+ fs.writeFileSync(path.join(codeProject,'shared.md'),'# Shared\n');
40
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'Synthetic requirements.');
41
+ fs.writeFileSync(path.join(codeProject,'existing.mjs'),'process.exit(0)');
42
+ fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
43
+ const execution=({write,qa})=>({configuration:{kind:'synthetic-feature-delivery'},timeoutMs:2000,excludedContexts:['parent-host'],
44
+ developer:{provider:'codex',requestedModel:'synthetic',contextId:'author',run:createCodexDeveloperRun({requestedModel:'synthetic',worker:async()=>{
45
+ write();return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
46
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
47
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',allowed:true,available:true,
48
+ contexts:['review-1','review-2'],run:async(request,{onEvent})=>{
49
+ events(onEvent,`synthetic-review-${request.identity.runId}`);
50
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
51
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};}}],
52
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['parent-host']},
53
+ check:createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]}),
54
+ qaLogHome:path.join(root,'logs'),qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:`qa-${binding.identity.runId}`,
55
+ identity:binding.identity,packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-11-03T01:00:00Z'})},
56
+ qaExecutor:{mode:'commands',caseCount:1,timeoutMs:1000,run:async binding=>{
57
+ const result=qa(),report=path.join(specsDir,'.reviews',`${binding.testRunId}.md`);
58
+ fs.writeFileSync(report,`Synthetic QA ${result}`);
59
+ return {result,passed:result==='PASS'?1:0,failed:result==='FAIL'?1:0,blocked:0,report};}},
60
+ applicableAgentFiles:[],documentationProvider:{timeoutMs:1000,inspect:async binding=>({
61
+ syncId:binding.syncId,identity:binding.identity,packageDigest:binding.packageDigest,contextDigest:binding.contextDigest,
62
+ status:'completed',reason:'Synthetic documentation unchanged',at:'2026-11-03T02:00:00Z'})}});
63
+ const identity={repositoryId:'fixture',runId:'feature1-T001',taskId:'T-001',attempt:1};
64
+ const definition={version:1,specsDir,codeProject,feature:'1.value',identity,scope:['shared.md'],requirements:['requirements.md']};
65
+ const parentExecution=execution({write:()=>fs.writeFileSync(path.join(codeProject,'shared.md'),'# Shared\nfeature 1\n'),qa:()=>'FAIL'});
66
+ let run=await openControlRun(definition,'create',parentExecution);
67
+ let before;
68
+ try{
69
+ assert.equal((await run.host.handle({version:1,requestId:'p',operation:'advance',identity})).code,'qa_failed');
70
+ before=await run.host.handle({version:1,requestId:'b',operation:'status',identity});
71
+ }finally{run.close();}
72
+ // Feature 2's own T-001 is reviewed later and appends to the same shared file.
73
+ const laterIdentity={repositoryId:'fixture',runId:'feature2-T001',taskId:'T-001',attempt:1};
74
+ const later=await openControlRun({version:1,specsDir,codeProject,feature:'2.more',identity:laterIdentity,
75
+ scope:['shared.md'],requirements:['requirements.md']},'create',
76
+ execution({write:()=>fs.appendFileSync(path.join(codeProject,'shared.md'),'feature 2\n'),qa:()=>'PASS'}));
77
+ try{
78
+ const done=await later.host.handle({version:1,requestId:'l',operation:'advance',identity:laterIdentity});
79
+ assert.equal(done.code,'project_qa_not_passed',JSON.stringify(done));
80
+ }finally{later.close();}
81
+
82
+ // Discovery keys a task by its feature tasks.md and task id. Unknown stays conservative.
83
+ const found=tasksPath=>completedReviewedDeliveries({specsRoot:specsDir,root:codeProject,identity,tasksPath}).map(item=>item.runId);
84
+ assert.deepEqual(found(path.join(specsDir,'1.value','tasks.md')),['feature2-T001']);
85
+ assert.deepEqual(found(path.join(specsDir,'2.more','tasks.md')),[],'a rerun of the same feature and task is never adopted');
86
+ assert.deepEqual(found(null),[],'without a feature the historical task-id exclusion holds');
87
+
88
+ run=await openControlRun(definition,'resume',parentExecution);
89
+ try{
90
+ const status=await run.host.handle({version:1,requestId:'s',operation:'status',identity});
91
+ assert.notEqual(status.code,'correction_review_required',JSON.stringify(status));
92
+ assert.deepEqual([status.state,status.code,status.pendingAction],[before.state,before.code,before.pendingAction]);
93
+ }finally{run.close();}
94
+ });
95
+
96
+ test('sameDeliveryTask compares tasks.md only when both sides record one',()=>{
97
+ const a='/specs/1.a/tasks.md',b='/specs/2.b/tasks.md';
98
+ assert.equal(sameDeliveryTask({taskId:'T-005',tasksPath:a},{taskId:'T-005',tasksPath:b}),false);
99
+ assert.equal(sameDeliveryTask({taskId:'T-005',tasksPath:a},{taskId:'T-005',tasksPath:a}),true);
100
+ assert.equal(sameDeliveryTask({taskId:'T-005',tasksPath:null},{taskId:'T-005',tasksPath:b}),true);
101
+ assert.equal(sameDeliveryTask({taskId:'T-005',tasksPath:a},{taskId:'T-006',tasksPath:a}),false);
102
+ });
@@ -11,6 +11,7 @@ import {installSyntheticReview,syntheticReviewConfig} from './cm-ai-host-fixture
11
11
  import {createConversationExecution} from './cm-ai-host.mjs';
12
12
  import {createCmAiConversationEntry} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
13
13
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
14
+ import {captureSpecificationMaterial} from '../runtime/js/cm-ai/specification-material.mjs';
14
15
 
15
16
  const driver=fileURLToPath(new URL('./cm-ai-drive.mjs',import.meta.url));
16
17
  const home=fs.mkdtempSync(path.join(os.tmpdir(),'cm-progress-home-'));
@@ -35,6 +36,9 @@ function fixture(t){
35
36
  const answers=path.join(root,'answers');fs.mkdirSync(answers);
36
37
  fs.writeFileSync(path.join(answers,'target.txt'),'export const value=42;\n');
37
38
  fs.writeFileSync(path.join(answers,'develop.json'),JSON.stringify({status:'succeeded',value:{outcome:'implemented',
39
+ ...(captureSpecificationMaterial({specsRoot:specsDir,feature,taskId:identity.taskId}).acceptanceContract?{requirements:
40
+ captureSpecificationMaterial({specsRoot:specsDir,feature,taskId:identity.taskId}).acceptanceContract.obligations
41
+ .map(item=>({...item,satisfied:true,evidence:'Synthetic progress fixture implementation and check evidence'}))}:{}),
38
42
  application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}},edits:{'target.mjs':'target.txt'}}));
39
43
  fs.writeFileSync(path.join(root,'review.json'),JSON.stringify(syntheticReviewConfig(codeProject)));
40
44
  const plan=(checks,extra={})=>{
@@ -76,6 +80,8 @@ test('failed checks project blocked and do not start later commands or independe
76
80
  assert.equal(run.status,0,run.stderr);const result=JSON.parse(run.stdout).result;
77
81
  assert.equal(result.code,'develop_checks_not_passed');assert.equal(result.pendingAction,'resume');
78
82
  assert.equal(result.guidance.recoveryOperation,'advance');assert.equal(result.guidance.authorizationGranted,false);
83
+ assert.equal(result.guidance.blockage.phase.code,'checks');assert.equal(result.guidance.blockage.detail.status,'recorded');
84
+ assert.match(result.guidance.blockage.detail.text,/broken: failed/);assert.match(run.stderr,/缺项\/原因:develop_checks_not_passed: broken: failed/);
79
85
  assert.match(f.status().detail,/开发检查未通过/);assert.match(run.stderr,/恢复原运行并发送 advance/);
80
86
  assert.equal(f.status().state,'blocked');assert.equal(f.status().code,'develop_checks_not_passed');
81
87
  assert.equal(f.status().task,identity.taskId);assert.equal(fs.existsSync(marker),false);
@@ -103,6 +109,7 @@ test('guidance survives original-run status and recovery without writing it into
103
109
  assert.equal(result.identity.attempt,1);assert.equal(result.guidance,undefined);
104
110
  const after=snapshot();assert.deepEqual(after.records.slice(0,before.records.length),before.records);
105
111
  assert.equal(JSON.stringify(after.records).includes('recoveryOperation'),false);
112
+ assert.equal(JSON.stringify(after.records).includes('"blockage"'),false);
106
113
  assert(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8').includes('- [ ] T-001'));
107
114
  assert(!f.events().some(row=>row.phase_name==='reviewing'),'start recovery preserves the development stage');
108
115
  });
@@ -17,6 +17,7 @@ import {explainReviewedDrift} from '../runtime/js/cm-ai/fix-code-association.mjs
17
17
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
18
18
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
19
19
  import {createTaskRunner} from '../runtime/js/cm-ai/task-runner.mjs';
20
+ import {completionSummary} from '../runtime/js/cm-ai/completion-summary.mjs';
20
21
 
21
22
  const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-project-qa-gate-'));
22
23
  const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
@@ -30,14 +31,14 @@ const lesson={status:'lesson_candidate',reason:null,candidates:[{classification:
30
31
  const noLesson={status:'no_new_lesson',candidates:[],reason:null};
31
32
 
32
33
  // Two approved features: 1.work/T-002 carries one blocking browser case, 2.next/T-003 is the project's last task.
33
- function project(){
34
+ function project({mandatory=false}={}){
34
35
  const root=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'project-')));
35
36
  const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs');fs.mkdirSync(codeProject);
36
37
  for(const [feature,task] of [['1.work','T-002'],['2.next','T-003']]){
37
38
  fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
38
39
  fs.writeFileSync(path.join(specsDir,feature,'design.md'),'# D\n');
39
40
  fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),feature==='1.work'?'# R\n\n- AC-001: page renders\n':'# R\n');
40
- fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),`- [ ] ${task}: fixture\n`);
41
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),`- [ ] ${task}: ${mandatory?'必验: ':''}fixture\n`);
41
42
  }
42
43
  fs.writeFileSync(path.join(specsDir,'1.work','test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',cases:[
43
44
  {id:'TC-001',origin:'generated',kind:'browser',blocking:true,acIds:['AC-001'],taskIds:['T-002'],title:'renders',
@@ -65,6 +66,8 @@ function project(){
65
66
  examinedPaths:reviewPaths(review.payload.reviewPackage),findings:result==='approved'?[]:
66
67
  [{id:'F1',severity:'P2',path:'b.mjs',message:'Again',evidence:'Synthetic'}],summary:'Synthetic review'}};}}],
67
68
  reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control']},check:createHostCheck({cwd:codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]}),
69
+ verificationGate:async request=>({satisfied:true,...(request.acceptanceContract?{items:request.acceptanceContract.obligations.map(item=>({...item,
70
+ satisfied:true,evidence:'Synthetic implementation fixture evidence; separate QA result is exercised below'}))}:{})}),
68
71
  qaLogHome:logHome,applicableAgentFiles:[],
69
72
  documentationProvider:{timeoutMs:5000,inspect:async binding=>{state.documentation++;
70
73
  return {syncId:binding.syncId,identity:binding.identity,packageDigest:binding.packageDigest,contextDigest:binding.contextDigest,
@@ -95,6 +98,41 @@ function project(){
95
98
  }
96
99
  const status=p=>JSON.parse(fs.readFileSync(path.join(p.specsDir,'.cm-status.json'),'utf8'));
97
100
 
101
+ test('completion layers keep feature PASS separate from pending project work; later QA cannot reuse an old PASS',async()=>{
102
+ const p=project();p.state.browserUp=true;
103
+ const selected={...p.first,featureSelection:{version:1,feature:'1.work'}};
104
+ const done=await p.advance(selected,p.firstExecution(),'create');
105
+ assert.equal(done.code,'context_refreshed',JSON.stringify(done));
106
+ assert.equal(done.completion.feature.status,'passed',JSON.stringify(done.completion));
107
+ assert.equal(done.completion.run.status,'pending');assert.equal(done.completion.task.status,'completed');
108
+ assert.equal(done.completion.project.status,'pending');assert.equal(done.completion.project.pendingTasks,1);
109
+ assert.equal(done.completion.project.totalFeatures,2);assert.equal(done.completion.productAcceptance.status,'unknown');
110
+ const journal=path.join(p.specsDir,'.reviews','.execution',p.first.identity.runId,'state.json');
111
+ const originalJournal=fs.readFileSync(journal,'utf8'),saved=JSON.parse(originalJournal);
112
+ const {revision,...initialOnly}=saved;initialOnly.records=saved.records.slice(0,1);
113
+ fs.writeFileSync(journal,JSON.stringify({...initialOnly,revision:digest(initialOnly)})+'\n');
114
+ const stale=completionSummary({specsDir:p.specsDir,feature:'1.work',result:done});
115
+ assert.equal(stale.task.status,'unknown');assert.equal(stale.task.historicalCompleted,true);
116
+ assert.equal(stale.task.reason,'completion_owner_changed');assert.equal(stale.feature.qa.status,'unknown');
117
+ assert.notEqual(stale.binding.runnerRevision,done.completion.binding.runnerRevision);
118
+ fs.writeFileSync(journal,originalJournal);
119
+ const design=path.join(p.specsDir,'1.work','design.md'),original=fs.readFileSync(design,'utf8');
120
+ fs.appendFileSync(design,'\nAdditional mandatory acceptance condition\n');p.reapprove();
121
+ const drift=completionSummary({specsDir:p.specsDir,feature:'1.work',result:done});
122
+ assert.equal(drift.feature.qa.status,'blocked');assert.equal(drift.feature.qa.reason,'qa_specification_changed');
123
+ assert.equal(drift.task.status,'blocked');assert.equal(drift.task.historicalCompleted,true);
124
+ fs.writeFileSync(design,original);p.reapprove();
125
+ const log=path.join(p.specsDir,'运行日志.jsonl');
126
+ const rows=fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse);
127
+ const start=rows.filter(row=>row.event==='test_run'&&row.phase==='start').at(-1);
128
+ // Adversarial newer in-flight evidence: even an illegal new round must block,
129
+ // never let a display fall back to the previous completed PASS.
130
+ fs.appendFileSync(log,JSON.stringify({...start,event_id:'later-start',operation_id:'later-qa',attempt:start.attempt+1})+'\n');
131
+ const current=completionSummary({specsDir:p.specsDir,feature:'1.work',result:done});
132
+ assert.notEqual(current.feature.qa.status,'passed');assert.notEqual(current.feature.status,'passed');
133
+ assert.equal(current.run.historicalFinalized,false);assert.notEqual(current.run.status,'finalized');
134
+ });
135
+
98
136
  test('qaChangedFiles rejects stale_qa before completion and for a mismatched digest after completion',async()=>{
99
137
  const p=project(),identity=p.first.identity;
100
138
  const terminal=(request,result)=>({version:1,invocationId:request.invocationId,
@@ -126,9 +164,11 @@ test('qaChangedFiles rejects stale_qa before completion and for a mismatched dig
126
164
  });
127
165
 
128
166
  test('#17 an earlier feature whose QA is BLOCKED keeps the project from run_done until it is recovered; #18 its recovery survives a later reviewed task',async()=>{
129
- const p=project();
167
+ const p=project({mandatory:true});
130
168
  const blocked=await p.advance(p.first,p.firstExecution(),'create');
131
169
  assert.equal(blocked.code,'qa_result_blocked');
170
+ assert.equal(blocked.completion.task.status,'completed');assert.equal(blocked.completion.task.review.status,'passed');
171
+ assert.equal(blocked.completion.feature.qa.status,'blocked');assert.equal(blocked.completion.project.pendingTasks,1);
132
172
  const admission=inspectCmAiAdmission({specsDir:p.specsDir,codeProject:p.codeProject});
133
173
  assert.equal(admission.nextTask.id,'T-003');
134
174
  assert.deepEqual(admission.warnings.filter(line=>line.includes('QA 未通过')).length,1);
@@ -160,8 +200,19 @@ test('#17 an earlier feature whose QA is BLOCKED keeps the project from run_done
160
200
  const recovered=await p.advance(p.first,p.firstExecution(),'resume',{rerunBlockedQa:true});
161
201
  assert.notEqual(recovered.code,'correction_review_required',JSON.stringify(recovered));
162
202
  assert.equal(recovered.code,'run_done',JSON.stringify(recovered));
203
+ const readyRun=await openControlRun(last,'resume',lastExecution());
204
+ try{
205
+ const ready=await readyRun.host.handle({version:1,operation:'finish',requestId:'finish-only',identity:last.identity,
206
+ packageDigest:refused.packageDigest,testRunId});
207
+ assert.equal(ready.code,'documentation_synced',JSON.stringify(ready));
208
+ assert.equal(ready.completion.run.status,'ready_to_finalize');assert.equal(ready.completion.run.historicalFinalized,false);
209
+ assert.equal(ready.completion.project.status,'ready_to_finalize');
210
+ }finally{readyRun.close();}
163
211
  const finished=await p.advance(last,lastExecution(),'resume');
164
212
  assert.equal(finished.code,'run_done',JSON.stringify(finished));
213
+ assert.equal(finished.completion.project.status,'completed',JSON.stringify(finished.completion));
214
+ assert.equal(finished.completion.run.status,'finalized');assert.equal(finished.completion.task.acceptanceProtection,'contract_v1');
215
+ assert.equal(finished.completion.productAcceptance.status,'unknown');assert.equal(finished.completion.deployment.status,'unknown');
165
216
  assert.equal(status(p).state,'run_done');
166
217
  });
167
218
 
@@ -386,7 +437,7 @@ test('#17 a feature completed outside N6 has no completion QA and blocks run_don
386
437
  test('#17 a skip is fine while tasks remain, but a terminal feature whose latest decision is a skip blocks run_done',async()=>{
387
438
  const p=project();
388
439
  const tasks=path.join(p.specsDir,'1.work','tasks.md');
389
- fs.writeFileSync(tasks,'- [ ] T-001: first\n- [ ] T-002: fixture\n');p.reapprove();
440
+ fs.writeFileSync(tasks,'- [ ] T-001: first (AC-001)\n- [ ] T-002: fixture\n');p.reapprove();
390
441
  const first=p.definition('1.work','T-001',['a.mjs']);
391
442
  const skipped=await p.advance(first,p.execution('1.work',{write:()=>fs.writeFileSync(path.join(p.codeProject,'a.mjs'),'export const a=1;\n'),
392
443
  decision:{status:'skipped',reason:'no_fixed_trigger',score:null}}),'create');