@aibyzero/cm-workflow 0.15.5 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +45 -0
  3. package/README.md +2 -2
  4. package/VERSION +1 -1
  5. package/docs/installation.md +1 -1
  6. package/docs/js-workflow-control.md +174 -3
  7. package/package.json +1 -1
  8. package/runtime/js/cm-ai/checklist-coverage.mjs +70 -0
  9. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +12 -2
  10. package/runtime/js/cm-ai/durable-runner-state.mjs +12 -1
  11. package/runtime/js/cm-ai/effect-contract.mjs +31 -4
  12. package/runtime/js/cm-ai/host-conversation-execution.mjs +91 -3
  13. package/runtime/js/cm-ai/host-handoff.mjs +59 -1
  14. package/runtime/js/cm-ai/host-session.mjs +21 -2
  15. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  16. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -1
  17. package/runtime/js/cm-ai/review-package.mjs +29 -3
  18. package/runtime/js/cm-ai/task-runner.mjs +44 -3
  19. package/runtime/js/cm-fix/cause-invocation.mjs +17 -4
  20. package/runtime/js/cm-fix/execution.mjs +30 -22
  21. package/runtime/js/cm-fix/final-review.mjs +18 -11
  22. package/runtime/js/cm-fix/finish.mjs +14 -1
  23. package/runtime/js/cm-security/scan.mjs +7 -1
  24. package/scripts/cm-ai-batch-host.mjs +18 -6
  25. package/scripts/cm-ai-batch-run.mjs +12 -4
  26. package/scripts/cm-ai-checklist-coverage.test.mjs +116 -0
  27. package/scripts/cm-ai-execution-diagnostic.test.mjs +68 -0
  28. package/scripts/cm-ai-host.mjs +7 -2
  29. package/scripts/cm-ai-qa-recovery-args.test.mjs +80 -0
  30. package/scripts/cm-ai-review-timeout-config.test.mjs +53 -0
  31. package/scripts/cm-ai-run.mjs +2 -1
  32. package/scripts/cm-ai-verification-gate.test.mjs +116 -0
  33. package/scripts/cm-fix-cross-session-host.test.mjs +100 -0
  34. package/scripts/cm-fix-execution.test.mjs +33 -0
  35. package/scripts/cm-fix-host.mjs +11 -5
  36. package/scripts/cm-fix-repair-owner.test.mjs +22 -18
  37. package/scripts/cm-host-handoff.test.mjs +116 -1
  38. package/scripts/cm-host-session-diagnostic.test.mjs +82 -0
  39. package/scripts/cm-review-dependency-snapshot.test.mjs +85 -0
  40. package/scripts/cm-review-inventory.test.mjs +42 -0
  41. package/scripts/cm-security.test.mjs +24 -0
  42. package/skills/cm-ai/references/N3-execute-task.md +10 -0
  43. package/skills/cm-fix/references/js-host.md +18 -1
  44. package/templates/auto-update/cm-update.sh +51 -0
@@ -9,7 +9,7 @@ import {digest,id,json,need,shape,text,validIdentity,requestFor,failureCode} fro
9
9
  import {createFixReproduction,inspectFixReproduction} from './reproduce.mjs';
10
10
  import {inspectFixLearning} from './learning.mjs';
11
11
  import {createFixCausePackage} from './cause-package.mjs';
12
- import {validateCauseReviewer,inspectCauseRegistration,inspectCauseResult,causeExpectation} from './cause-invocation.mjs';
12
+ import {validateCauseReviewer,inspectCauseRegistration,inspectCauseResult,causeExpectation,fixHostContexts} from './cause-invocation.mjs';
13
13
  import {inspectProviderCauseReview} from '../cm-ai/provider-review-observation.mjs';
14
14
  import {publishCauseEvidence} from './cause-evidence.mjs';
15
15
  import {createFixRedTest,inspectFixRedTest,verifyFixRedEvidence,redTestFiles} from './red-test.mjs';
@@ -60,7 +60,8 @@ function diagnosis(raw){
60
60
  }
61
61
 
62
62
  export function openFixExecution(options,{bridge=null,prepare=null,causeReview=null,finalReview=null,assertReviewReady=null}={}){
63
- shape(options,['identity','configuration','create',...(Object.hasOwn(options,'specsRoot')?['specsRoot']:[])]);
63
+ shape(options,['identity','configuration','create',...(Object.hasOwn(options,'hostContextId')?['hostContextId']:[]),
64
+ ...(Object.hasOwn(options,'specsRoot')?['specsRoot']:[])]);
64
65
  const {identity,configuration:originalConfiguration,create}=json(options,64*1024);validIdentity(identity);
65
66
  const bare=options.specsRoot==null;
66
67
  need(!Object.hasOwn(originalConfiguration,'archiveMode'),'invalid_fix_config');
@@ -90,7 +91,14 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
90
91
  need(digest(identity)===digest(qaFixIdentity(configuration.qaSource)),'fix_qa_identity_mismatch');
91
92
  if(Object.hasOwn(configuration,'runtime'))need(configuration.runtime==='claude'
92
93
  &&(!configuration.causeReview||configuration.causeReview.provider==='claude'),'invalid_runtime');
93
- if(configuration.causeReview)validateCauseReviewer(configuration.causeReview,configuration.hostContextId);
94
+ // configuration is the durable run record: its hostContextId stays the session
95
+ // that created the run, so stored bytes and the store fingerprint never move.
96
+ // options.hostContextId is the live session; reviewConfiguration carries both so
97
+ // a resumed run keeps issuing and replaying grants without impersonating either.
98
+ const liveHostContextId=options.hostContextId??configuration.hostContextId;id(liveHostContextId);
99
+ const hostContextIds=[...new Set([configuration.hostContextId,liveHostContextId])];
100
+ const reviewConfiguration=hostContextIds.length>1?{...configuration,hostContextIds}:configuration;
101
+ if(configuration.causeReview)validateCauseReviewer(configuration.causeReview,hostContextIds);
94
102
  if(Object.hasOwn(configuration,'applicableAgentFiles')){
95
103
  need(Array.isArray(configuration.applicableAgentFiles),'invalid_input');
96
104
  for(const file of configuration.applicableAgentFiles){
@@ -134,14 +142,14 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
134
142
  const finalCycleRecord=(row,suffix)=>new RegExp(`^fix-final-(?:recovery-(?:[1-9]\\d*-)?)?${suffix}$`).test(row.id);
135
143
  const publishCause=(inspectOnly=false)=>{
136
144
  const records=store.snapshot().records;
137
- return publishCauseEvidence({specsRoot:evidenceSpecsRoot,configuration,inspectOnly,
145
+ return publishCauseEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,
138
146
  registration:records.find(record=>record.id==='fix-cause-registered')?.payload,
139
147
  started:records.find(record=>record.id==='fix-cause-started')?.payload.providerThreadId??null,
140
148
  result:records.find(record=>record.id==='fix-cause-result')?.payload});
141
149
  };
142
150
  const publishFinal=(inspectOnly=false)=>{
143
151
  const records=store.snapshot().records;
144
- return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration,inspectOnly,
152
+ return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,
145
153
  causeThread:records.find(record=>record.id==='fix-cause-started')?.payload.providerThreadId??null,
146
154
  registration:finalRecord(records,'registered')?.payload,
147
155
  started:finalRecord(records,'started')?.payload.providerThreadId??null,
@@ -151,7 +159,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
151
159
  const records=store.snapshot().records;
152
160
  const failed=records.find(row=>row.id==='fix-walkthrough-result')?.payload;
153
161
  const regression=records.find(row=>row.id==='fix-post-regression-result')?.payload;
154
- return {configuration:fixFinalReviewConfiguration(configuration,records.find(row=>row.id==='fix-cause-started')?.payload.providerThreadId??null),
162
+ return {configuration:fixFinalReviewConfiguration(reviewConfiguration,records.find(row=>row.id==='fix-cause-started')?.payload.providerThreadId??null),
155
163
  registration:finalRecord(records,'registered')?.payload,
156
164
  started:finalRecord(records,'started')?.payload.providerThreadId??null,
157
165
  result:finalRecord(records,'result')?.payload,
@@ -164,7 +172,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
164
172
  };
165
173
  const publishRevisionFinal=(inspectOnly=false)=>{
166
174
  const records=store.snapshot().records;
167
- return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration,inspectOnly,reviewFeedback:revisionFeedback(),
175
+ return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,reviewFeedback:revisionFeedback(),
168
176
  registration:records.find(row=>row.id==='fix-revision-final-registered')?.payload,
169
177
  started:records.find(row=>row.id==='fix-revision-final-started')?.payload.providerThreadId??null,
170
178
  result:records.find(row=>row.id==='fix-revision-final-result')?.payload});
@@ -448,7 +456,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
448
456
  }
449
457
  if(record.id==='fix-revision-final-registered'){
450
458
  need(revision&&stage==='revision_final_review_required'&&record.kind==='intent','fix_history_invalid');
451
- revisionFinalRegistration=inspectFixFinalRegistration(record.payload,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity));
459
+ revisionFinalRegistration=inspectFixFinalRegistration(record.payload,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds));
452
460
  const {handoff:boundHandoff,packageDigest,...body}=revisionFinalRegistration.request.payload.reviewPackage;
453
461
  need(digest(body)===(revisionLearningPackage??revisionRetrospectivePackage).packageDigest&&boundHandoff.sha256===revisionHandoff.handoffSha256
454
462
  &&boundHandoff.path===path.basename(revisionHandoffPath()),'final_package_mismatch');
@@ -458,13 +466,13 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
458
466
  need(revision&&pending==='revision_final_review'&&revisionFinalStarted===null&&record.kind==='result','fix_history_invalid');
459
467
  need(record.payload.providerThreadId!==finalRecovery?.providerThreadId,'final_context_mismatch');
460
468
  shape(record.payload,['providerThreadId']);id(record.payload.providerThreadId);
461
- const config=fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity);
462
- need(![config.hostContextId,config.reviewer.contextId,...config.reviewer.excludedThreadIds].includes(record.payload.providerThreadId),'final_context_mismatch');
469
+ const config=fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds);
470
+ need(![...fixHostContexts(config),config.reviewer.contextId,...config.reviewer.excludedThreadIds].includes(record.payload.providerThreadId),'final_context_mismatch');
463
471
  revisionFinalStarted=record.payload.providerThreadId;continue;
464
472
  }
465
473
  if(record.id==='fix-revision-final-result'){
466
474
  need(revision&&pending==='revision_final_review'&&record.kind==='result','fix_history_invalid');
467
- revisionFinalResult=inspectFixFinalResult(record.payload,revisionFinalRegistration,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity),revisionFinalStarted);
475
+ revisionFinalResult=inspectFixFinalResult(record.payload,revisionFinalRegistration,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds),revisionFinalStarted);
468
476
  pending=null;stage=revisionFinalResult.observationStatus==='completed'
469
477
  ?revisionFinalResult.review.verdict==='approved'?'revision_final_review_evidence_required':revisionFinalResult.review.verdict==='changes_requested'?'revision_review_limit_reached':'revision_final_review_blocked':'unknown';continue;
470
478
  }
@@ -528,7 +536,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
528
536
  }
529
537
  if(record.id==='fix-final-registered'){
530
538
  need(stage==='final_review_required'&&record.kind==='intent','fix_history_invalid');
531
- finalRegistration=inspectFixFinalRegistration(record.payload,fixFinalReviewConfiguration(configuration,started));
539
+ finalRegistration=inspectFixFinalRegistration(record.payload,fixFinalReviewConfiguration(reviewConfiguration,started));
532
540
  need(!finalInvocations.has(finalRegistration.request.invocationId),'fix_review_recovery_mismatch');
533
541
  finalInvocations.add(finalRegistration.request.invocationId);
534
542
  if(finalRecovery)need(finalRegistration.request.invocationId!==finalRecovery.invocationId
@@ -541,14 +549,14 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
541
549
  if(record.id==='fix-final-started'){
542
550
  need(pending==='final_review'&&finalStarted===null&&record.kind==='result','fix_history_invalid');
543
551
  shape(record.payload,['providerThreadId']);id(record.payload.providerThreadId);
544
- const config=fixFinalReviewConfiguration(configuration,started);
552
+ const config=fixFinalReviewConfiguration(reviewConfiguration,started);
545
553
  need(!finalThreads.has(record.payload.providerThreadId),'final_context_mismatch');
546
- need(![config.hostContextId,config.reviewer.contextId,...config.reviewer.excludedThreadIds].includes(record.payload.providerThreadId),'final_context_mismatch');
554
+ need(![...fixHostContexts(config),config.reviewer.contextId,...config.reviewer.excludedThreadIds].includes(record.payload.providerThreadId),'final_context_mismatch');
547
555
  finalStarted=record.payload.providerThreadId;finalThreads.add(finalStarted);continue;
548
556
  }
549
557
  if(record.id==='fix-final-result'){
550
558
  need(pending==='final_review'&&record.kind==='result','fix_history_invalid');
551
- finalResult=inspectFixFinalResult(record.payload,finalRegistration,fixFinalReviewConfiguration(configuration,started),finalStarted);
559
+ finalResult=inspectFixFinalResult(record.payload,finalRegistration,fixFinalReviewConfiguration(reviewConfiguration,started),finalStarted);
552
560
  pending=null;stage=finalResult.observationStatus==='completed'
553
561
  ?finalResult.review.verdict==='approved'?'final_review_evidence_required':finalResult.review.verdict==='changes_requested'?'final_review_changes_requested':'final_review_blocked':'unknown';
554
562
  continue;
@@ -682,7 +690,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
682
690
  need((stage==='cause_review_required'||late&&pending===null&&(!finalRegistration||prior)
683
691
  &&correctionStages.includes(resumeStage))
684
692
  &&cause===null&&record.kind==='intent','fix_history_invalid');
685
- cause=inspectCauseRegistration(record.payload,configuration);
693
+ cause=inspectCauseRegistration(record.payload,reviewConfiguration);
686
694
  const pkg=cause.request.payload.reviewPackage;
687
695
  if(late){
688
696
  let repairPackage=null;
@@ -720,11 +728,11 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
720
728
  if(record.id==='fix-cause-started'){
721
729
  need(pending==='cause_review'&&started===null&&record.kind==='result','fix_history_invalid');
722
730
  shape(record.payload,['providerThreadId']);id(record.payload.providerThreadId);started=record.payload.providerThreadId;
723
- need(![configuration.hostContextId,configuration.causeReview.contextId,finalStarted,...configuration.causeReview.excludedThreadIds].includes(started),'cause_registration_mismatch');continue;
731
+ need(![...hostContextIds,configuration.causeReview.contextId,finalStarted,...configuration.causeReview.excludedThreadIds].includes(started),'cause_registration_mismatch');continue;
724
732
  }
725
733
  if(record.id==='fix-cause-result'){
726
734
  need(pending==='cause_review'&&record.kind==='result','fix_history_invalid');
727
- causeResult=inspectCauseResult(record.payload,cause,configuration,started);pending=null;
735
+ causeResult=inspectCauseResult(record.payload,cause,reviewConfiguration,started);pending=null;
728
736
  stage=causeResult.observationStatus!=='completed'?'unknown':causeResult.review.verdict==='approved'
729
737
  ?(causeResumeStage??(diagnosed.status==='design_change'?'design_change_required':'red_test_required'))
730
738
  :causeResult.review.verdict==='changes_requested'?'rediagnosis_required':'cause_review_blocked';continue;
@@ -1110,7 +1118,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1110
1118
  const checks=reviewChecks(revising?start.revisionRegression:start.regression),selectedHandoff=revising?revisionHandoffPath():handoffPath();
1111
1119
  const pkg=createReviewPackage({root:configuration.reproduction.cwd,baseline,checks,handoffPath:selectedHandoff});
1112
1120
  if(start.finalReviewRecovery&&!revising)need(pkg.packageDigest===start.finalReviewRecovery.packageDigest,'fix_review_recovery_drift');
1113
- const run=createFixFinalReview({reviewPackage:pkg,configuration:revising?fixRevisionReviewConfiguration(revisionFeedback(),start.revision.nextIdentity):fixFinalReviewConfiguration(configuration,start.causeReview?.providerThreadId??null),
1121
+ const run=createFixFinalReview({reviewPackage:pkg,configuration:revising?fixRevisionReviewConfiguration(revisionFeedback(),start.revision.nextIdentity,hostContextIds):fixFinalReviewConfiguration(reviewConfiguration,start.causeReview?.providerThreadId??null),
1114
1122
  timeoutMs:configuration.reproduction.timeoutMs},finalReview);
1115
1123
  const controller=new AbortController();active=controller;let registered=false;
1116
1124
  try{
@@ -1403,7 +1411,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1403
1411
  if(types.isPromise(grant)){grant.catch(()=>{});need(false,'cause_authorization_invalid');}
1404
1412
  need(!controller.signal.aborted,'cancelled');
1405
1413
  if(digest(grant)===digest({status:'denied',code:'permission_denied'}))return {...project(),reason:'permission_denied'};
1406
- const registration=inspectCauseRegistration({request,authorizationAt,registeredAt:Date.now(),grant},configuration);
1414
+ const registration=inspectCauseRegistration({request,authorizationAt,registeredAt:Date.now(),grant},reviewConfiguration);
1407
1415
  append('fix-cause-registered','intent',registration);
1408
1416
  registered=true;
1409
1417
  const dispatchAt=Date.now();need(dispatchAt>=registration.registeredAt&&dispatchAt<grant.expiresAt,'grant_expired');
@@ -1414,7 +1422,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1414
1422
  try{
1415
1423
  const event=json(raw,64*1024);
1416
1424
  inspectProviderCauseReview(JSON.stringify({...observation({status:'failed',code:'in_progress'}),events:[...events,event]}),
1417
- JSON.stringify(causeExpectation(request,configuration)));
1425
+ JSON.stringify(causeExpectation(request,reviewConfiguration)));
1418
1426
  if(event.event==='thread.started'){
1419
1427
  append('fix-cause-started','result',{providerThreadId:event.provider_thread});started=event.provider_thread;
1420
1428
  }
@@ -1434,7 +1442,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1434
1442
  }finally{sealed=true;controller.signal.removeEventListener('abort',rejectAbort);}
1435
1443
  if(invalid||controller.signal.aborted)return project();
1436
1444
  const value={dispatchAt,observation:observation(timedOut?{status:'failed',code:'timeout'}:result)};
1437
- inspectCauseResult(value,registration,configuration,started);
1445
+ inspectCauseResult(value,registration,reviewConfiguration,started);
1438
1446
  append('fix-cause-result','result',value);
1439
1447
  if(project().causeReview?.observationStatus==='completed')publishCause();
1440
1448
  return project();
@@ -6,22 +6,25 @@ import {digest,json,need,shape,requestFor,validIdentity,failureCode} from '../cm
6
6
  import {readReviewPackage} from '../cm-ai/review-package.mjs';
7
7
  import {validateReviewDispatchGrant} from '../cm-ai/durable-runner-state.mjs';
8
8
  import {inspectProviderReview} from '../cm-ai/provider-review-observation.mjs';
9
- import {validateCauseReviewer} from './cause-invocation.mjs';
9
+ import {validateCauseReviewer,fixHostContexts} from './cause-invocation.mjs';
10
10
  import {inspectFixWalkthrough} from './walkthrough.mjs';
11
11
  import {inspectFixRegressionFailure} from './regression-evidence.mjs';
12
12
 
13
13
  // Preserve old persisted configuration bytes: reuse its reviewer model settings,
14
14
  // never its cause-review authority or actual provider thread.
15
15
  export function fixFinalReviewConfiguration(configuration,causeThread=null){
16
- const base=validateCauseReviewer(configuration.causeReview,configuration.hostContextId);
17
- return {hostContextId:configuration.hostContextId,reviewer:{...base,reviewerId:'fix-final-reviewer',
16
+ const hosts=fixHostContexts(configuration);
17
+ const base=validateCauseReviewer(configuration.causeReview,hosts);
18
+ return {hostContextId:configuration.hostContextId,...(hosts.length>1?{hostContextIds:hosts}:{}),
19
+ reviewer:{...base,reviewerId:'fix-final-reviewer',
18
20
  adapterId:`${base.provider}-review-adapter`,contextId:'fix-final-review-context',
19
21
  excludedThreadIds:[...new Set([...base.excludedThreadIds,...(causeThread?[causeThread]:[])])]}};
20
22
  }
21
23
 
22
24
  function expectation(request,configuration){
23
- return {request,developerThreadId:configuration.hostContextId,
24
- excludedThreadIds:[...configuration.reviewer.excludedThreadIds,request.contextId]};
25
+ const hosts=fixHostContexts(configuration);
26
+ return {request,developerThreadId:hosts[0],
27
+ excludedThreadIds:[...configuration.reviewer.excludedThreadIds,...hosts.slice(1),request.contextId]};
25
28
  }
26
29
 
27
30
  // Immediate diagnostics only, never approval or replay evidence. Do not expose
@@ -43,14 +46,14 @@ function reviewDiagnostic(phase,error,event=null){
43
46
  }
44
47
  export function inspectFixFinalRegistration(raw,configuration){
45
48
  const value=json(raw,12*1024*1024);shape(value,['request','authorizationAt','registeredAt','grant']);
46
- const reviewer=validateCauseReviewer(configuration.reviewer,configuration.hostContextId,configuration.reviewFeedback?34:33),request=value.request;
49
+ const reviewer=validateCauseReviewer(configuration.reviewer,fixHostContexts(configuration),configuration.reviewFeedback?34:33),request=value.request;
47
50
  need(request.provider===reviewer.provider&&request.requestedModel===reviewer.requestedModel&&request.contextId===reviewer.contextId,'final_registration_mismatch');
48
51
  const pkg=readReviewPackage(request.payload.reviewPackage);
49
52
  const previous=configuration.reviewFeedback?inspectFixRepairReview(configuration.reviewFeedback,pkg.identity):null;
50
53
  need(pkg.handoff&&digest(request.payload.priorReview)===digest(previous?.review??null),'final_handoff_required');
51
54
  if(previous)need(reviewer.excludedThreadIds.includes(previous.providerThreadId),'final_context_mismatch');
52
55
  validateReviewDispatchGrant(value.grant,{request,reviewerId:reviewer.reviewerId,adapterId:reviewer.adapterId,
53
- packageDigest:pkg.packageDigest,hostContextIds:[configuration.hostContextId],authorizationAt:value.authorizationAt,registeredAt:value.registeredAt});
56
+ packageDigest:pkg.packageDigest,hostContextIds:fixHostContexts(configuration),authorizationAt:value.authorizationAt,registeredAt:value.registeredAt});
54
57
  inspectProviderReview(JSON.stringify({version:1,kind:'cm-provider-review-observation',requestDigest:request.requestDigest,
55
58
  events:[],result:{status:'failed',code:'in_progress'}}),JSON.stringify(expectation(request,configuration)));
56
59
  return value;
@@ -96,16 +99,20 @@ export function inspectFixRepairReview(raw,nextIdentity){
96
99
  ...(value.regressionFailure?{regressionFailure:value.regressionFailure}:{})});
97
100
  }
98
101
 
99
- export function fixRevisionReviewConfiguration(feedback,nextIdentity){
102
+ // The persisted feedback carries the configuration of the session that recorded
103
+ // it. A later session passes its own host contexts so its grants are accepted too.
104
+ export function fixRevisionReviewConfiguration(feedback,nextIdentity,hostContextIds=null){
100
105
  const previous=inspectFixRepairReview(feedback,nextIdentity),config=json(feedback.configuration);
101
- return {...config,reviewer:{...config.reviewer,excludedThreadIds:[...new Set([...config.reviewer.excludedThreadIds,previous.providerThreadId])]},reviewFeedback:feedback};
106
+ return {...config,...(hostContextIds&&hostContextIds.length>1?{hostContextIds}:{}),reviewer:{...config.reviewer,excludedThreadIds:[...new Set([...config.reviewer.excludedThreadIds,previous.providerThreadId])]},reviewFeedback:feedback};
102
107
  }
103
108
 
104
109
  export function createFixFinalReview({reviewPackage,configuration,timeoutMs},{authorize,run}){
105
110
  const pkg=readReviewPackage(reviewPackage);need(pkg.handoff,'final_handoff_required');
106
- const config=json(configuration,12*1024*1024);shape(config,['hostContextId','reviewer',...(Object.hasOwn(config,'reviewFeedback')?['reviewFeedback']:[])]);
111
+ const config=json(configuration,12*1024*1024);shape(config,['hostContextId','reviewer',
112
+ ...(Object.hasOwn(config,'hostContextIds')?['hostContextIds']:[]),
113
+ ...(Object.hasOwn(config,'reviewFeedback')?['reviewFeedback']:[])]);
107
114
  const previous=config.reviewFeedback?inspectFixRepairReview(config.reviewFeedback,pkg.identity):null;
108
- const reviewer=validateCauseReviewer(config.reviewer,config.hostContextId,previous?34:33);
115
+ const reviewer=validateCauseReviewer(config.reviewer,fixHostContexts(config),previous?34:33);
109
116
  if(previous)need(reviewer.excludedThreadIds.includes(previous.providerThreadId),'final_context_mismatch');
110
117
  need(Number.isInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=3600000,'invalid_timeout');
111
118
  need(typeof authorize==='function'&&typeof run==='function','final_review_unavailable');
@@ -94,10 +94,23 @@ export function finishFix({specsRoot,identity,configuration,status,registeredAt}
94
94
  need(['closeout_required','closeout_incomplete','completed'].includes(status.stage),'fix_closeout_unavailable');
95
95
  requireCloseoutEvidence(status);
96
96
  const feature=`fix-${identity.taskId.slice(6)}`,reviewsDir=path.join(specsRoot,'.reviews');
97
+ // Git delivery is its own logged event (runtime/logging.md: commit/push/
98
+ // pull_request), not a precondition of task completion: cm-ai completes under
99
+ // every delivery mode and leaves Git to the executor, and this skill's own
100
+ // SKILL.md documents branch and draft-mr for fix too. Demanding 'diff' here
101
+ // instead locked out every project cm-init generates for a repo with a remote,
102
+ // and the obvious workaround was impossible: findConfig only reads the project
103
+ // root, which is inside the business snapshot, so editing the mode invalidates
104
+ // the very N5 evidence re-checked three lines below.
105
+ // Pinning the mode rather than dictating it keeps the contract from shifting
106
+ // while completion records are written. Today the snapshot notices such an edit
107
+ // first, so this is the local, explicit statement of that invariant rather than
108
+ // its only enforcement; it stays correct if the snapshot rules ever change.
109
+ const delivery=loadConfig({projectRoot:configuration.reproduction.cwd}).policies.delivery;
97
110
  const verify=()=>{
98
111
  const owned=assertOwned();if(types.isPromise(owned))Promise.prototype.then.call(owned,()=>{},()=>{});
99
112
  need(owned===undefined,'fix_owner_required');
100
- need(loadConfig({projectRoot:configuration.reproduction.cwd}).policies.delivery==='diff','fix_delivery_authorization_required');
113
+ need(loadConfig({projectRoot:configuration.reproduction.cwd}).policies.delivery===delivery,'fix_delivery_changed');
101
114
  const gate=checkN5({handoff:path.join(reviewsDir,`${feature}-${identity.taskId}-a${identity.attempt}-handoff.json`),
102
115
  reviewsDir,feature,task:identity.taskId,projectRoot:configuration.reproduction.cwd,requireLearning:true});
103
116
  need(digest(gate)===digest(status.n5.gate),'n5_evidence_changed');
@@ -45,7 +45,13 @@ const git=(project,args,optional=false)=>{
45
45
  need(!result.error&&result.status===0,'git_read_failed');return result.stdout;
46
46
  };
47
47
  const paths=bytes=>decode(bytes).split('\0').filter(Boolean);
48
- const protectedPath=file=>/(^|\/)(?:\.env(?:\..*)?|credentials[^/]*|id_rsa|id_ed25519)(\/|$)|\.(?:pem|key|p12|pfx)$/i.test(file);
48
+ // `.env` 家族默认按真实密钥保护、不读取。但 .env.example / .env.sample /
49
+ // .env.template / .env.dist 是提交进仓库、给人照抄的占位文件,恰恰需要被扫到——
50
+ // 真密钥误写进示例文件是常见事故。这里只放行这四种明确的示例后缀,
51
+ // 其余 .env.* (.env.local、.env.production 等)保持保护。
52
+ const exampleEnv=/(^|\/)\.env\.(?:example|sample|template|dist)$/i;
53
+ const protectedPath=file=>!exampleEnv.test(file)
54
+ &&/(^|\/)(?:\.env(?:\..*)?|credentials[^/]*|id_rsa|id_ed25519)(\/|$)|\.(?:pem|key|p12|pfx)$/i.test(file);
49
55
  const controlPath=file=>/(^|\/)(?:\.gitignore|\.gitleaks[^/]*|\.semgrep[^/]*|osv-scanner\.toml|\.gitmodules)$/.test(file);
50
56
  const maps=['docs/architecture.md','docs/codebase-context/00-index.md','docs/codebase-context/07-business-logic.md'];
51
57
  const locks=/(^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|poetry\.lock|Pipfile\.lock|requirements[^/]*\.txt|Cargo\.lock|go\.sum|Gemfile\.lock|composer\.lock|packages\.lock\.json)$/;
@@ -13,7 +13,7 @@ import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
13
13
  import {validateHostWorkflowConfiguration,featureHasBrowserCases,readBrowserCapability} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
14
14
  import {digest,json,need,shape} from '../runtime/js/cm-ai/effect-contract.mjs';
15
15
 
16
- const usage='cm-ai-batch-host.mjs serve --config PATH --host-context ID --allow-development [--runtime codex|claude] [--review-config PATH] [--allow-review FEATURE/TASK:1|2]... [--allow-qa] [--browser-qa available|unavailable] [--protected-conversation-config PATH | --protected-config PATH] [--allow-provider-development FEATURE/TASK:1|2]...';
16
+ const usage='cm-ai-batch-host.mjs serve --config PATH --host-context ID --allow-development [--runtime codex|claude] [--review-config PATH] [--allow-review FEATURE/TASK:1|2]... [--allow-qa] [--rerun-unknown-qa | --rerun-blocked-qa] [--verification-precheck] [--browser-qa available|unavailable] [--protected-conversation-config PATH | --protected-config PATH] [--allow-provider-development FEATURE/TASK:1|2]...';
17
17
  const safeCode=error=>typeof error?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(error.code)?error.code:'batch_host_failed';
18
18
 
19
19
  async function memberReviewConfiguration(batch,definition,review,runtime){
@@ -26,9 +26,12 @@ async function memberReviewConfiguration(batch,definition,review,runtime){
26
26
  fs.mkdirSync(directory,{recursive:true,mode:0o700});
27
27
  need(fs.realpathSync(directory)===directory,'invalid_preflight_cache');
28
28
  const file=path.join(directory,`preflight-${definition.identity.taskId}.json`);
29
+ // The cached file stays a pure preflight diagnostic. The reviewer budget is a
30
+ // launch argument, so it is applied on return and never written to the cache.
31
+ const withTimeout=config=>review.timeoutMs==null?config:{...config,timeoutMs:review.timeoutMs};
29
32
  if(fs.existsSync(file)){
30
33
  const info=fs.lstatSync(file);need(info.isFile()&&!info.isSymbolicLink(),'invalid_preflight_cache');
31
- try{const cached=readConversationReviewConfiguration(file);if(matches(cached))return cached;}
34
+ try{const cached=readConversationReviewConfiguration(file);if(matches(cached))return withTimeout(cached);}
32
35
  catch{/* Invalid or obsolete diagnostics require a fresh loopback, never a rewritten fingerprint. */}
33
36
  }
34
37
  const config=await runReviewPreflight(definition,{model:review.model,runtime,disabledSkills:review.disabledSkills});
@@ -36,12 +39,12 @@ async function memberReviewConfiguration(batch,definition,review,runtime){
36
39
  const temporary=`${file}.${process.pid}.tmp`;
37
40
  fs.writeFileSync(temporary,JSON.stringify(config)+'\n',{flag:'wx',mode:0o600});
38
41
  try{fs.renameSync(temporary,file);}finally{if(fs.existsSync(temporary))fs.unlinkSync(temporary);}
39
- return config;
42
+ return withTimeout(config);
40
43
  }catch{need(false,'review_preflight_failed');}
41
44
  }
42
45
 
43
46
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
44
- if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nOptional --protected-conversation-config PATH uses the shared current-host scoped text proposals and native sandbox checks; {checkCommands,timeoutMs}. No extra model call, same Codex/Claude runtime and per-task Review permissions. Optional --protected-config PATH {model,checkCommands,timeoutMs} enables CLI development only for per-task --allow-provider-development FEATURE/TASK:1|2 grants; mutually exclusive with --protected-conversation-config. Optional bundle.bootstraps maps approved bootstrap task keys to {selection}; --allow-bootstrap-write grants only those fixed instruction/scaffold steps. Optional batch.codeProjects uses prefixed paths and checks with codeProject per command; one task remains one completion gate.\nBatch entry requires a clean Git main checkout (including untracked files); batch_main_dirty lists dirty files before any task or worktree starts. Serial tasks are committed automatically before batch_handoff, with task_commit recording the SHA (null if unchanged). Terminal parallel members preserve WIP on their retained branches and fall back once to serial generation 2 after ready members merge.\n');return 0;}
47
+ if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nOptional --protected-conversation-config PATH uses the shared current-host scoped text proposals and native sandbox checks; {checkCommands,timeoutMs}. No extra model call, same Codex/Claude runtime and per-task Review permissions. Optional --protected-config PATH {model,checkCommands,timeoutMs} enables CLI development only for per-task --allow-provider-development FEATURE/TASK:1|2 grants; mutually exclusive with --protected-conversation-config. Optional bundle.bootstraps maps approved bootstrap task keys to {selection}; --allow-bootstrap-write grants only those fixed instruction/scaffold steps. Optional batch.codeProjects uses prefixed paths and checks with codeProject per command; one task remains one completion gate.\nOptional --review-config PATH is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 60000). It is independent of --protected-conversation-config/--protected-config and wins over their timeoutMs for the reviewer, so a review that exceeds the default can be raised without switching development mode. It is not part of the authorized configuration digest, so a resumed run may raise it after review_transport_timeout.\nOptional --rerun-unknown-qa / --rerun-blocked-qa carry the same single-task QA recovery into a batch and require --allow-qa; they are mutually exclusive. A batch has no --mode, so each task applies the flag only when it resumes an existing run and has a QA executor; a created run or a task without QA ignores it rather than failing the whole batch. Semantics, limits and the qaRound cap are the single-task ones, unchanged.\nOptional --verification-precheck sends the written verification of the task and the collected checks back as a verification_precheck request before any handoff or review package is built. It may only block: a requirement reported unsatisfied stops the task at blocked / verification_precheck_failed with pendingAction resume and spends no review round. Passing it is not an approval, writes no receipt and does not replace the independent review. A task with no written verification is unaffected.\nBatch entry requires a clean Git main checkout (including untracked files); batch_main_dirty lists dirty files before any task or worktree starts. Serial tasks are committed automatically before batch_handoff, with task_commit recording the SHA (null if unchanged). Terminal parallel members preserve WIP on their retained branches and fall back once to serial generation 2 after ready members merge.\n');return 0;}
45
48
  let bridge;
46
49
  try{
47
50
  need(argv.length>=6&&argv[0]==='serve'&&argv[1]==='--config'&&argv[3]==='--host-context'
@@ -59,10 +62,14 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
59
62
  }
60
63
  need(keys.length===Object.keys(workflows).length&&keys.every(key=>Object.hasOwn(workflows,key)),'workflow_task_mismatch');
61
64
  for(const key of keys)if(workflows[key]!==null)validateHostWorkflowConfiguration(workflows[key]);
62
- let review=null,allowQa=false,allowBootstrap=false,runtime=null,protection=null,providerConfig=null,browserQaFlag;const approvals=new Set(),developments=new Map();
65
+ let review=null,allowQa=false,allowBootstrap=false,runtime=null,protection=null,providerConfig=null,browserQaFlag;
66
+ let rerunUnknownQa=false,rerunBlockedQa=false,verificationPrecheck=false;const approvals=new Set(),developments=new Map();
63
67
  for(let index=6;index<argv.length;index++){
64
68
  const name=argv[index];
65
69
  if(name==='--allow-qa'){need(!allowQa,'invalid_arguments');allowQa=true;}
70
+ else if(name==='--rerun-unknown-qa'){need(!rerunUnknownQa,'invalid_arguments');rerunUnknownQa=true;}
71
+ else if(name==='--rerun-blocked-qa'){need(!rerunBlockedQa,'invalid_arguments');rerunBlockedQa=true;}
72
+ else if(name==='--verification-precheck'){need(!verificationPrecheck,'invalid_arguments');verificationPrecheck=true;}
66
73
  else if(name==='--browser-qa'){
67
74
  need(browserQaFlag===undefined&&typeof argv[index+1]==='string','invalid_arguments');browserQaFlag=argv[++index];
68
75
  }
@@ -98,6 +105,10 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
98
105
  readBrowserCapability(browserQaFlag,keys.some(key=>workflows[key]?.qa!=null
99
106
  &&featureHasBrowserCases(batch.specsDir,key.slice(0,key.lastIndexOf('/')),batch.codeProject)));
100
107
  need(!approvals.size||review!==null,'review_configuration_required');
108
+ // Same two guards as the single-task host. A batch has no --mode, so the
109
+ // per-task resume check lives in createCmAiBatch rather than here.
110
+ need(!(rerunUnknownQa&&rerunBlockedQa),'qa_recovery_authorization_required');
111
+ need(!(rerunUnknownQa||rerunBlockedQa)||allowQa,'qa_recovery_authorization_required');
101
112
  need(allowQa||!Object.values(workflows).some(item=>item?.qa!=null),'qa_authorization_required');
102
113
  bridge=createHostToolBridge();
103
114
  // The current conversation transport accepts one outstanding host call.
@@ -109,12 +120,13 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
109
120
  }};
110
121
  const driver=createCmAiBatch({configuration:batch,logHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
111
122
  runtime:runtime??'codex',checkCommands:(providerConfig??protection)?.checkCommands??null,checkTimeoutMs:(providerConfig??protection)?.timeoutMs??60000,
123
+ rerunUnknownQa,rerunBlockedQa,
112
124
  executionFor:async(definition,{parallelMember=false}={})=>{
113
125
  const key=`${definition.feature}/${definition.identity.taskId}`;
114
126
  const attempts=[1,2].filter(attempt=>approvals.has(`${key}:${attempt}`));
115
127
  const memberReview=parallelMember?await memberReviewConfiguration(batch,definition,review,runtime??'codex'):review;
116
128
  const execution=createConversationExecution(definition,argv[4],parallelMember?memberBridge:bridge,memberReview,attempts,workflows[key],allowQa,runtime??'codex',
117
- {parallelMember,batchWorkflowsDigest:digest(bootstraps?{workflows,bootstraps}:workflows),qaLogHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
129
+ {parallelMember,...(verificationPrecheck?{verificationPrecheck:true}:{}),batchWorkflowsDigest:digest(bootstraps?{workflows,bootstraps}:workflows),qaLogHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
118
130
  // A protected CLI config also protects unauthorized tasks: they stay on the
119
131
  // current-session transport but with the same sandbox checks (protected-text edits).
120
132
  ...(protection?{protection}:providerConfig?{protection:{checkCommands:providerConfig.checkCommands,timeoutMs:providerConfig.timeoutMs}}:{}),
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import {spawnSync} from 'node:child_process';
6
6
  import {fileURLToPath} from 'node:url';
7
7
  import {openControlRun,validateRunDefinition} from './cm-ai-run.mjs';
8
+ import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
8
9
  import {digest,json,shape,need,id,hex} from '../runtime/js/cm-ai/effect-contract.mjs';
9
10
  import {scanRows,findCmAiQaDecision,latestCmAiQaRun} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
10
11
  import {checkParallelWrite} from './cm-task-gate.mjs';
@@ -14,7 +15,8 @@ import {inspectRunClosure} from './cm-log-event.mjs';
14
15
 
15
16
  const writer=fileURLToPath(new URL('./cm-log-event.py',import.meta.url));
16
17
  const key=task=>`${task.feature}/${task.taskId}`;
17
- export function createCmAiBatch({configuration,executionFor,logHome,runtime='codex',checkCommands=null,checkTimeoutMs=60000}){
18
+ export function createCmAiBatch({configuration,executionFor,logHome,runtime='codex',checkCommands=null,checkTimeoutMs=60000,
19
+ rerunUnknownQa=false,rerunBlockedQa=false}){
18
20
  const config=json(configuration);
19
21
  shape(config,['version','repositoryId','batchId','specsDir','codeProject','tasks',...['codeProjects','parallel'].filter(name=>Object.hasOwn(config,name))]);
20
22
  need(config.version===1);id(config.repositoryId);id(config.batchId);need(config.batchId.length>=8);
@@ -83,8 +85,14 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
83
85
  }
84
86
  async function open(taskKey){
85
87
  const definition=plans.get(taskKey),state=path.join(config.specsDir,'.reviews','.execution',definition.identity.runId,'state.json');
86
- return openControlRun(definition,fs.existsSync(state)?'resume':'create',await executionForKey(taskKey),
87
- membership.has(taskKey)?{parallelSelection:{version:1,group:membership.get(taskKey).map(key=>plans.get(key).identity.taskId)}}:{});
88
+ const mode=fs.existsSync(state)?'resume':'create',execution=await executionForKey(taskKey);
89
+ // QA recovery is rejected outright for a created run or one without a QA
90
+ // executor. Passing it to every task would take down the unrelated ones, so
91
+ // only the tasks the flag can legally apply to receive it.
92
+ const recovery=mode==='resume'&&execution?.qaExecutor&&(rerunUnknownQa||rerunBlockedQa)
93
+ ? {rerunUnknownQa,rerunBlockedQa} : {};
94
+ return openControlRun(definition,mode,execution,{...recovery,
95
+ ...(membership.has(taskKey)?{parallelSelection:{version:1,group:membership.get(taskKey).map(key=>plans.get(key).identity.taskId)}}:{})});
88
96
  }
89
97
  function parallelProgress(rows){
90
98
  const done=new Set(),ready=new Map(),merging=new Map(),blocked=new Map();let stopped=false,code=null;
@@ -188,7 +196,7 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
188
196
  };
189
197
  for(let round=status.identity.attempt;round<=2;round++){
190
198
  if(status.code===null&&['ready','changes_requested'].includes(status.state)
191
- ||status.state==='blocked'&&status.code==='developer_result_invalid')await call('start');
199
+ ||developmentRetryable(status))await call('start');
192
200
  if(['reported','advanced'].includes(status.outcome)&&(status.code===null&&status.state==='awaiting_review'
193
201
  ||status.state==='pending_review'&&status.code==='review_transport_timeout'))await call('decision');
194
202
  if(status.outcome==='advanced'&&status.code===null&&status.state==='changes_requested'&&status.identity.attempt===round+1)continue;
@@ -0,0 +1,116 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ import {checklistGaps, extractChecklists} from '../runtime/js/cm-ai/checklist-coverage.mjs';
8
+ import {deliveredText} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
9
+
10
+ // The task line that produced the real rejection on the reference project.
11
+ const realTask = '- [x] T-003: 按 `test-cases.json` 的 browser 用例在本地 `npm start` 页面走查:'
12
+ + '3 条未完成时点击后全部变为已完成且 `剩余 0 项`、空列表与全部已完成时按钮 disabled、'
13
+ + '删除一条后点击本按钮撤销仍可用;并核对既有筛选/搜索/编辑/删除/清理已完成/清空全部不回归\n'
14
+ + '- T-003: 浏览器证据必须逐用例标注输入方式(鼠标/键盘/脚本)与起始存储;'
15
+ + '按钮状态类用例必须分别记录**列表为空、有未完成、全部已完成**三种情形下 `#mark-all-done` 的 `disabled` 值。';
16
+
17
+ // Exactly the rows the independent reviewer quoted from the rejected round.
18
+ const rejectedEvidence = '## 已有功能不回归\n单条添加 删除 撤销删除 筛选「已完成」 搜索「王」 计数 剩余 N 项\n'
19
+ + '本文档不涉及需要打桩的确认对话框。';
20
+
21
+ // This is the case the whole module exists for. A human reviewer spent a full
22
+ // round finding it; the entries are countable, so it should not have cost one.
23
+ test('the entries the real review rejected over are reported before dispatch', () => {
24
+ const gaps = checklistGaps(realTask, rejectedEvidence);
25
+ const regression = gaps.find(gap => gap.total === 6);
26
+ assert.notEqual(regression, undefined, '六项回归清单未被识别');
27
+ assert.deepEqual([...regression.missing], ['编辑', '清理已完成', '清空全部不回归']);
28
+ });
29
+
30
+ test('a delivery covering every entry reports no gap for that list', () => {
31
+ const complete = '筛选 搜索 编辑 删除 清理已完成 清空全部 都走查过了';
32
+ assert.equal(checklistGaps('核对既有筛选/搜索/编辑/删除/清理已完成/清空全部不回归', complete).length, 0);
33
+ });
34
+
35
+ // The first and last entry absorb the surrounding sentence, so verbatim
36
+ // matching alone would report a gap for a delivery that actually covered them.
37
+ test('the first and last entry match without their absorbed sentence context', () => {
38
+ const task = '核对既有筛选/搜索/清空全部不回归';
39
+ assert.equal(checklistGaps(task, '筛选 搜索 清空全部').length, 0);
40
+ assert.deepEqual([...checklistGaps(task, '筛选 清空全部')[0].missing], ['搜索']);
41
+ });
42
+
43
+ test('both enumeration forms are extracted and nothing else is invented', () => {
44
+ const lists = extractChecklists(realTask);
45
+ const sizes = lists.map(list => list.items.length).sort();
46
+ assert.deepEqual(sizes, [3, 3, 6], `抽出来的清单不对: ${JSON.stringify(lists)}`);
47
+ // A two-entry pair is a phrase, not a checklist.
48
+ assert.deepEqual([...extractChecklists('核对新增/删除两条路径')], []);
49
+ assert.deepEqual([...extractChecklists('')], []);
50
+ assert.deepEqual([...extractChecklists(null)], []);
51
+ });
52
+
53
+ test('results are frozen so a caller cannot edit the report into a pass', () => {
54
+ const gaps = checklistGaps('核对既有筛选/搜索/编辑不回归', '筛选');
55
+ assert.throws(() => { gaps.push({}); }, TypeError);
56
+ assert.throws(() => { gaps[0].missing.length = 0; }, TypeError);
57
+ });
58
+
59
+ // Advisory means advisory. Wording differs legitimately between the task and
60
+ // the evidence, and this module must never be read as a verdict.
61
+ test('a synonym the module cannot see is reported as a gap, which is why it only advises', () => {
62
+ const gaps = checklistGaps('分别记录**列表为空、有未完成、全部已完成**三种情形', '空列表 有未完成 全部已完成');
63
+ assert.deepEqual([...gaps[0].missing], ['列表为空'],
64
+ '这是已知的误报:同义不同字。它只提醒,不判定。');
65
+ });
66
+
67
+ test('oversized or non-string input yields no report instead of throwing', () => {
68
+ assert.deepEqual([...checklistGaps('核对既有筛选/搜索/编辑不回归', '')], []);
69
+ assert.deepEqual([...checklistGaps('核对既有筛选/搜索/编辑不回归', null)], []);
70
+ assert.deepEqual([...extractChecklists('核'.repeat(512 * 1024 + 1))], []);
71
+ // An evidence body past the cap is truncated, not rejected.
72
+ const padded = 'x'.repeat(512 * 1024) + '编辑';
73
+ assert.deepEqual([...checklistGaps('核对既有筛选/搜索/编辑不回归', padded)[0].missing],
74
+ ['核对既有筛选', '搜索', '编辑不回归']);
75
+ });
76
+
77
+ function fixture(fn) {
78
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cm-checklist-')));
79
+ try { return fn(root); } finally { fs.rmSync(root, { recursive: true, force: true }); }
80
+ }
81
+
82
+ // The evidence usually lives in a scope file, not in the gate answers, so the
83
+ // reminder is worthless if it cannot read the delivery.
84
+ test('scope files are read, and unreadable entries contribute nothing rather than failing', () => fixture(root => {
85
+ fs.writeFileSync(path.join(root, 'qa.md'), '编辑 清理已完成');
86
+ fs.writeFileSync(path.join(root, 'big.md'), 'x'.repeat(256 * 1024 + 1));
87
+ fs.writeFileSync(path.join(root, 'binary.md'), Buffer.from([0x61, 0x00, 0x62]));
88
+ fs.symlinkSync('qa.md', path.join(root, 'link.md'));
89
+ fs.mkdirSync(path.join(root, 'dir.md'));
90
+
91
+ assert.match(deliveredText(root, ['qa.md']), /清理已完成/);
92
+ for (const entry of ['big.md', 'binary.md', 'link.md', 'dir.md', 'missing.md', '', 42])
93
+ assert.equal(deliveredText(root, [entry]), '', `${entry} 不该被读进来`);
94
+ assert.equal(deliveredText(root, 'not-an-array'), '');
95
+ assert.equal(deliveredText(null, ['qa.md']), '');
96
+ // A readable file still counts when it sits beside unreadable ones.
97
+ assert.match(deliveredText(root, ['missing.md', 'qa.md', 'big.md']), /编辑/);
98
+ }));
99
+
100
+ // The gate's verdict is the gate's. This module reports alongside it.
101
+ test('the gate emits the reminder without letting it change the verdict', async () => {
102
+ const source = fs.readFileSync(new URL('../runtime/js/cm-ai/host-conversation-execution.mjs',
103
+ import.meta.url), 'utf8');
104
+ const gate = /const verificationGate=options\.verificationPrecheck===true\?([\s\S]*?)\n \}:null;/.exec(source);
105
+ assert.notEqual(gate, null, 'verificationGate not found');
106
+ assert.match(gate[1], /checklistGaps\(/);
107
+ assert.match(gate[1], /diagnostic:'checklist_coverage'/);
108
+ assert.match(gate[1], /advisory:true/);
109
+ // The returned verdict must still be the gate's own, unqualified by coverage.
110
+ assert.match(gate[1], /return \{satisfied:verdict\.satisfied\};/);
111
+ assert.equal(/satisfied:verdict\.satisfied&&/.test(gate[1]), false,
112
+ 'coverage was folded into the verdict; it must stay advisory');
113
+ // Any throw inside the reminder must not reach the caller.
114
+ const reminder = /\/\/ Advisory only\.[\s\S]*?\}catch\{[^}]*\}/.exec(gate[1]);
115
+ assert.notEqual(reminder, null, 'the reminder is not wrapped in its own try/catch');
116
+ });