@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.
- package/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +8 -0
- package/CHANGELOG.md +38 -0
- package/README.md +15 -1
- package/VERSION +1 -1
- package/docs/architecture.md +3 -0
- package/docs/cm-acceptance-completion.md +185 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +1 -1
- package/docs/proposals/spec-amendment-tiers.md +100 -0
- package/package.json +1 -1
- package/runtime/js/acceptance-language.mjs +32 -0
- package/runtime/js/autonomy.mjs +168 -3
- package/runtime/js/check-coverage.mjs +130 -0
- package/runtime/js/cm-ai/acceptance-contract.mjs +257 -0
- package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
- package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +49 -8
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
- package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
- package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
- package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
- package/runtime/js/cm-ai/completion-summary.mjs +187 -0
- package/runtime/js/cm-ai/control-policy.mjs +3 -1
- package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
- package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
- package/runtime/js/cm-ai/drive-core.mjs +15 -4
- package/runtime/js/cm-ai/durable-runner-state.mjs +10 -6
- package/runtime/js/cm-ai/effect-contract.mjs +8 -1
- package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
- package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
- package/runtime/js/cm-ai/execution-store.mjs +7 -4
- package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
- package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
- package/runtime/js/cm-ai/host-progress.mjs +2 -1
- package/runtime/js/cm-ai/log-rows.mjs +3 -2
- package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
- package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
- package/runtime/js/cm-ai/review-package.mjs +22 -8
- package/runtime/js/cm-ai/review-presentation.mjs +12 -5
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
- package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
- package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
- package/runtime/js/cm-ai/specification-material.mjs +57 -12
- package/runtime/js/cm-ai/task-commit.mjs +4 -2
- package/runtime/js/cm-ai/task-runner.mjs +64 -22
- package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
- package/runtime/js/cm-ai/verification-auto.mjs +6 -4
- package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
- package/runtime/js/cm-prd/change.mjs +52 -5
- package/runtime/js/cm-prd/self-check.mjs +36 -6
- package/runtime/js/cm-prd/session.mjs +8 -3
- package/runtime/js/cm-prd/summary.mjs +5 -0
- package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
- package/runtime/js/node-test-selection.mjs +38 -0
- package/runtime/js/run-analysis.mjs +153 -0
- package/runtime/js/session-boundary.mjs +17 -5
- package/runtime/js/session-handoff.mjs +5 -2
- package/runtime/js/task-scope.mjs +4 -1
- package/runtime/test-contract.md +1 -0
- package/scripts/cm-acceptance-preview.mjs +26 -0
- package/scripts/cm-acceptance-preview.test.mjs +156 -0
- package/scripts/cm-ai-acceptance-contract.test.mjs +195 -0
- package/scripts/cm-ai-admission.mjs +8 -2
- package/scripts/cm-ai-admission.test.mjs +20 -4
- package/scripts/cm-ai-blockage.test.mjs +120 -0
- package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
- package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
- package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
- package/scripts/cm-ai-completion-summary.test.mjs +154 -0
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
- package/scripts/cm-ai-drive.mjs +18 -11
- package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
- package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
- package/scripts/cm-ai-progress.test.mjs +7 -0
- package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
- package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
- package/scripts/cm-ai-run.test.mjs +23 -1
- package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
- package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
- package/scripts/cm-ai-verification-auto.test.mjs +33 -8
- package/scripts/cm-ai-verification-gate.test.mjs +1 -1
- package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
- package/scripts/cm-autonomy-review-r1.test.mjs +142 -0
- package/scripts/cm-autonomy.mjs +3 -1
- package/scripts/cm-autonomy.test.mjs +10 -9
- package/scripts/cm-check-runtime.sh +5 -2
- package/scripts/cm-delivery-evidence.mjs +59 -0
- package/scripts/cm-delivery-evidence.test.mjs +177 -0
- package/scripts/cm-drive-liveness.test.mjs +14 -0
- package/scripts/cm-driver-light-import.test.mjs +32 -0
- package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
- package/scripts/cm-fix-review-storage.test.mjs +14 -4
- package/scripts/cm-journal-limit.test.mjs +69 -0
- package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
- package/scripts/cm-node-test-selection.test.mjs +108 -0
- package/scripts/cm-notify-read-drift.test.mjs +6 -3
- package/scripts/cm-prd-completion.test.mjs +49 -0
- package/scripts/cm-prd-drive.mjs +1 -1
- package/scripts/cm-prd-host.mjs +3 -1
- package/scripts/cm-prd-host.test.mjs +19 -2
- package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
- package/scripts/cm-prd-self-check.test.mjs +24 -1
- package/scripts/cm-prd-summary.test.mjs +25 -4
- package/scripts/cm-review-inventory.test.mjs +25 -6
- package/scripts/cm-run-analysis.mjs +21 -0
- package/scripts/cm-run-analysis.test.mjs +120 -0
- package/scripts/cm-spec-amend.mjs +68 -0
- package/scripts/cm-spec-amend.test.mjs +510 -0
- package/scripts/cm-specs-status.test.mjs +6 -0
- package/scripts/cm-start-check.mjs +140 -53
- package/scripts/cm-start-check.test.mjs +139 -1
- package/scripts/cm-task-scope.test.mjs +3 -2
- package/scripts/cm-usage-report.py +8 -3
- package/scripts/cm019-r1-contract.test.mjs +137 -0
- package/scripts/cm019-review-gates.test.mjs +97 -0
- package/scripts/test-journal-limit-1mib.mjs +4 -0
- package/scripts/validate-public-repo.py +4 -0
- package/skills/cm-ai/references/N1-init.md +23 -1
- package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
- package/skills/cm-ai/references/js-host-recovery.md +2 -1
- package/skills/cm-ai/references/js-host.md +7 -2
- package/skills/cm-prd/references/js-change-recovery.md +2 -1
- package/skills/cm-prd/references/js-host.md +1 -0
|
@@ -73,6 +73,18 @@ test('actual change CLI resumes unsaved phase across processes and stops at huma
|
|
|
73
73
|
c=await client(t,dir,respond,{session:runId});assert.equal((await c.request('status')).result.stage,'change_design');
|
|
74
74
|
for(const text of ['Design','Tasks','Check']){result=await c.request('advance',{text});assert.ok(result.result,JSON.stringify(result));}
|
|
75
75
|
assert.equal(result.result.stage,'change_confirmation');const proposalDigest=result.result.proposal.proposalDigest;
|
|
76
|
+
assert.equal(result.result.acceptancePreview.proposalDigest,proposalDigest);
|
|
77
|
+
assert.equal(result.result.acceptancePreview.sourceKind,'proposed_documents');
|
|
78
|
+
assert.equal(result.result.acceptancePreview.taskGrammar,1,'unpublished existing change retains legacy grammar');
|
|
79
|
+
assert.equal(result.result.acceptancePreview.approvalAuthorized,false);
|
|
80
|
+
assert.equal(result.result.acceptancePreview.executionAuthorized,false);
|
|
81
|
+
const checkpointPath=path.join(dir,'.reviews/prd-sessions',runId,'state.json'),checkpoint=fs.readFileSync(checkpointPath);
|
|
82
|
+
const sourcePath=path.join(dir,'1.guide/requirements.md'),originalSource=fs.readFileSync(sourcePath);
|
|
83
|
+
fs.appendFileSync(sourcePath,'\nExternal edit\n');
|
|
84
|
+
const stale=await c.request('status');assert.equal(stale.result.acceptancePreview.status,'stale');
|
|
85
|
+
assert.equal(stale.result.acceptancePreview.proposalDigest,proposalDigest);
|
|
86
|
+
assert.deepEqual(fs.readFileSync(checkpointPath),checkpoint,'preview status does not rewrite the session');
|
|
87
|
+
fs.writeFileSync(sourcePath,originalSource);
|
|
76
88
|
assert.equal((await c.request('save_draft')).error.code,'host_request_failed');
|
|
77
89
|
assert.ok((await c.request('decision',{proposalDigest,approved:true,allowUserCaseChanges:false})).result);
|
|
78
90
|
result=await c.request('save_draft');assert.equal(result.result.status,'awaiting_review');assert.equal(result.result.counts.preservedCompletedTasks,1);
|
|
@@ -340,3 +352,40 @@ for(const recoveryMode of ['process-loss','mode-mismatch','publication-conflict'
|
|
|
340
352
|
assert.ok(fs.readFileSync(path.join(dir,'.reviews/prd-new-guide-split-r1.md')).equals(evidence));
|
|
341
353
|
assert.equal(fs.existsSync(path.join(dir,'.reviews/prd-new-guide-split-r2.md')),false);assert.equal(calls,4);await c.close();
|
|
342
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
|
+
});
|
package/scripts/cm-prd-drive.mjs
CHANGED
|
@@ -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');
|
package/scripts/cm-prd-host.mjs
CHANGED
|
@@ -16,6 +16,7 @@ import {createPrdDispositionOwner} from '../runtime/js/cm-prd/review-disposition
|
|
|
16
16
|
import {savePrdDraft,savePrdDesign,savePrdPromotedDraft} from '../runtime/js/cm-prd/draft-save.mjs';
|
|
17
17
|
import {createPrdCorrectionOwner,inspectPrdCorrectionRecovery,resumePrdCorrection} from '../runtime/js/cm-prd/review-correction.mjs';
|
|
18
18
|
import {createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
|
|
19
|
+
import {currentAcceptancePreview} from '../runtime/js/cm-prd/acceptance-preview.mjs';
|
|
19
20
|
import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
|
|
20
21
|
import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
|
|
21
22
|
import {need,shape,json,id,digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
@@ -138,6 +139,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
138
139
|
// Repair older cancelled checkpoints without replaying their retained call.
|
|
139
140
|
if(cancelled&&!ended){reviewController.abort();session.commit(checkpoint());}
|
|
140
141
|
const status=()=>ended?{stage:'inputs_replaced',runId,replacement:ended,completionAuthorized:false}:({...change?.status()??analysis.status(),...(predecessor?{predecessor}:{}),runId,logWriteEnabled:true,reviewState,summaryState,publishedSummary,
|
|
142
|
+
...(summaryState?.acceptancePreview?{acceptancePreview:currentAcceptancePreview({specs:admission.specs,preview:summaryState.acceptancePreview})}:{}),
|
|
141
143
|
recovery:session.state.active?{request:session.state.active.request,calls:session.state.active.calls.map(({callId,requestDigest,kind,result})=>
|
|
142
144
|
({callId,requestDigest,kind,status:result===undefined?'unknown':'recorded'}))}:null});
|
|
143
145
|
const handle=async raw=>{
|
|
@@ -185,7 +187,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
185
187
|
summaryState=null;
|
|
186
188
|
try{
|
|
187
189
|
need(Array.isArray(currentFeatures)&¤tFeatures.length>0,'prd_summary_scope_unknown');
|
|
188
|
-
summaryState=await summarize(admission.specs,{currentFeatures},reviewController.signal);return summaryState;
|
|
190
|
+
summaryState=await summarize(admission.specs,{currentFeatures,taskGrammar:session.versions().taskGrammar},reviewController.signal);return summaryState;
|
|
189
191
|
}catch(cause){
|
|
190
192
|
// The shared transport redacts thrown errors. Keep this recoverable
|
|
191
193
|
// scope failure visible without changing that transport contract.
|
|
@@ -7,6 +7,7 @@ import {spawn} from 'node:child_process';
|
|
|
7
7
|
import {once} from 'node:events';
|
|
8
8
|
import {createInterface} from 'node:readline';
|
|
9
9
|
import {fileURLToPath} from 'node:url';
|
|
10
|
+
import {analyzeRunRows} from '../runtime/js/run-analysis.mjs';
|
|
10
11
|
import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
|
|
11
12
|
import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
|
|
12
13
|
const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
|
|
@@ -106,7 +107,7 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
106
107
|
}else if(message.requestId==='save'){
|
|
107
108
|
assert.equal(message.result.status,'draft_saved');assert.equal(message.result.artifacts.length,3);
|
|
108
109
|
// The save keeps its operation's rule, so later re-checks of these files use it.
|
|
109
|
-
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-guide-task-scope.json'),'utf8')).selfCheckRules,
|
|
110
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-guide-task-scope.json'),'utf8')).selfCheckRules,5);
|
|
110
111
|
assert.equal(fs.existsSync(path.join(dir,'.cm-specs-status')),false);
|
|
111
112
|
send({requestId:'package',operation:'final_review_package',stage:'split',feature:'1.guide'});
|
|
112
113
|
}else if(message.requestId==='package'){
|
|
@@ -148,6 +149,10 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
148
149
|
send({requestId:'summary',operation:'prepare_summary'});
|
|
149
150
|
}else if(message.requestId==='summary'){
|
|
150
151
|
assert.equal(message.result.status,'human_summary_prepared');assert.equal(message.result.readyForAwaitingReview,true);
|
|
152
|
+
assert.equal(message.result.acceptancePreview.taskGrammar,3);
|
|
153
|
+
assert.deepEqual(message.result.acceptancePreview.scope.features,['1.guide']);
|
|
154
|
+
assert.equal(message.result.acceptancePreview.approvalAuthorized,false);
|
|
155
|
+
assert.equal(message.result.acceptancePreview.executionAuthorized,false);
|
|
151
156
|
assert.deepEqual(message.result.currentFeatures,['1.guide']);
|
|
152
157
|
assert.match(message.result.notes.join('\n'),/历史 feature 2.history.*旧版归档/);
|
|
153
158
|
assert.equal(message.result.totals.tasks,1);assert.equal(message.result.checklist.every(item=>!item.checked),true);
|
|
@@ -166,7 +171,14 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
166
171
|
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).status,'awaiting_review');
|
|
167
172
|
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).features,['1.guide','2.history']);
|
|
168
173
|
send({requestId:'status',operation:'status'});
|
|
169
|
-
}else if(message.requestId==='status'){
|
|
174
|
+
}else if(message.requestId==='status'){
|
|
175
|
+
status=message.result;
|
|
176
|
+
if(mode==='self-check'){
|
|
177
|
+
assert.deepEqual(status.acceptancePreview,status.summaryState.acceptancePreview);
|
|
178
|
+
assert.equal(status.acceptancePreview.taskGrammar,3);
|
|
179
|
+
}
|
|
180
|
+
send({type:'host_close',sessionId});
|
|
181
|
+
}
|
|
170
182
|
}
|
|
171
183
|
assert.equal((await closed)[0],0,stderr);
|
|
172
184
|
assert.equal(status.stage,mode==='cancel'?'cancelled':mode==='draft'?'draft_ready':mode==='self-check'?'self_check_reported_passed':'analysis_ready');
|
|
@@ -175,6 +187,11 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
175
187
|
assert.equal(fs.existsSync(path.join(dir,'1.guide')),false);
|
|
176
188
|
}
|
|
177
189
|
const events=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
|
|
190
|
+
const timing=analyzeRunRows(events).timing;
|
|
191
|
+
assert(timing.pairedSegments>0,'actual PRD producer timing must be recognized');
|
|
192
|
+
assert.equal(timing.unrecognizedEvents,0);assert.equal(timing.incompleteSegments,0);
|
|
193
|
+
if(mode==='draft'){assert(timing.combinedSegments>=3);assert(timing.stages.some(x=>x.stage==='design_generation'));}
|
|
194
|
+
if(mode==='codex'||mode==='claude')assert(timing.closedForInput>=1);
|
|
178
195
|
assert.equal(events.filter(event=>event.event==='run_start').length,1);
|
|
179
196
|
const done=events.filter(event=>event.event==='run_done');assert.equal(done.length,1);
|
|
180
197
|
assert.equal(done[0].outcome,mode==='cancel'?'cancelled':'incomplete');
|
|
@@ -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=
|
|
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
|
|
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:
|
|
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:
|
|
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,
|
|
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:
|
|
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,
|
|
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:
|
|
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
|
+
});
|
|
@@ -10,13 +10,19 @@ import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
|
|
|
10
10
|
import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
|
|
11
11
|
import {recordPrdHostDisposition,createPrdDispositionOwner} from '../runtime/js/cm-prd/review-disposition.mjs';
|
|
12
12
|
import {inspectPrdSummaryEvidence,createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
|
|
13
|
-
import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange} from '../runtime/js/cm-prd/change.mjs';
|
|
13
|
+
import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange,createPrdChange} from '../runtime/js/cm-prd/change.mjs';
|
|
14
14
|
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
|
-
function fixture(t,{pendingCorrection=false}={}){
|
|
25
|
+
function fixture(t,{pendingCorrection=false,mandatory=false}={}){
|
|
20
26
|
const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-summary-marks-')));
|
|
21
27
|
t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));fs.mkdirSync(path.join(specs,'.reviews'));
|
|
22
28
|
const inputs=[];
|
|
@@ -24,7 +30,7 @@ function fixture(t,{pendingCorrection=false}={}){
|
|
|
24
30
|
const findings=pendingCorrection&&feature==='1.guide'?[{id:'R1',severity:'P2',path:`${feature}/tasks.md`,
|
|
25
31
|
message:'Clarify task split',evidence:'Synthetic finding'}]:[];
|
|
26
32
|
const documents=[{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Read guide'},
|
|
27
|
-
{path:'design.md',content:'## 方案摘要\nDocumentation'}, {path:'tasks.md',content
|
|
33
|
+
{path:'design.md',content:'## 方案摘要\nDocumentation'}, {path:'tasks.md',content:`- [ ] T-001: ${mandatory?'必验: ':''}Guide\n - 范围: \`README.md\``}];
|
|
28
34
|
const prepared=preparePrdReview({specs,stage:'split',feature,draft:{draftDigest:'a'.repeat(64),features:[{name:feature.split('.')[1],directory:feature,documents}]}});
|
|
29
35
|
claimPrdReview({...prepared.paths,package_sha256:prepared.packageDigest});
|
|
30
36
|
publishPrdReview({specs,reviewPackage:prepared.reviewPackage,packageDigest:prepared.packageDigest,authorContextId:'author',
|
|
@@ -41,7 +47,7 @@ function fixture(t,{pendingCorrection=false}={}){
|
|
|
41
47
|
return {specs,mark,inputs};
|
|
42
48
|
}
|
|
43
49
|
test('summary includes completed historical feature and exact new feature with runtime metadata',async t=>{
|
|
44
|
-
const {specs,mark}=fixture(t),before=inspectPrdSummaryEvidence(specs);mark();
|
|
50
|
+
const {specs,mark}=fixture(t,{mandatory:true}),before=inspectPrdSummaryEvidence(specs);mark();
|
|
45
51
|
const evidence=inspectPrdSummaryEvidence(specs);
|
|
46
52
|
assert.equal(evidence.features.length,2);assert.deepEqual(evidence.specFiles,before.specFiles);
|
|
47
53
|
assert.equal(evidence.features[0].reviews.split.gate.runtimeMarksNormalized,true);
|
|
@@ -56,6 +62,10 @@ test('summary includes completed historical feature and exact new feature with r
|
|
|
56
62
|
evidence:['Synthetic documentation fixture']}))})});
|
|
57
63
|
const summary=await owner(specs,new AbortController().signal);
|
|
58
64
|
assert.equal(summary.status,'human_summary_prepared');
|
|
65
|
+
assert.equal(summary.acceptancePreview.status,'needs_clarification');
|
|
66
|
+
assert.equal(summary.acceptancePreview.approvalAuthorized,false);
|
|
67
|
+
assert.equal(summary.acceptancePreview.executionAuthorized,false);
|
|
68
|
+
assert(summary.acceptancePreview.features[0].tasks[0].issues.some(issue=>issue.message.includes('no explicit task/case mapping')));
|
|
59
69
|
assert.equal(summary.readyForAwaitingReview,false);
|
|
60
70
|
assert.deepEqual(summary.blockers,['mechanical_self_check_failed']);
|
|
61
71
|
assert.deepEqual(summary.mechanicalSelfCheck.findings,[{feature:'1.guide',code:'new_task_not_pending'}]);
|
|
@@ -281,3 +291,14 @@ test('historical gate failure still rejects publication when history changes aft
|
|
|
281
291
|
fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\nAnother edit after preparation');
|
|
282
292
|
assert.throws(()=>publishPrdAwaitingReview({specs,summary,writeEnabled:true}),/prd_summary_inputs_changed/);
|
|
283
293
|
});
|
|
294
|
+
|
|
295
|
+
test('R1 G5 change preview inventory includes unchanged features outside proposal scope',t=>{
|
|
296
|
+
const {specs}=fixture(t),admission={specs,project:specs,feature:'1.guide',cases:null,skillDir:path.resolve('skills/cm-prd')};
|
|
297
|
+
const options={admission,runtime:'codex',call:()=>assert.fail('status is read-only')};
|
|
298
|
+
const original=createPrdChange(options),state=structuredClone(original.checkpoint());
|
|
299
|
+
state.stage='change_confirmation';state.proposal={proposalDigest:'a'.repeat(64),removed:[],features:[{directory:'1.guide',
|
|
300
|
+
documents:['requirements.md','design.md','tasks.md'].map(name=>({path:name,content:fs.readFileSync(path.join(specs,'1.guide',name),'utf8')}))}]};
|
|
301
|
+
const value=createPrdChange({...options,restored:state}).status();
|
|
302
|
+
assert.deepEqual(value.acceptancePreview.featureInventory,['1.guide','2.appendix']);
|
|
303
|
+
assert.deepEqual(value.acceptancePreview.scope.features,['1.guide']);
|
|
304
|
+
});
|
|
@@ -434,6 +434,8 @@ import {buildDeveloperPrompt,readDeveloperRequest} from '../runtime/js/cm-ai/dev
|
|
|
434
434
|
import {requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
435
435
|
import {reviewResult,reviewPaths,reviewReceipt} from '../runtime/js/cm-ai/review-runner.mjs';
|
|
436
436
|
import {checkCompletion} from '../runtime/js/cm-ai/gate-bridge.mjs';
|
|
437
|
+
import {encodeAcceptanceEvidence,acceptanceCoverage} from '../runtime/js/cm-ai/acceptance-contract.mjs';
|
|
438
|
+
import {createHostHandoff} from '../runtime/js/cm-ai/host-handoff.mjs';
|
|
437
439
|
|
|
438
440
|
function specificationFixture(t,{cases=true,design='export function normalizePriority(value): Priority;\n'}={}){
|
|
439
441
|
const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-specification-')));
|
|
@@ -530,22 +532,39 @@ for(const size of [65536,65537,1024*1024+4])test(`design byte limit ${size} pres
|
|
|
530
532
|
assert(design.startsWith(material.designExcerpt));
|
|
531
533
|
});
|
|
532
534
|
|
|
533
|
-
test('new specification
|
|
534
|
-
const f=specificationFixture(t)
|
|
535
|
+
test('new specification requires bound acceptance evidence while legacy receipt eligibility is retained',t=>{
|
|
536
|
+
const f=specificationFixture(t);
|
|
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();
|
|
541
|
+
const baseline=f.capture();
|
|
542
|
+
assert.deepEqual(baseline.specification.acceptanceContract.requiredCommands,[['node','--test','priority.test.mjs']]);
|
|
535
543
|
const legacyBaseline=captureReviewBaseline({root:f.code,identity,scope:['code.js'],requirements:['requirements.md']});
|
|
536
544
|
write(f.code,'code.js','after');
|
|
537
|
-
const
|
|
545
|
+
const contract=baseline.specification.acceptanceContract;
|
|
546
|
+
const acceptedChecks=contract.requiredCommands.map((command,index)=>({...checks[0],id:`declared-${index}`,
|
|
547
|
+
command:command.map((token,at)=>at===0&&token==='node'?process.execPath:token)}));
|
|
548
|
+
const incomplete=createReviewPackage({root:f.code,baseline,checks:acceptedChecks});
|
|
549
|
+
const handoffPath=path.join(f.specsRoot,'.reviews','priority-T-001-a1-handoff.json');
|
|
550
|
+
fs.mkdirSync(path.dirname(handoffPath),{recursive:true});
|
|
551
|
+
const evidence=encodeAcceptanceEvidence({contract,identity,items:contract.obligations.map(item=>({...item,satisfied:true,
|
|
552
|
+
evidence:'Synthetic fixture approval input, not a product execution'})),facts:null,coverage:acceptanceCoverage(contract,acceptedChecks)});
|
|
553
|
+
createHostHandoff({root:f.code,baseline,checks:acceptedChecks,handoffPath,evidence:[evidence]});
|
|
554
|
+
const current=createReviewPackage({root:f.code,baseline,checks:acceptedChecks,handoffPath});
|
|
538
555
|
const old=createReviewPackage({root:f.code,baseline:legacyBaseline,checks});
|
|
539
556
|
const {unchangedScope,packageDigest,...oldBody}=old,legacy={...oldBody,packageDigest:digest(oldBody)};
|
|
540
|
-
for(const pkg of [current,legacy]){
|
|
557
|
+
for(const pkg of [incomplete,current,legacy]){
|
|
541
558
|
assert.deepEqual(readReviewPackage(pkg),pkg);
|
|
542
559
|
const result=reviewResult({verdict:'approved',packageDigest:pkg.packageDigest,examinedPaths:reviewPaths(pkg),findings:[],summary:'Synthetic review'},pkg);
|
|
543
560
|
const request=requestFor({invocationId:'receipt',identity,role:'reviewer',provider:'claude',requestedModel:'fixture',contextId:'reviewer',payload:{reviewPackage:pkg,priorReview:null}});
|
|
544
561
|
const call={invocationId:request.invocationId,started:true,terminal:'succeeded',requestDigest:request.requestDigest,resultDigest:digest(result),
|
|
545
562
|
provider:'claude',contextId:'reviewer',requestedModel:'fixture',effectiveModel:'fixture',channel:'fixture'};
|
|
546
563
|
const receipt=reviewReceipt({request,call,result,reviewPackage:pkg,developerProvider:'codex',fallbackReasons:[]});
|
|
547
|
-
assert.
|
|
548
|
-
assert.equal(
|
|
564
|
+
if(pkg===incomplete)assert.throws(()=>checkCompletion({receipt,registered:receipt,execution:call,reviewPackage:pkg,identity}),{code:'verification_precheck_failed'});
|
|
565
|
+
else assert.equal(checkCompletion({receipt,registered:receipt,execution:call,reviewPackage:pkg,identity}).outcome,'eligible');
|
|
566
|
+
assert.equal(verifyReviewPackage({root:f.code,baseline:pkg===legacy?legacyBaseline:baseline,checks:pkg===legacy?checks:acceptedChecks,
|
|
567
|
+
...(pkg===current?{handoffPath}:{}),reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
|
|
549
568
|
}
|
|
550
569
|
});
|
|
551
570
|
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {inspectRunAnalysis,runAnalysisLines} from '../runtime/js/run-analysis.mjs';
|
|
5
|
+
const usage='用法: cm-run-analysis.mjs --specs DIR [--run-id ID] [--json]\n读取规格目录的运行日志;不执行工作流或修改状态。\n';
|
|
6
|
+
export function main(argv=process.argv.slice(2),{stdout=process.stdout,stderr=process.stderr}={}){
|
|
7
|
+
if(argv.length===1&&['--help','-h'].includes(argv[0])){stdout.write(usage);return 0;}
|
|
8
|
+
try{
|
|
9
|
+
const options={};
|
|
10
|
+
for(let i=0;i<argv.length;i++){
|
|
11
|
+
const name=argv[i];if(!['--specs','--run-id','--json'].includes(name)||Object.hasOwn(options,name))throw Error('run_analysis_arguments_invalid');
|
|
12
|
+
if(name==='--json')options[name]=true;
|
|
13
|
+
else{const value=argv[++i];if(!value||value.startsWith('--'))throw Error('run_analysis_arguments_invalid');options[name]=value;}
|
|
14
|
+
}
|
|
15
|
+
if(!options['--specs'])throw Error('run_analysis_arguments_invalid');
|
|
16
|
+
const report=inspectRunAnalysis({specs:path.resolve(options['--specs']),runId:options['--run-id']??null});
|
|
17
|
+
stdout.write(options['--json']?JSON.stringify(report)+'\n':runAnalysisLines(report).join('\n')+'\n');return 0;
|
|
18
|
+
}catch(error){const reason=error.code??error.message;
|
|
19
|
+
stderr.write(`运行分析不可用:${/^run_analysis_[a-z_]+$/.test(reason)?reason:'run_analysis_read_failed'}\n`);return 2;}
|
|
20
|
+
}
|
|
21
|
+
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=main();
|
|
@@ -0,0 +1,120 @@
|
|
|
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 {withHostProgress,startHostProgress} from '../runtime/js/cm-ai/host-progress.mjs';
|
|
9
|
+
import {recordCmAiQaDecision,recordCmAiQaRun} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
|
|
10
|
+
import {analyzeRunRows,inspectRunAnalysis,runAnalysisLines} from '../runtime/js/run-analysis.mjs';
|
|
11
|
+
const cli=fileURLToPath(new URL('./cm-run-analysis.mjs',import.meta.url));
|
|
12
|
+
const base={run_id:'run-1',workflow:'cm-ai',runtime:'codex',stage:'develop',role:'developer',adapter:'codex-cli',requested_model:'configured',source:'native-cli-terminal',purpose:'workflow-execution'};
|
|
13
|
+
const claim=(id,extra={})=>({...base,event:'model_call',phase:'claimed',call_id:id,...extra});
|
|
14
|
+
const usage=(id,extra={})=>({...base,event:'model_usage',phase:'complete',call_id:id,usage_state:'observed',outcome:'success',input_tokens:10,output_tokens:5,...extra});
|
|
15
|
+
const progress=(phase,time,extra={})=>({run_id:'run-1',workflow:'cm-prd',event:'progress',phase,operation_id:'prd-design',phase_name:'design_generation',segment:1,at:`2026-01-01T00:${time}Z`,...(phase==='complete'?{outcome:'completed'}:{}),...extra});
|
|
16
|
+
function fixture(t,rows){const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-analysis-')));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));fs.writeFileSync(path.join(dir,'运行日志.jsonl'),rows.map(x=>JSON.stringify(x)).join('\n')+'\n');return dir;}
|
|
17
|
+
|
|
18
|
+
test('reuses native usage identity, reasoning subset and unavailable semantics',()=>{
|
|
19
|
+
const report=analyzeRunRows([claim('a'),usage('a',{outcome:'error',cache_write_tokens:3,reasoning_tokens:4}),claim('b'),usage('b',{usage_state:'unavailable',input_tokens:undefined,output_tokens:undefined}),claim('c')]);
|
|
20
|
+
assert.equal(report.usage.status,'partial');assert.equal(report.usage.summary.observed_calls,1);
|
|
21
|
+
assert.equal(report.usage.summary.outcomes.error,1);assert.equal(report.usage.summary.unavailable_calls,1);
|
|
22
|
+
assert.equal(report.usage.summary.unresolved_claims,1);assert.equal(report.usage.summary.output_tokens,5);
|
|
23
|
+
assert.equal(report.usage.native_components.fields.reasoning_tokens.tokens,4);
|
|
24
|
+
assert.equal(report.usage.native_components.fields.cache_read_tokens.tokens,null);
|
|
25
|
+
assert.equal(report.repetitions.groups[0].count,3);
|
|
26
|
+
});
|
|
27
|
+
test('claim mismatch, missing prior claim, duplicate call and invalid reasoning are never counted',()=>{
|
|
28
|
+
const report=analyzeRunRows([usage('missing'),claim('a'),usage('a',{stage:'review'}),claim('b'),usage('b',{reasoning_tokens:6}),claim('c'),usage('c'),usage('c')]);
|
|
29
|
+
assert.equal(report.usage.summary.observed_calls,1);assert.equal(report.usage.summary.invalid_calls,4);
|
|
30
|
+
assert.equal(report.usage.summary.unresolved_claims,2);assert.equal(report.usage.status,'partial');
|
|
31
|
+
});
|
|
32
|
+
test('paired phase segments exclude waiting gaps and union combined call overlaps',()=>{
|
|
33
|
+
const rows=[progress('start','00:00'),progress('complete','00:10',{outcome:'awaiting_input'}),
|
|
34
|
+
progress('start','05:00',{segment:2,timing_scope:'combined_host_call'}),
|
|
35
|
+
progress('start','05:00',{operation_id:'prd-task',phase_name:'task_split',timing_scope:'combined_host_call'}),
|
|
36
|
+
progress('complete','05:20',{segment:2,timing_scope:'combined_host_call'}),
|
|
37
|
+
progress('complete','05:20',{operation_id:'prd-task',phase_name:'task_split',timing_scope:'combined_host_call'})];
|
|
38
|
+
const r=analyzeRunRows(rows).timing;assert.equal(r.activeIntervalUnionMs,30000);assert.equal(r.closedForInput,1);
|
|
39
|
+
assert.equal(r.combinedSegments,2);assert.equal(r.waitingMs,null);assert.equal(r.stages[0].durationMs,30000);
|
|
40
|
+
});
|
|
41
|
+
test('timing never pairs across run, workflow, operation, duplicate or inverted order',()=>{
|
|
42
|
+
const r=analyzeRunRows([progress('start','00:00'),progress('complete','00:10',{run_id:'run-2'}),
|
|
43
|
+
progress('complete','00:10',{workflow:'cm-ai'}),progress('start','00:00',{operation_id:'duplicate'}),progress('start','00:00',{operation_id:'duplicate'}),progress('complete','00:10',{operation_id:'duplicate'}),
|
|
44
|
+
progress('complete','00:10',{operation_id:'inverted'}),progress('start','00:00',{operation_id:'inverted'})]).timing;
|
|
45
|
+
assert.equal(r.pairedSegments,0);assert.equal(r.activeIntervalUnionMs,null);assert.equal(r.incompleteSegments,4);assert.equal(r.unrecognizedEvents,1);
|
|
46
|
+
});
|
|
47
|
+
test('selects original run, deduplicates exact events, rejects conflicting identity and preserves legacy unknown',()=>{
|
|
48
|
+
const a=claim('a',{event_id:'event-1'});const r=analyzeRunRows([a,a,usage('a'),claim('other',{run_id:'run-2'}),{event:'legacy'}],{runId:'run-1'});
|
|
49
|
+
assert.deepEqual(r.runs,['run-1']);assert.equal(r.deduplicatedEvents,1);assert.equal(r.ignoredHistoricalRows,1);
|
|
50
|
+
assert.equal(r.usage.summary.observed_calls,1);
|
|
51
|
+
assert.throws(()=>analyzeRunRows([a,{...a,stage:'review'}]),/log_invalid/);
|
|
52
|
+
assert.throws(()=>analyzeRunRows([a],{runId:'absent'}),/run_not_found/);
|
|
53
|
+
});
|
|
54
|
+
test('QA repetitions are unique operation starts, command execution remains unknown',()=>{
|
|
55
|
+
const start={run_id:'run-1',workflow:'cm-ai',event:'test_run',phase:'start',feature:'1.login',task:'T-001',operation_id:'qa-1'};
|
|
56
|
+
const r=analyzeRunRows([start,start,{...start,operation_id:'qa-2'}]).repetitions;
|
|
57
|
+
assert.equal(r.groups[0].count,2);assert.equal(r.commandReexecution,'unavailable');
|
|
58
|
+
});
|
|
59
|
+
test('actual CLI reads one stable log and does not modify logs or state',t=>{
|
|
60
|
+
const dir=fixture(t,[claim('a'),usage('a'),progress('start','00:00'),progress('complete','00:10')]);
|
|
61
|
+
const state=path.join(dir,'.cm-run.json');fs.writeFileSync(state,'{"run_id":"do-not-use-pointer"}');
|
|
62
|
+
const before=fs.readdirSync(dir).map(name=>[name,fs.readFileSync(path.join(dir,name)),fs.statSync(path.join(dir,name)).mtimeMs]);
|
|
63
|
+
const result=spawnSync(process.execPath,[cli,'--specs',dir,'--run-id','run-1','--json'],{encoding:'utf8'});
|
|
64
|
+
assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).usage.summary.observed_calls,1);
|
|
65
|
+
for(const [name,bytes,mtime] of before){assert.deepEqual(fs.readFileSync(path.join(dir,name)),bytes);assert.equal(fs.statSync(path.join(dir,name)).mtimeMs,mtime);}
|
|
66
|
+
assert.equal(fs.readdirSync(dir).length,before.length);
|
|
67
|
+
});
|
|
68
|
+
test('malformed, symlink and oversized authoritative logs fail closed without raw input',t=>{
|
|
69
|
+
const dir=fixture(t,[]),file=path.join(dir,'运行日志.jsonl');fs.writeFileSync(file,'SECRET-BAD-JSON');
|
|
70
|
+
let r=spawnSync(process.execPath,[cli,'--specs',dir,'--json'],{encoding:'utf8'});assert.equal(r.status,2);assert.doesNotMatch(r.stderr,/SECRET/);
|
|
71
|
+
fs.unlinkSync(file);fs.writeFileSync(path.join(dir,'other'),'{}');fs.symlinkSync('other',file);assert.throws(()=>inspectRunAnalysis({specs:dir}),/unavailable/);
|
|
72
|
+
fs.unlinkSync(file);fs.writeFileSync(file,'');fs.truncateSync(file,32*1024*1024+1);assert.throws(()=>inspectRunAnalysis({specs:dir}),/unavailable/);
|
|
73
|
+
});
|
|
74
|
+
test('missing Python is explicit unavailable and malicious labels never reach human output',()=>{
|
|
75
|
+
const old=process.env.PATH;try{process.env.PATH='';const r=analyzeRunRows([claim('a'),usage('a')]);assert.equal(r.usage.status,'unavailable');assert.equal(r.usage.reason,'usage_reader_unavailable');}finally{process.env.PATH=old;}
|
|
76
|
+
const r=analyzeRunRows([claim('a',{stage:'\u001b[31mSECRET'}),usage('a',{stage:'\u001b[31mSECRET'})]);
|
|
77
|
+
assert.equal(r.usage.summary.observed_calls,0);assert.equal(r.usage.summary.invalid_claims,1);
|
|
78
|
+
assert.doesNotMatch(runAnalysisLines(r).join('\n'),/SECRET|\u001b/);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
test('actual AI progress producer: returned, failed, aborted and unfinished operations remain distinct',async t=>{
|
|
83
|
+
const dir=fixture(t,[]),specsDir=dir,codeProject=path.join(dir,'code');fs.mkdirSync(codeProject);
|
|
84
|
+
const definition={specsDir,codeProject,feature:'1.example'},identity={repositoryId:'analysis-fixture',runId:'run-ai-native',taskId:'T-001',attempt:1};
|
|
85
|
+
const options={definition,identity,stage:'checking'};
|
|
86
|
+
await withHostProgress({...options,signal:new AbortController().signal},async()=>({outcome:'failed'}));
|
|
87
|
+
await assert.rejects(withHostProgress({...options,signal:new AbortController().signal},async()=>{throw Error('fixture failure');}),/fixture failure/);
|
|
88
|
+
const controller=new AbortController(),p=startHostProgress({...options,signal:controller.signal});controller.abort();p.complete('returned');
|
|
89
|
+
startHostProgress({...options,signal:new AbortController().signal});
|
|
90
|
+
const rows=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
|
|
91
|
+
assert(rows.filter(x=>x.event==='progress').every(x=>!Object.hasOwn(x,'segment')));
|
|
92
|
+
const report=inspectRunAnalysis({specs:dir}),timing=report.timing;
|
|
93
|
+
assert.equal(timing.pairedSegments,3);assert.equal(timing.incompleteSegments,1);assert.equal(timing.unrecognizedEvents,0);
|
|
94
|
+
assert.equal(timing.status,'partial');assert.deepEqual(timing.stages[0].outcomes,{returned:1,failed:1,aborted:1});
|
|
95
|
+
assert.equal(timing.waitingMs,null);assert.equal(timing.closedForInput,0);
|
|
96
|
+
assert.match(runAnalysisLines(report).join('\n'),/returned=1, failed=1, aborted=1/);
|
|
97
|
+
const start=rows.find(x=>x.phase==='start');
|
|
98
|
+
const wrong={...rows.find(x=>x.phase==='complete'),event_id:'wrong-task',task:'T-002'};
|
|
99
|
+
assert.equal(analyzeRunRows([start,wrong]).timing.pairedSegments,0);
|
|
100
|
+
assert.equal(analyzeRunRows([{...start,workflow:'cm-prd'}]).timing.unrecognizedEvents,1);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('actual QA writer provides identity and operation fields consumed by repetition analysis',t=>{
|
|
104
|
+
const dir=fixture(t,[]),codeProject=path.join(dir,'code');fs.mkdirSync(codeProject);
|
|
105
|
+
const identity={repositoryId:'analysis-fixture',runId:'run-qa-native',taskId:'T-001',attempt:1},packageDigest='a'.repeat(64);
|
|
106
|
+
const binding={specsDir:dir,codeProject,feature:'1.example',identity,packageDigest,logHome:path.join(dir,'mirror')};
|
|
107
|
+
recordCmAiQaDecision({...binding,decision:{decisionId:'qa-decision',identity,packageDigest,status:'triggered',score:null,reason:'api',at:'2026-01-01T00:00:00Z'}});
|
|
108
|
+
recordCmAiQaRun({...binding,testRunId:'qa-operation-native',mode:'commands',caseCount:1,phase:'start'});
|
|
109
|
+
const row=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse).find(x=>x.event==='test_run');
|
|
110
|
+
assert.equal(row.operation_id,'qa-operation-native');assert.equal(row.feature,'1.example');assert.equal(row.task,'T-001');
|
|
111
|
+
// A second distinct start follows the exact producer shape; does not simulate a QA verdict or retry authorization.
|
|
112
|
+
const report=analyzeRunRows([row,{...row,event_id:'second-observed-start',operation_id:'qa-operation-2'}]);
|
|
113
|
+
assert.equal(report.repetitions.groups[0].count,2);assert.equal(report.repetitions.groups[0].kind,'qa_invocation_start');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test('global event identity collisions across runs are rejected before usage deduplication',()=>{
|
|
117
|
+
const a=usage('a',{event_id:'same-event'}),b=usage('b',{run_id:'run-2',event_id:'same-event'});
|
|
118
|
+
assert.throws(()=>analyzeRunRows([a,b]),/log_invalid/);
|
|
119
|
+
assert.throws(()=>analyzeRunRows([a,b],{runId:'run-1'}),/log_invalid/);
|
|
120
|
+
});
|