@aibyzero/cm-workflow 0.12.0 → 0.13.2
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 +1 -0
- package/CHANGELOG.md +55 -1
- package/README.md +31 -3
- package/VERSION +1 -1
- package/compat/claude-commands/cm-runtime.md +3 -0
- package/docs/installation.md +43 -1
- package/docs/js-workflow-control.md +63 -6
- package/docs/runtime-failover.md +97 -0
- package/docs/user-guide.md +37 -1
- package/install-codex.sh +5 -0
- package/install.ps1 +10 -2
- package/install.sh +5 -0
- package/package.json +2 -1
- package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
- package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
- package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
- package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
- package/runtime/js/cm-ai/codex-config.mjs +6 -0
- package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
- package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
- package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
- package/runtime/js/cm-ai/effect-contract.mjs +10 -1
- package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
- package/runtime/js/cm-ai/host-documentation.mjs +4 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
- package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
- package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
- package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
- package/runtime/js/cm-ai/host.mjs +1 -1
- package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
- package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
- package/runtime/js/cm-ai/review-package.mjs +76 -18
- package/runtime/js/cm-ai/review-runner.mjs +15 -3
- package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
- package/runtime/js/cm-ai/specification-material.mjs +98 -0
- package/runtime/js/cm-ai/task-runner.mjs +57 -20
- package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
- package/runtime/js/cm-ai/worker-claude.mjs +18 -5
- package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
- package/runtime/js/cm-ai/worker-codex.mjs +8 -12
- package/runtime/js/cm-init/draft-generation.mjs +24 -4
- package/runtime/js/cm-init/draft-inspection.mjs +29 -1
- package/runtime/js/cm-prd/session.mjs +19 -2
- package/runtime/js/cm-prd/summary.mjs +46 -20
- package/runtime/review.md +11 -1
- package/runtime/workflow-config.md +39 -2
- package/runtime/workflow-routing.md +6 -1
- package/scripts/cm-ai-admission.test.mjs +99 -0
- package/scripts/cm-ai-batch-host.test.mjs +4 -1
- package/scripts/cm-ai-batch-run.test.mjs +7 -1
- package/scripts/cm-ai-bootstrap.test.mjs +2 -1
- package/scripts/cm-ai-fix-integration.test.mjs +2 -1
- package/scripts/cm-ai-host.mjs +81 -12
- package/scripts/cm-ai-host.test.mjs +520 -5
- package/scripts/cm-ai-multi-root.test.mjs +9 -3
- package/scripts/cm-ai-nested-execution.test.mjs +11 -4
- package/scripts/cm-ai-review-timeout.test.mjs +226 -0
- package/scripts/cm-ai-run.mjs +40 -13
- package/scripts/cm-ai-run.test.mjs +45 -9
- package/scripts/cm-check-host.test.mjs +1 -1
- package/scripts/cm-check-runtime.sh +51 -1
- package/scripts/cm-claude-developer-worker.test.mjs +236 -0
- package/scripts/cm-claude-probe.test.mjs +64 -1
- package/scripts/cm-claude-review-stream.test.mjs +236 -1
- package/scripts/cm-claude-worker.test.mjs +110 -1
- package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
- package/scripts/cm-codex-developer-worker.test.mjs +84 -1
- package/scripts/cm-codex-review-progress.test.mjs +34 -6
- package/scripts/cm-failover.mjs +288 -0
- package/scripts/cm-failover.test.mjs +184 -0
- package/scripts/cm-host-qa-executor.test.mjs +277 -0
- package/scripts/cm-host-tool-bridge.test.mjs +31 -0
- package/scripts/cm-init-draft-generation.test.mjs +62 -0
- package/scripts/cm-init-draft-inspection.test.mjs +76 -0
- package/scripts/cm-init-host.mjs +4 -4
- package/scripts/cm-init-host.test.mjs +12 -7
- package/scripts/cm-init-session.test.mjs +50 -0
- package/scripts/cm-log-event.mjs +34 -5
- package/scripts/cm-prd-completion.test.mjs +2 -2
- package/scripts/cm-prd-host.mjs +39 -3
- package/scripts/cm-prd-host.test.mjs +52 -0
- package/scripts/cm-prd-review-gate.mjs +11 -2
- package/scripts/cm-prd-review-gate.test.mjs +62 -0
- package/scripts/cm-prd-session-recovery.test.mjs +167 -0
- package/scripts/cm-prd-summary.test.mjs +147 -0
- package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
- package/scripts/cm-review-inventory.test.mjs +189 -0
- package/scripts/cm-review-schema.test.mjs +35 -1
- package/scripts/cm-review-scope-recovery.test.mjs +63 -0
- package/scripts/cm-runtime-edit.mjs +104 -0
- package/scripts/cm-runtime-failover.test.mjs +130 -0
- package/scripts/cm-runtime-install.mjs +42 -0
- package/scripts/cm-runtime.mjs +113 -0
- package/scripts/cm-runtime.test.mjs +117 -0
- package/scripts/cm-spec-manifest.mjs +24 -21
- package/scripts/cm-spec-manifest.test.mjs +19 -0
- package/scripts/cm-workflow-config.mjs +113 -5
- package/scripts/cm-workflow-config.test.mjs +124 -1
- package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
- package/scripts/test-cm-prd-review-gate.py +30 -0
- package/scripts/test-shell-compat.sh +34 -0
- package/scripts/validate-public-repo.py +5 -0
- package/skills/cm-ai/references/N4-review.md +5 -4
- package/skills/cm-ai/references/js-host.md +36 -2
- package/skills/cm-check/SKILL.md +7 -3
- package/skills/cm-init/SKILL.md +4 -0
- package/skills/cm-init/references/js-host.md +2 -0
- package/skills/cm-init/references/runtime-declaration.md +26 -0
- package/skills/cm-prd/SKILL.md +3 -3
- package/skills/cm-prd/references/js-change-recovery.md +24 -3
- package/skills/cm-prd/references/summary-card.md +7 -0
- package/skills/cm-runtime/SKILL.md +32 -0
- package/templates/auto-update/cm-update.sh +1 -1
- package/templates/cm-workflow.yml +16 -0
package/scripts/cm-log-event.mjs
CHANGED
|
@@ -15,7 +15,7 @@ export const TERMINAL_EVENTS=new Set(['done','run_done']);
|
|
|
15
15
|
export const RESOURCE_GUARDED_EVENTS=new Set([...TERMINAL_EVENTS,'task_done']);
|
|
16
16
|
const RESOURCE_PHASES=new Set(['acquired','released','cleanup_failed']);
|
|
17
17
|
const TEST_RUN_GUARDED_EVENTS=new Set([...TERMINAL_EVENTS,'task_done']);
|
|
18
|
-
const TEST_RUN_PHASES=new Set(['start','case_start','case_complete','case_blocked','complete']);
|
|
18
|
+
const TEST_RUN_PHASES=new Set(['start','case_start','case_complete','case_blocked','complete','abandoned']);
|
|
19
19
|
const MODEL_USAGE_TOKEN_FIELDS=new Set(['input_tokens','output_tokens','cache_read_tokens','cache_write_tokens']);
|
|
20
20
|
const MODEL_USAGE_STATES=new Set(['observed','unavailable']);
|
|
21
21
|
const MODEL_USAGE_OUTCOMES=new Set(['success','error','blocked','cancelled']);
|
|
@@ -210,6 +210,10 @@ function applyTestRunTransition(active,openCases,phase,caseId){
|
|
|
210
210
|
if(!openCases.has(caseId))throw new UsageError('test_run case terminal phase has no case_start');
|
|
211
211
|
openCases.delete(caseId);return active;
|
|
212
212
|
}
|
|
213
|
+
if(phase==='abandoned'){
|
|
214
|
+
if(!active)throw new UsageError('test_run abandoned has no active test run');
|
|
215
|
+
openCases.clear();return false;
|
|
216
|
+
}
|
|
213
217
|
if(!active)throw new UsageError('test_run complete has no active test run');
|
|
214
218
|
if(openCases.size)throw new UsageError('test_run complete has unfinished cases');
|
|
215
219
|
return false;
|
|
@@ -315,8 +319,20 @@ function loadResourceStates(file,runId){
|
|
|
315
319
|
return states;
|
|
316
320
|
}
|
|
317
321
|
|
|
322
|
+
function validateQaAbandonment(state,event){
|
|
323
|
+
const start=state.start;
|
|
324
|
+
if(!state.active||state.hasNonPassResult||!start||event.workflow!=='cm-ai'||event.node!=='N6'
|
|
325
|
+
||JSON.stringify(event.partial_pass_cases===undefined?[]:event.partial_pass_cases)!==JSON.stringify([...state.partialPassCases].sort())
|
|
326
|
+
||(event.partial_pass_cases===undefined&&state.partialPassCases.size>0)
|
|
327
|
+
||event.reason!=='host_terminated'||event.previous_test_run_id!==start.operation_id
|
|
328
|
+
||!['repository_id','run_id','feature','task','package_digest','qa_decision_id','operation_id','attempt','mode','case_count']
|
|
329
|
+
.every(key=>event[key]!==undefined&&event[key]===start[key]))
|
|
330
|
+
throw new UsageError('QA abandonment requires the matching active invocation with only PASS results and matching partial_pass_cases');
|
|
331
|
+
}
|
|
332
|
+
|
|
318
333
|
function loadTestRunState(file,runId){
|
|
319
|
-
let active=false
|
|
334
|
+
let active=false,start=null,hasNonPassResult=false,abandoned=false;
|
|
335
|
+
const openCases=new Set(),partialPassCases=new Set();
|
|
320
336
|
for(const value of readJsonLines(file,{strict:true})){
|
|
321
337
|
if(!value||typeof value!=='object'||value.run_id!==runId||value.event!=='test_run'||value.phase===null||value.phase===undefined)continue;
|
|
322
338
|
const phase=value.phase,caseId=value.case_id;
|
|
@@ -324,16 +340,24 @@ function loadTestRunState(file,runId){
|
|
|
324
340
|
if(phase.startsWith('case_')&&(typeof caseId!=='string'||!RESOURCE_ID.test(caseId)))
|
|
325
341
|
throw new UsageError('test_run state log contains a malformed case event');
|
|
326
342
|
if(phase==='complete'&&!active&&!openCases.size)continue;
|
|
343
|
+
if(phase==='abandoned')validateQaAbandonment({active,start,hasNonPassResult,partialPassCases},value);
|
|
327
344
|
active=applyTestRunTransition(active,openCases,phase,typeof caseId==='string'?caseId:null);
|
|
345
|
+
if(phase==='start'){start=value;hasNonPassResult=false;partialPassCases.clear();abandoned=false;}
|
|
346
|
+
if(phase==='case_complete'){
|
|
347
|
+
if(value.result==='PASS')partialPassCases.add(caseId);
|
|
348
|
+
else hasNonPassResult=true;
|
|
349
|
+
}
|
|
350
|
+
if(phase==='case_blocked')hasNonPassResult=true;
|
|
351
|
+
if(phase==='abandoned')abandoned=true;
|
|
328
352
|
}
|
|
329
|
-
return {active,openCases};
|
|
353
|
+
return {active,openCases,start,hasNonPassResult,partialPassCases,abandoned};
|
|
330
354
|
}
|
|
331
355
|
|
|
332
356
|
// Read-only reuse of the writer's existing resource/test lifecycle guards by
|
|
333
357
|
// the batch coordinator. No new terminal event or task completion authority.
|
|
334
358
|
export function inspectRunClosure(file,runId){
|
|
335
359
|
const resources=unclosedResources(loadResourceStates(file,runId)),tests=loadTestRunState(file,runId);
|
|
336
|
-
return {closed:resources.length===0&&!tests.active&&tests.openCases.size===0};
|
|
360
|
+
return {closed:resources.length===0&&!tests.active&&!tests.abandoned&&tests.openCases.size===0};
|
|
337
361
|
}
|
|
338
362
|
|
|
339
363
|
function compactJson(value){return `${JSON.stringify(value)}\n`;}
|
|
@@ -451,12 +475,17 @@ export function writeLogEvent(rawInput,{environment=process.env,now=new Date(),u
|
|
|
451
475
|
if(existing===null&&((event.event==='test_run'&&event.phase!==undefined)||TEST_RUN_GUARDED_EVENTS.has(event.event)))try{
|
|
452
476
|
testRun=loadTestRunState(authoritativeLog,built.runId);
|
|
453
477
|
}catch(error){throw new UsageError(`test_run state cannot be verified: ${error.name}`);}
|
|
454
|
-
if(existing===null&&TEST_RUN_GUARDED_EVENTS.has(event.event)&&(testRun.active||testRun.openCases.size)){
|
|
478
|
+
if(existing===null&&TEST_RUN_GUARDED_EVENTS.has(event.event)&&(testRun.active||testRun.abandoned||testRun.openCases.size)){
|
|
455
479
|
const detail=[];
|
|
456
480
|
if(testRun.active)detail.push('active invocation');
|
|
457
481
|
if(testRun.openCases.size)detail.push(`open cases: ${[...testRun.openCases].sort().join(', ')}`);
|
|
458
482
|
throw new UsageError(`completion blocked by incomplete test_run: ${detail.join('; ')}`);
|
|
459
483
|
}
|
|
484
|
+
if(existing===null&&event.event==='test_run'&&event.phase==='abandoned'){
|
|
485
|
+
validateQaAbandonment(testRun,event);
|
|
486
|
+
if(unclosedResources(loadResourceStates(authoritativeLog,built.runId)).length)
|
|
487
|
+
throw new UsageError('QA abandonment blocked by unclosed resources');
|
|
488
|
+
}
|
|
460
489
|
if(existing===null&&event.event==='test_run'&&event.phase!==undefined)
|
|
461
490
|
applyTestRunTransition(testRun.active,testRun.openCases,event.phase,event.case_id??null);
|
|
462
491
|
|
|
@@ -85,8 +85,8 @@ test('unknown host generation resumes only its exact original receipt, no repeat
|
|
|
85
85
|
});await c.request('start',{text:'Add example'});const runId=(await c.request('status')).result.runId;
|
|
86
86
|
const crashed=await c.request('advance',{text:'Requirements'});assert.equal(crashed.closed,null);
|
|
87
87
|
c=await client(t,dir,()=>assert.fail('unknown call may not be dispatched again'),{session:runId});
|
|
88
|
-
assert.
|
|
89
|
-
assert.
|
|
88
|
+
assert.equal((await c.request('advance',{text:'Try again'})).result.reason,'prd_operation_recovery_required');
|
|
89
|
+
assert.equal((await c.request('resume',{resolution:null})).result.reason,'prd_host_result_unknown');
|
|
90
90
|
const recovery=original.payload.recovery;
|
|
91
91
|
const result=await c.request('resume',{resolution:{callId:recovery.callId,requestDigest:recovery.requestDigest,
|
|
92
92
|
result:changeResponse(original),evidence:'Synthetic original host saved output, not a new generation'}});
|
package/scripts/cm-prd-host.mjs
CHANGED
|
@@ -20,11 +20,16 @@ import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
|
|
|
20
20
|
import {createPrdChange,assertPrdReviewsSettled} from '../runtime/js/cm-prd/change.mjs';
|
|
21
21
|
import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
|
|
22
22
|
|
|
23
|
+
const sessionFailureCodes=new Set(['prd_operation_recovery_required','prd_host_result_unknown','prd_nothing_to_resume',
|
|
24
|
+
'prd_recovery_binding','prd_recovery_evidence_required','prd_replay_inputs_changed','cancelled','prd_turn_not_ready',
|
|
25
|
+
'prd_review_recovery_required']);
|
|
26
|
+
|
|
23
27
|
export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
|
|
24
28
|
let bridge,analysis,session,change=null,started=false,closed=false,record;
|
|
25
29
|
try{
|
|
26
30
|
if(argv.length===1&&argv[0]==='--help'){
|
|
27
31
|
output.write('New and --change SELECTOR share this host. --session prd-ID resumes a durable local conversation; obtain runId from status. resume {requestId,operation,resolution:null|{callId,requestDigest,result,evidence}} consumes only the original host result, never re-dispatches an unknown call. decision {requestId,operation,proposalDigest,approved,allowUserCaseChanges} confirms an exact change proposal; save_draft archives and writes awaiting_review. prepare_revision {requestId,operation,reason} revises the saved current batch with original review history retained; no review counters reset.\n');
|
|
32
|
+
output.write('resume also accepts resolution:{callId,requestDigest,abandon:true,evidence} with result absent: discard the entire pending operation and restore its before checkpoint, only if no call is prd_review. Explicit cancel is terminal: checkpoint cancelled and active cleared; resume cannot continue it. Session failures return {status:blocked,reason,recovery,completionAuthorized:false} (2026-09-17 dogfood: cancelled checkpoint retained active and hid recovery errors).\n');
|
|
28
33
|
output.write('promote_design {requestId,operation,draftDigest,reason} moves an unreviewed full draft to design while preserving draft and self-check rounds. Saved drafts require complete exact original bytes with private permissions; partial/conflicting saves, prior review and exhausted rounds are rejected. Saved task revisions archive both versions before replacement; no approval is implied.\n');
|
|
29
34
|
output.write('select_design_reviews {requestId,operation,draftDigest,risks:[{feature,signals,evidence}]} at design_ready freezes host-reported Step 9.5 risks for every feature. Only high-risk features may request design review; low-risk exact saved designs continue without it. Not approval; existing attempts cannot be downgraded.\n');
|
|
30
35
|
output.write('plan_design {requestId,operation,text} generates requirements/design only. design_ready permits save_design with --allow-spec-write and original design review. After original design disposition, advance generates tasks from the exact current design, then original self-check/save_draft. No approval is implied.\n');
|
|
@@ -102,6 +107,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
102
107
|
restore(cancelled?stored.checkpoint:stored.active?.before??stored.checkpoint);
|
|
103
108
|
const contextCompletedAt=new Date().toISOString();let contextLogged=false;
|
|
104
109
|
const checkpoint=()=>({analysis:analysis?.checkpoint()??null,change:change?.checkpoint()??null,started,routeTurn,reviewState,summaryState,publishedSummary});
|
|
110
|
+
// Repair older cancelled checkpoints without replaying their retained call.
|
|
111
|
+
if(cancelled){reviewController.abort();session.commit(checkpoint());}
|
|
105
112
|
const status=()=>({...change?.status()??analysis.status(),runId,logWriteEnabled:true,reviewState,summaryState,publishedSummary,
|
|
106
113
|
recovery:session.state.active?{request:session.state.active.request,calls:session.state.active.calls.map(({callId,requestDigest,kind,result})=>
|
|
107
114
|
({callId,requestDigest,kind,status:result===undefined?'unknown':'recorded'}))}:null});
|
|
@@ -140,7 +147,22 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
140
147
|
if(request.operation==='resume_correction')return resumePrdCorrection({specs:admission.specs,stage:request.stage,
|
|
141
148
|
feature:request.feature,writeEnabled:specWriteEnabled&&reviewEnabled},reviewController.signal);
|
|
142
149
|
if(request.operation==='prepare_summary'){
|
|
143
|
-
need(started,'prd_turn_not_ready');
|
|
150
|
+
need(started,'prd_turn_not_ready');
|
|
151
|
+
// The open session is bound to this run under .reviews/prd-sessions.
|
|
152
|
+
// Never infer its scope from the directory inventory or another session.
|
|
153
|
+
const saved=session.state.active?.before??session.state.checkpoint;
|
|
154
|
+
const currentFeatures=analysis.status().draft?.features.map(feature=>feature.directory)
|
|
155
|
+
??saved?.analysis?.draft?.features.map(feature=>feature.directory)??saved?.summaryState?.currentFeatures;
|
|
156
|
+
summaryState=null;
|
|
157
|
+
try{
|
|
158
|
+
need(Array.isArray(currentFeatures)&¤tFeatures.length>0,'prd_summary_scope_unknown');
|
|
159
|
+
summaryState=await summarize(admission.specs,{currentFeatures},reviewController.signal);return summaryState;
|
|
160
|
+
}catch(cause){
|
|
161
|
+
// The shared transport redacts thrown errors. Keep this recoverable
|
|
162
|
+
// scope failure visible without changing that transport contract.
|
|
163
|
+
if(cause.code==='prd_summary_scope_unknown')return {status:'blocked',reason:cause.code,completionAuthorized:false};
|
|
164
|
+
throw cause;
|
|
165
|
+
}
|
|
144
166
|
}
|
|
145
167
|
if(request.operation==='publish_summary'){
|
|
146
168
|
need(summaryState!==null&&summaryState.summaryDigest===request.summaryDigest,'prd_summary_not_ready');
|
|
@@ -200,15 +222,21 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
200
222
|
if(['draft_ready','change_check'].includes(stage))return ['prd-spec-validation','spec_validation'];
|
|
201
223
|
return ['prd-task-split','task_split'];
|
|
202
224
|
};
|
|
203
|
-
const
|
|
225
|
+
const dispatch=async request=>{
|
|
204
226
|
if(request.operation==='status')return status();
|
|
205
|
-
if(request.operation==='cancel'){
|
|
227
|
+
if(request.operation==='cancel'){await handle(request);session.commit(checkpoint());return status();}
|
|
206
228
|
if(request.operation==='inspect_correction')return handle(request);
|
|
229
|
+
need(!reviewController.signal.aborted,'cancelled');
|
|
207
230
|
let operation=request;
|
|
208
231
|
if(request.operation==='resume'){
|
|
209
232
|
shape(request,['requestId','operation','resolution']);
|
|
210
233
|
need(!reviewController.signal.aborted&&session.state.checkpoint?.analysis?.stage!=='cancelled'
|
|
211
234
|
&&session.state.checkpoint?.change?.stage!=='cancelled','cancelled');
|
|
235
|
+
if(request.resolution?.abandon===true){
|
|
236
|
+
const decision=session.abandon(request.resolution);
|
|
237
|
+
restore(session.state.checkpoint);replaying=false;
|
|
238
|
+
record({event:'decision',phase:'recovery',data:decision});return status();
|
|
239
|
+
}
|
|
212
240
|
if(request.resolution!==null)session.resolve(request.resolution);
|
|
213
241
|
const active=session.replay();
|
|
214
242
|
need(active.calls.every(call=>Object.hasOwn(call,'result')),'prd_host_result_unknown');
|
|
@@ -256,6 +284,14 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
256
284
|
session.commit(checkpoint());
|
|
257
285
|
throw cause;
|
|
258
286
|
}
|
|
287
|
+
};
|
|
288
|
+
const host={handle:async request=>{
|
|
289
|
+
try{return await dispatch(request);}
|
|
290
|
+
catch(cause){
|
|
291
|
+
if(sessionFailureCodes.has(cause?.code))return {status:'blocked',reason:cause.code,
|
|
292
|
+
recovery:status().recovery,completionAuthorized:false};
|
|
293
|
+
throw cause;
|
|
294
|
+
}
|
|
259
295
|
}};
|
|
260
296
|
const rawMode=input.isTTY&&typeof input.setRawMode==='function';if(rawMode)input.setRawMode(true);
|
|
261
297
|
try{await serveCmAiHost({host,input,output,toolBridge:bridge,inputLimit:1024*1024});}finally{if(rawMode)input.setRawMode(false);}
|
|
@@ -7,6 +7,8 @@ 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 {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
|
|
11
|
+
import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
|
|
10
12
|
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
11
13
|
for(const mode of ['codex','claude','cancel','cases','materials','draft','self-check'])test(`PRD actual CLI and original log adapter: ${mode}`,{timeout:15000},async()=>{
|
|
12
14
|
const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-host-')));
|
|
@@ -131,9 +133,16 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
131
133
|
assert.equal(message.result.status,'disposition_recorded');
|
|
132
134
|
assert.equal(message.result.gate.disposition,'applied');assert.equal(checks,3);
|
|
133
135
|
assert.equal(message.result.completionAuthorized,false);
|
|
136
|
+
fs.mkdirSync(path.join(dir,'2.history'));
|
|
137
|
+
for(const file of ['requirements.md','design.md','tasks.md'])fs.writeFileSync(path.join(dir,'2.history',file),
|
|
138
|
+
fs.readFileSync(path.join(dir,'1.guide',file),'utf8').replaceAll('[ ]','[x]'),{mode:0o600});
|
|
139
|
+
fs.writeFileSync(path.join(dir,'.reviews/prd-history-split-r1.md'),
|
|
140
|
+
fs.readFileSync(path.join(dir,'.reviews/prd-guide-split-r1.md'),'utf8').replace(/\n```json\n[^\n]+\n```\n$/,''),{mode:0o600});
|
|
134
141
|
send({requestId:'summary',operation:'prepare_summary'});
|
|
135
142
|
}else if(message.requestId==='summary'){
|
|
136
143
|
assert.equal(message.result.status,'human_summary_prepared');assert.equal(message.result.readyForAwaitingReview,true);
|
|
144
|
+
assert.deepEqual(message.result.currentFeatures,['1.guide']);
|
|
145
|
+
assert.match(message.result.notes.join('\n'),/历史 feature 2.history.*旧版归档/);
|
|
137
146
|
assert.equal(message.result.totals.tasks,1);assert.equal(message.result.checklist.every(item=>!item.checked),true);
|
|
138
147
|
firstSummary=message.result;send({requestId:'summary-again',operation:'prepare_summary'});
|
|
139
148
|
}else if(message.requestId==='summary-again'){
|
|
@@ -148,6 +157,7 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
148
157
|
}else if(message.requestId==='publish-summary'){
|
|
149
158
|
assert.equal(message.result.status,'awaiting_review');assert.equal(message.result.completionAuthorized,false);
|
|
150
159
|
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).status,'awaiting_review');
|
|
160
|
+
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).features,['1.guide','2.history']);
|
|
151
161
|
send({requestId:'status',operation:'status'});
|
|
152
162
|
}else if(message.requestId==='status'){status=message.result;send({type:'host_close',sessionId});}
|
|
153
163
|
}
|
|
@@ -167,3 +177,45 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
167
177
|
assert.equal(status.completionAuthorized,false);
|
|
168
178
|
}finally{child.kill();lines.close();await closed;fs.rmSync(dir,{recursive:true,force:true});}
|
|
169
179
|
});
|
|
180
|
+
|
|
181
|
+
for(const known of [true,false])test(`summary without draft uses only current durable session scope: ${known}`,{timeout:15000},async t=>{
|
|
182
|
+
const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-summary-session-')));
|
|
183
|
+
t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
|
184
|
+
for(const name of ['docs','mirror','1.history','2.current'])fs.mkdirSync(path.join(dir,name));
|
|
185
|
+
fs.writeFileSync(path.join(dir,'docs/input.md'),'Synthetic request');
|
|
186
|
+
for(const feature of ['1.history','2.current'])for(const [file,content] of Object.entries({
|
|
187
|
+
'requirements.md':'- [ ] [AC-001] Read guide','tasks.md':'- [ ] T-001: Guide','design.md':'# Design'}))
|
|
188
|
+
fs.writeFileSync(path.join(dir,feature,file),feature==='1.history'?content.replace('[ ]','[x]'):content,{mode:0o600});
|
|
189
|
+
const entry={skillDir:path.join(root,'skills/cm-prd'),project:dir,specs:dir};
|
|
190
|
+
const analysis=createCmPrdAnalysis({input:entry,runtime:'codex',record:()=>{},analyze:async()=>({
|
|
191
|
+
status:'analyzed',summary:'Synthetic request',sourcePaths:['docs/input.md'],openQuestions:[]})});
|
|
192
|
+
await analysis.advance('Analyze');
|
|
193
|
+
const checkpoint={analysis:analysis.checkpoint(),started:true,summaryState:known?{currentFeatures:['2.current']}:null};
|
|
194
|
+
for(const [sessionId,state] of [['prd-current',checkpoint],['prd-other',{...checkpoint,summaryState:{currentFeatures:['1.history']}}]]){
|
|
195
|
+
const session=openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});session.checkpoint(state);session.close();
|
|
196
|
+
}
|
|
197
|
+
const child=spawn(process.execPath,[path.join(root,'scripts/cm-prd-host.mjs'),'serve','--skill-dir',entry.skillDir,
|
|
198
|
+
'--project',dir,'--specs',dir,'--runtime','codex','--allow-log-write','--session','prd-current'],
|
|
199
|
+
{env:{...process.env,CM_WORKFLOW_LOG_HOME:path.join(dir,'mirror')},stdio:['pipe','pipe','pipe']});
|
|
200
|
+
const closed=once(child,'close'),lines=createInterface({input:child.stdout});let sessionId,calls=0,result,stderr='';
|
|
201
|
+
child.stderr.on('data',chunk=>{stderr+=chunk;});const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
|
|
202
|
+
try{
|
|
203
|
+
for await(const line of lines){
|
|
204
|
+
const message=JSON.parse(line);
|
|
205
|
+
if(message.type==='host_ready'){sessionId=message.sessionId;send({requestId:'summary',operation:'prepare_summary'});}
|
|
206
|
+
else if(message.type==='host_request'){
|
|
207
|
+
calls++;assert.equal(known,true);assert.equal(message.kind,'prd_summary');
|
|
208
|
+
assert.deepEqual(message.payload.evidence.currentFeatures,['2.current']);
|
|
209
|
+
send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,result:{
|
|
210
|
+
evidenceDigest:message.payload.evidenceDigest,deliveryForm:'Docs',estimatedTime:'Unknown',openQuestions:'None',risks:'Synthetic',
|
|
211
|
+
contextScope:'Targeted',platformReadiness:'None',uiBaseline:'None',designRisk:[{feature:'2.current',
|
|
212
|
+
signals:{greenfieldAdr:false,architectureOrDataFlow:false,newRuntimeDependencyOrToolchain:false,
|
|
213
|
+
publicContractDataOrSecurity:false,fiveOrMoreFunctions:false},evidence:['Synthetic fixture']}]}});
|
|
214
|
+
}else if(message.requestId==='summary'){result=message;send({type:'host_close',sessionId});}
|
|
215
|
+
}
|
|
216
|
+
assert.equal((await closed)[0],0,stderr);assert.ok(result);
|
|
217
|
+
if(known){assert.equal(calls,1);assert.equal(result.result.status,'human_summary_prepared');
|
|
218
|
+
assert.deepEqual(result.result.blockers,['2.current: split_review_disposition_required']);}
|
|
219
|
+
else{assert.equal(calls,0);assert.equal(result.result.status,'blocked');assert.equal(result.result.reason,'prd_summary_scope_unknown');}
|
|
220
|
+
}finally{child.kill();lines.close();await closed;}
|
|
221
|
+
});
|
|
@@ -6,6 +6,7 @@ import os from 'node:os';
|
|
|
6
6
|
import {createHash,randomUUID} from 'node:crypto';
|
|
7
7
|
import {TextDecoder} from 'node:util';
|
|
8
8
|
import {fileURLToPath} from 'node:url';
|
|
9
|
+
import {normalizeRuntimeMarks} from './cm-spec-manifest.mjs';
|
|
9
10
|
|
|
10
11
|
const fail=message=>{throw new Error(message);};
|
|
11
12
|
const need=(ok,message)=>{if(!ok)fail(message);};
|
|
@@ -103,7 +104,14 @@ function loadReceipt(file,args,evidence){
|
|
|
103
104
|
const raw=path.join(root,item.path);need(!link(raw),'PRD review artifact is missing or unsafe');
|
|
104
105
|
const artifact=resolve(raw);need(within(root,artifact),'PRD review artifact escapes the specs directory');
|
|
105
106
|
need(stat(artifact)?.isFile(),'PRD review artifact is missing or unsafe');
|
|
106
|
-
|
|
107
|
+
const bytes=fs.readFileSync(artifact);
|
|
108
|
+
if(createHash('sha256').update(bytes).digest('hex')!==item.sha256){
|
|
109
|
+
const text=bytes.toString('utf8');
|
|
110
|
+
need(path.extname(artifact)==='.md'&&Buffer.from(text,'utf8').equals(bytes)
|
|
111
|
+
&&createHash('sha256').update(normalizeRuntimeMarks(text,path.basename(artifact))).digest('hex')===item.sha256,
|
|
112
|
+
'PRD review artifact changed after disposition');
|
|
113
|
+
value.runtimeMarksNormalized=true;
|
|
114
|
+
}
|
|
107
115
|
}
|
|
108
116
|
return value;
|
|
109
117
|
}
|
|
@@ -150,7 +158,8 @@ export function inspectPrdReview(args){
|
|
|
150
158
|
if(!stat(evidence))return dispatch?{...base,outcome:'dispatch_unknown',package_sha256:dispatch.package_sha256}:
|
|
151
159
|
{...base,outcome:'dispatch_once'};
|
|
152
160
|
evidenceHeader(evidence);if(!stat(receipt))return {...base,outcome:'resume_disposition'};
|
|
153
|
-
const value=loadReceipt(receipt,args,evidence);return {...base,outcome:'completed',disposition:value.disposition
|
|
161
|
+
const value=loadReceipt(receipt,args,evidence);return {...base,outcome:'completed',disposition:value.disposition,
|
|
162
|
+
...(value.runtimeMarksNormalized?{runtimeMarksNormalized:true}:{})};
|
|
154
163
|
}
|
|
155
164
|
export function recordPrdReview(args){
|
|
156
165
|
counts(args.disposition,args.finding_count,args.unresolved_count);
|
|
@@ -0,0 +1,62 @@
|
|
|
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 {inspectPrdReview,recordPrdReview} from './cm-prd-review-gate.mjs';
|
|
7
|
+
function fixture(t,documents){
|
|
8
|
+
const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-marks-')));
|
|
9
|
+
t.after(()=>fs.rmSync(root,{recursive:true,force:true}));fs.mkdirSync(path.join(root,'.reviews'));
|
|
10
|
+
const args={stage:'split',feature:'guide',evidence:path.join(root,'.reviews/prd-guide-split-r1.md'),
|
|
11
|
+
receipt:path.join(root,'.reviews/prd-guide-split-disposition.json')};
|
|
12
|
+
fs.writeFileSync(args.evidence,'---\nat: 2026-09-08T00:00:00Z\nreviewer: codex-subagent\nindependent: true\nscope:\n - tasks.md\n---\nSynthetic fixture review');
|
|
13
|
+
for(const [name,content] of Object.entries(documents))fs.writeFileSync(path.join(root,name),content);
|
|
14
|
+
const record={...args,disposition:'no_findings',finding_count:0,unresolved_count:0,
|
|
15
|
+
artifact:Object.keys(documents).map(name=>path.join(root,name))};
|
|
16
|
+
recordPrdReview(record);return {root,args,record};
|
|
17
|
+
}
|
|
18
|
+
for(const mark of ['x','X'])test(`receipt accepts only runtime ${mark} marks without rewriting evidence`,t=>{
|
|
19
|
+
const {root,args,record}=fixture(t,{'tasks.md':'- [ ] T-001: 文档\r\n','requirements.md':'- [ ] [AC-001] 文档\r\n'});
|
|
20
|
+
const receipt=fs.readFileSync(args.receipt),evidence=fs.readFileSync(args.evidence);
|
|
21
|
+
assert.deepEqual(inspectPrdReview(args),{stage:'split',feature:'guide',outcome:'completed',disposition:'no_findings'});
|
|
22
|
+
for(const name of ['tasks.md','requirements.md']){
|
|
23
|
+
const file=path.join(root,name);fs.writeFileSync(file,fs.readFileSync(file,'utf8').replace('[ ]',`[${mark}]`));
|
|
24
|
+
}
|
|
25
|
+
assert.deepEqual(inspectPrdReview(args),{stage:'split',feature:'guide',outcome:'completed',disposition:'no_findings',runtimeMarksNormalized:true});
|
|
26
|
+
assert.equal(recordPrdReview(record).outcome,'already_recorded');
|
|
27
|
+
assert.deepEqual(fs.readFileSync(args.receipt),receipt);assert.deepEqual(fs.readFileSync(args.evidence),evidence);
|
|
28
|
+
});
|
|
29
|
+
for(const [name,before,after] of [
|
|
30
|
+
['tasks.md','- [ ] T-001: Guide\n','- [x] T-001: Guides\n'],
|
|
31
|
+
['requirements.md','- [ ] [AC-001] Guide\n','- [x] [AC-001] Guides\n'],
|
|
32
|
+
['tasks.md','- [ ] T-001: Guide\r\n','- [x] T-001: Guide\n'],
|
|
33
|
+
['tasks.md','- [ ] T-001: Guide\n- [DROPPED] T-002: Old\n','- [x] T-001: Guide\n- [CHANGED] T-002: Old\n'],
|
|
34
|
+
['tasks.md','```md\n- [ ] T-001: Example\n```','```md\n- [x] T-001: Example\n```'],
|
|
35
|
+
['tasks.md',' - [ ] T-001: Example',' - [x] T-001: Example'],
|
|
36
|
+
['tasks.md','Prose - [ ] T-001: Example','Prose - [x] T-001: Example'],
|
|
37
|
+
['tasks.md','- [ ] General checkbox','- [x] General checkbox'],
|
|
38
|
+
['tasks.md','- [ ] [AC-001] Wrong file','- [x] [AC-001] Wrong file'],
|
|
39
|
+
['design.md','- [ ] T-001: Example','- [x] T-001: Example'],
|
|
40
|
+
['test-cases.json','{"cases":[]}','{"cases":[]}\n'],
|
|
41
|
+
['test-cases.json','{"note":"- [ ] T-001: Example"}','{"note":"- [x] T-001: Example"}'],
|
|
42
|
+
])test(`receipt rejects non-runtime drift: ${name} ${JSON.stringify(after)}`,t=>{
|
|
43
|
+
const {root,args}=fixture(t,{[name]:before});fs.writeFileSync(path.join(root,name),after);
|
|
44
|
+
assert.throws(()=>inspectPrdReview(args),/PRD review artifact changed after disposition/);
|
|
45
|
+
});
|
|
46
|
+
test('runtime mark in another artifact cannot mask JSON drift',t=>{
|
|
47
|
+
const {root,args}=fixture(t,{'tasks.md':'- [ ] T-001: Guide','test-cases.json':'{"cases":[]}'});
|
|
48
|
+
fs.writeFileSync(path.join(root,'tasks.md'),'- [x] T-001: Guide');
|
|
49
|
+
fs.appendFileSync(path.join(root,'test-cases.json'),' ');
|
|
50
|
+
assert.throws(()=>inspectPrdReview(args),/PRD review artifact changed after disposition/);
|
|
51
|
+
});
|
|
52
|
+
test('raw completed receipt remains valid but unchecking it cannot match a normalized receipt',t=>{
|
|
53
|
+
const {root,args}=fixture(t,{'tasks.md':'- [x] T-001: Guide'});
|
|
54
|
+
assert.equal(inspectPrdReview(args).runtimeMarksNormalized,undefined);
|
|
55
|
+
fs.writeFileSync(path.join(root,'tasks.md'),'- [ ] T-001: Guide');
|
|
56
|
+
assert.throws(()=>inspectPrdReview(args),/PRD review artifact changed after disposition/);
|
|
57
|
+
});
|
|
58
|
+
test('normalization does not replace invalid UTF-8 with a formerly reviewed replacement character',t=>{
|
|
59
|
+
const {root,args}=fixture(t,{'tasks.md':'- [ ] T-001: \ufffd'});
|
|
60
|
+
fs.writeFileSync(path.join(root,'tasks.md'),Buffer.concat([Buffer.from('- [x] T-001: '),Buffer.from([0xff])]));
|
|
61
|
+
assert.throws(()=>inspectPrdReview(args),/PRD review artifact changed after disposition/);
|
|
62
|
+
});
|
|
@@ -0,0 +1,167 @@
|
|
|
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 {spawn,spawnSync} from 'node:child_process';
|
|
7
|
+
import {once} from 'node:events';
|
|
8
|
+
import {createInterface} from 'node:readline';
|
|
9
|
+
import {fileURLToPath} from 'node:url';
|
|
10
|
+
import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
|
|
11
|
+
import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
|
|
12
|
+
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
13
|
+
const sessionId='prd-recovery-fixture';
|
|
14
|
+
async function fixture(t,{ready=false,change=false}={}){
|
|
15
|
+
const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-recovery-')));
|
|
16
|
+
t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
|
17
|
+
for(const name of ['docs','mirror','1.guide'])fs.mkdirSync(path.join(dir,name));
|
|
18
|
+
fs.writeFileSync(path.join(dir,'docs/input.md'),'Synthetic request');
|
|
19
|
+
for(const [file,content] of Object.entries({'requirements.md':'- [ ] [AC-001] Guide',
|
|
20
|
+
'design.md':'# Guide','tasks.md':'- [ ] T-001: Guide'}))fs.writeFileSync(path.join(dir,'1.guide',file),content,{mode:0o600});
|
|
21
|
+
const entry={skillDir:path.join(root,'skills/cm-prd'),project:dir,specs:dir,...(change?{change:'1.guide'}:{})};
|
|
22
|
+
const identity={entry,runtime:'codex'},open=()=>openPrdSession({specs:dir,sessionId,identity});
|
|
23
|
+
if(!change){
|
|
24
|
+
const analysis=createCmPrdAnalysis({input:entry,runtime:'codex',record:()=>{},analyze:async()=>({
|
|
25
|
+
status:'analyzed',summary:'Synthetic request',sourcePaths:['docs/input.md'],openQuestions:[]})});
|
|
26
|
+
if(!ready)await analysis.advance('Analyze');
|
|
27
|
+
const session=open();session.checkpoint({analysis:analysis.checkpoint(),change:null,started:!ready,
|
|
28
|
+
routeTurn:0,reviewState:null,summaryState:ready?null:{currentFeatures:['1.guide']},publishedSummary:false});session.close();
|
|
29
|
+
}
|
|
30
|
+
const stateFile=path.join(dir,'.reviews/prd-sessions',sessionId,'state.json');
|
|
31
|
+
return {dir,entry,open,state:()=>JSON.parse(fs.readFileSync(stateFile,'utf8'))};
|
|
32
|
+
}
|
|
33
|
+
async function client(t,f){
|
|
34
|
+
const child=spawn(process.execPath,[path.join(root,'scripts/cm-prd-host.mjs'),'serve','--skill-dir',f.entry.skillDir,
|
|
35
|
+
'--project',f.dir,'--specs',f.dir,'--runtime','codex','--allow-log-write','--session',sessionId,
|
|
36
|
+
...(f.entry.change?['--change',f.entry.change]:[])],
|
|
37
|
+
{env:{...process.env,CM_WORKFLOW_LOG_HOME:path.join(f.dir,'mirror')},stdio:['pipe','pipe','pipe']});
|
|
38
|
+
let stderr='',seq=0;child.stderr.on('data',chunk=>stderr+=chunk);
|
|
39
|
+
const closed=once(child,'close'),lines=createInterface({input:child.stdout}),queue=[],waiters=[];
|
|
40
|
+
lines.on('line',line=>{const value=JSON.parse(line),index=waiters.findIndex(w=>w.match(value));
|
|
41
|
+
if(index===-1)queue.push(value);else waiters.splice(index,1)[0].resolve(value);});
|
|
42
|
+
const wait=match=>{const index=queue.findIndex(match);return index===-1?
|
|
43
|
+
new Promise(resolve=>waiters.push({match,resolve})):Promise.resolve(queue.splice(index,1)[0]);};
|
|
44
|
+
const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
|
|
45
|
+
t.after(async()=>{if(child.exitCode===null&&child.signalCode===null)child.kill();await closed;lines.close();});
|
|
46
|
+
const ready=await wait(m=>m.type==='host_ready');
|
|
47
|
+
return {wait,send,request:(operation,fields={})=>{const requestId=`request-${++seq}`;
|
|
48
|
+
const reply=wait(m=>m.requestId===requestId);send({requestId,operation,...fields});return reply;},
|
|
49
|
+
close:async()=>{send({type:'host_close',sessionId:ready.sessionId});assert.equal((await closed)[0],0,stderr);},
|
|
50
|
+
result:(call,result)=>send({type:'host_result',sessionId:ready.sessionId,callId:call.callId,requestDigest:call.requestDigest,result})};
|
|
51
|
+
}
|
|
52
|
+
function blocked(reply,reason){
|
|
53
|
+
assert.equal(reply.error,undefined);assert.equal(reply.result.status,'blocked');assert.equal(reply.result.reason,reason);
|
|
54
|
+
assert.equal(reply.result.completionAuthorized,false);assert.ok(Object.hasOwn(reply.result,'recovery'));return reply.result;
|
|
55
|
+
}
|
|
56
|
+
async function unknownSummary(t,f){
|
|
57
|
+
const c=await client(t,f),pending=c.request('prepare_summary');
|
|
58
|
+
const call=await c.wait(m=>m.type==='host_request');assert.equal(call.kind,'prd_summary');
|
|
59
|
+
await c.close();assert.equal((await pending).error.code,'host_request_failed');return call;
|
|
60
|
+
}
|
|
61
|
+
const abandon=call=>({callId:call.payload.recovery.callId,requestDigest:call.payload.recovery.requestDigest,
|
|
62
|
+
abandon:true,evidence:'Synthetic original call unavailable; explicit discard reference'});
|
|
63
|
+
|
|
64
|
+
test('unknown summary exposes session reasons, abandon restores before and permits fresh host request', {timeout:20000},async t=>{
|
|
65
|
+
const f=await fixture(t),original=await unknownSummary(t,f),before=f.state().active.before;
|
|
66
|
+
let c=await client(t,f);
|
|
67
|
+
const recovery=blocked(await c.request('prepare_summary'),'prd_operation_recovery_required').recovery;
|
|
68
|
+
assert.equal(recovery.calls[0].callId,original.payload.recovery.callId);assert.equal(recovery.calls[0].status,'unknown');
|
|
69
|
+
blocked(await c.request('resume',{resolution:null}),'prd_host_result_unknown');
|
|
70
|
+
const initial=f.state(),resolution=abandon(original);
|
|
71
|
+
for(const bad of [{...resolution,result:{}},{...resolution,requestDigest:'wrong'},
|
|
72
|
+
{...resolution,callId:'wrong'},{...resolution,abandon:false},{...resolution,unexpected:true}]){
|
|
73
|
+
blocked(await c.request('resume',{resolution:bad}),'prd_recovery_binding');assert.deepEqual(f.state(),initial);
|
|
74
|
+
}
|
|
75
|
+
for(const bad of [{...resolution,evidence:' '},{callId:resolution.callId,requestDigest:resolution.requestDigest,abandon:true},
|
|
76
|
+
{callId:resolution.callId,requestDigest:resolution.requestDigest,result:{},evidence:''}]){
|
|
77
|
+
blocked(await c.request('resume',{resolution:bad}),'prd_recovery_evidence_required');assert.deepEqual(f.state(),initial);
|
|
78
|
+
}
|
|
79
|
+
const result=(await c.request('resume',{resolution})).result;
|
|
80
|
+
assert.equal(result.stage,before.analysis.stage);assert.equal(result.recovery,null);
|
|
81
|
+
assert.equal(f.state().active,null);assert.deepEqual(f.state().checkpoint,before);
|
|
82
|
+
assert.equal(JSON.stringify(f.state()).includes(resolution.evidence),false);
|
|
83
|
+
const rows=fs.readFileSync(path.join(f.dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
|
|
84
|
+
const decisions=rows.filter(row=>row.event==='decision'&&row.phase==='recovery');assert.equal(decisions.length,1);
|
|
85
|
+
const decision=decisions[0];assert.equal(decision.operation,'prepare_summary');assert.equal(decision.kind,'prd_summary');
|
|
86
|
+
assert.equal(decision.callId,resolution.callId);assert.match(decision.evidence.sha256,/^[a-f0-9]{64}$/);
|
|
87
|
+
assert.equal(decision.evidence.length,resolution.evidence.length);assert.equal(Object.hasOwn(decision,'payload'),false);
|
|
88
|
+
for(const row of decisions)assert.equal(JSON.stringify(row).includes(resolution.evidence),false);
|
|
89
|
+
await c.close();c=await client(t,f);
|
|
90
|
+
blocked(await c.request('resume',{resolution:null}),'prd_nothing_to_resume');
|
|
91
|
+
const retry=c.request('prepare_summary'),fresh=await c.wait(m=>m.type==='host_request');
|
|
92
|
+
assert.equal(fresh.kind,'prd_summary');assert.notEqual(fresh.payload.recovery.callId,resolution.callId);
|
|
93
|
+
assert.deepEqual(fresh.payload.evidence.currentFeatures,['1.guide']);
|
|
94
|
+
await c.close();await retry;
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
for(const mode of ['summary','analysis','change'])test(`cancel clears pending ${mode} and stays terminal across restart`,{timeout:15000},async t=>{
|
|
98
|
+
const f=await fixture(t,{ready:mode==='analysis',change:mode==='change'});let c=await client(t,f);
|
|
99
|
+
const pending=c.request(mode==='summary'?'prepare_summary':'start',mode==='summary'?{}:{text:'Analyze'});
|
|
100
|
+
const call=await c.wait(m=>m.type==='host_request');
|
|
101
|
+
const cancelled=(await c.request('cancel')).result;assert.equal(cancelled.stage,'cancelled');assert.equal(cancelled.recovery,null);
|
|
102
|
+
assert.equal((await pending).result.stage,'cancelled');
|
|
103
|
+
const key=mode==='change'?'change':'analysis';assert.equal(f.state().checkpoint[key].stage,'cancelled');assert.equal(f.state().active,null);
|
|
104
|
+
c.result(call,{});assert.equal((await c.wait(m=>m.type==='host_response')).accepted,false);
|
|
105
|
+
for(const resolution of [null,abandon(call),{...abandon(call),result:{}}])blocked(await c.request('resume',{resolution}),'cancelled');
|
|
106
|
+
blocked(await c.request('prepare_summary'),'cancelled');await c.close();
|
|
107
|
+
c=await client(t,f);assert.equal((await c.request('status')).result.stage,'cancelled');
|
|
108
|
+
blocked(await c.request('resume',{resolution:null}),'cancelled');blocked(await c.request('start',{text:'Retry'}),'cancelled');
|
|
109
|
+
assert.equal(f.state().active,null);await c.close();
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test('old cancelled checkpoint with active is normalized without replay', {timeout:15000},async t=>{
|
|
113
|
+
const f=await fixture(t);await unknownSummary(t,f);
|
|
114
|
+
const session=f.open(),checkpoint=session.state.checkpoint;
|
|
115
|
+
session.checkpoint({...checkpoint,analysis:{...checkpoint.analysis,stage:'cancelled'}});session.close();
|
|
116
|
+
assert.ok(f.state().active);const c=await client(t,f);
|
|
117
|
+
assert.equal(f.state().active,null);assert.equal((await c.request('status')).result.stage,'cancelled');
|
|
118
|
+
blocked(await c.request('resume',{resolution:null}),'cancelled');await c.close();
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
async function seedCalls(f,calls,request={requestId:'original',operation:'prepare_summary'}){
|
|
122
|
+
const session=f.open();try{
|
|
123
|
+
session.begin(request,session.state.checkpoint);
|
|
124
|
+
for(const {kind,result} of calls){
|
|
125
|
+
try{await session.call(kind,{synthetic:'private-payload'},new AbortController().signal,async()=>{
|
|
126
|
+
if(result===undefined)throw Error('synthetic disconnect');return result;});}catch(e){assert.equal(e.message,'synthetic disconnect');}
|
|
127
|
+
}
|
|
128
|
+
}finally{session.close();}
|
|
129
|
+
}
|
|
130
|
+
for(const mixed of [false,true])test(`abandon rejects any prd_review call in operation: mixed=${mixed}`,{timeout:15000},async t=>{
|
|
131
|
+
const f=await fixture(t);await seedCalls(f,mixed?[{kind:'prd_review',result:{}},{kind:'prd_self_check'}]:[{kind:'prd_review'}]);
|
|
132
|
+
const before=f.state(),target=before.active.calls.at(-1),c=await client(t,f);
|
|
133
|
+
const resolution={callId:target.callId,requestDigest:target.requestDigest,abandon:true,evidence:'Synthetic discard request'};
|
|
134
|
+
const result=blocked(await c.request('resume',{resolution}),'prd_review_recovery_required');
|
|
135
|
+
assert.equal(result.recovery.calls.length,before.active.calls.length);assert.deepEqual(f.state(),before);await c.close();
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test('turn and replay errors are visible while unrelated errors remain redacted', {timeout:15000},async t=>{
|
|
139
|
+
const f=await fixture(t,{ready:true});let c=await client(t,f);
|
|
140
|
+
assert.equal(blocked(await c.request('advance',{text:'Too early'}),'prd_turn_not_ready').recovery,null);
|
|
141
|
+
assert.equal((await c.request('save_draft')).error.code,'host_request_failed');await c.close();
|
|
142
|
+
await seedCalls(f,[{kind:'prd_analyze',result:{status:'question',question:'Original'}}],{requestId:'original',operation:'start',text:'Analyze'});
|
|
143
|
+
c=await client(t,f);const result=blocked(await c.request('resume',{resolution:null}),'prd_replay_inputs_changed');
|
|
144
|
+
assert.equal(result.recovery.calls[0].status,'recorded');await c.close();
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('session rejects abandoning recorded results and late replies cannot resurrect cancelled active',async t=>{
|
|
148
|
+
const f=await fixture(t),session=f.open();try{
|
|
149
|
+
session.begin({requestId:'original',operation:'prepare_summary'},session.state.checkpoint);
|
|
150
|
+
await session.call('prd_summary',{},new AbortController().signal,async()=>({original:true}));
|
|
151
|
+
const before=session.state,target=before.active.calls[0];
|
|
152
|
+
assert.throws(()=>session.abandon({callId:target.callId,requestDigest:target.requestDigest,abandon:true,evidence:'Reference'}),{code:'prd_recovery_binding'});
|
|
153
|
+
assert.deepEqual(session.state,before);
|
|
154
|
+
session.commit(before.checkpoint);session.begin({requestId:'late',operation:'prepare_summary'},before.checkpoint);
|
|
155
|
+
let finish;const controller=new AbortController();
|
|
156
|
+
const pending=session.call('prd_summary',{},controller.signal,()=>new Promise(resolve=>{finish=resolve;}));
|
|
157
|
+
const terminal={...before.checkpoint,analysis:{...before.checkpoint.analysis,stage:'cancelled'}};
|
|
158
|
+
controller.abort();session.commit(terminal);finish({late:true});
|
|
159
|
+
await assert.rejects(pending,{code:'cancelled'});assert.equal(session.state.active,null);assert.deepEqual(f.state().checkpoint,terminal);
|
|
160
|
+
}finally{session.close();}
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test('help documents abandon shape and terminal cancellation',()=>{
|
|
164
|
+
const result=spawnSync(process.execPath,[path.join(root,'scripts/cm-prd-host.mjs'),'--help'],{encoding:'utf8'});
|
|
165
|
+
assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/abandon:true/);assert.match(result.stdout,/result absent/);
|
|
166
|
+
assert.match(result.stdout,/cancel is terminal/);assert.match(result.stdout,/prd_review/);
|
|
167
|
+
});
|