@aibyzero/cm-workflow 0.16.0 → 0.16.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.
Files changed (38) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +61 -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 +8 -2
  7. package/docs/untested-branches.md +73 -0
  8. package/package.json +1 -1
  9. package/runtime/js/cm-ai/checklist-coverage.mjs +70 -0
  10. package/runtime/js/cm-ai/effect-contract.mjs +37 -3
  11. package/runtime/js/cm-ai/host-conversation-execution.mjs +37 -1
  12. package/runtime/js/cm-ai/metrics-table.mjs +22 -0
  13. package/runtime/js/cm-ai/review-package.mjs +29 -3
  14. package/runtime/js/cm-ai/task-runner.mjs +10 -4
  15. package/runtime/js/cm-fix/cause-invocation.mjs +17 -4
  16. package/runtime/js/cm-fix/execution.mjs +41 -24
  17. package/runtime/js/cm-fix/final-review.mjs +18 -11
  18. package/runtime/js/cm-fix/finish.mjs +14 -1
  19. package/runtime/js/cm-fix/layout.mjs +26 -0
  20. package/runtime/js/cm-fix/metrics.mjs +2 -4
  21. package/runtime/js/cm-fix/walkthrough.mjs +8 -2
  22. package/runtime/js/cm-refactor/workflow.mjs +3 -2
  23. package/runtime/js/cm-security/scan.mjs +7 -1
  24. package/scripts/audit-untested-enums.mjs +59 -0
  25. package/scripts/cm-ai-checklist-coverage.test.mjs +116 -0
  26. package/scripts/cm-ai-execution-diagnostic.test.mjs +25 -0
  27. package/scripts/cm-ai-verification-gate.test.mjs +18 -0
  28. package/scripts/cm-fix-cross-session-host.test.mjs +100 -0
  29. package/scripts/cm-fix-execution.test.mjs +74 -0
  30. package/scripts/cm-fix-host.mjs +11 -5
  31. package/scripts/cm-fix-metrics.test.mjs +32 -0
  32. package/scripts/cm-fix-repair-owner.test.mjs +22 -18
  33. package/scripts/cm-release-smoke.sh +14 -0
  34. package/scripts/cm-review-dependency-snapshot.test.mjs +85 -0
  35. package/scripts/cm-review-inventory.test.mjs +42 -0
  36. package/scripts/cm-security.test.mjs +24 -0
  37. package/skills/cm-fix/references/js-host.md +18 -1
  38. 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';
@@ -29,13 +29,13 @@ import {publishFixFinalEvidence} from './final-review-evidence.mjs';
29
29
  import {checkN5} from '../../../scripts/cm-task-gate.mjs';
30
30
  import {readProjectInstructionContext} from '../cm-ai/cm-ai-context-refresh.mjs';
31
31
  import {publishFixDossier,publishFixObservationDossier,readFixObservationArchive} from './dossier.mjs';
32
- import {readFixWalkthrough,fixWalkthroughBinding,createFixWalkthrough,inspectFixWalkthrough,verifyFixWalkthroughEvidence} from './walkthrough.mjs';
32
+ import {readFixWalkthrough,fixWalkthroughBinding,createFixWalkthrough,inspectFixWalkthrough,verifyFixWalkthroughEvidence,walkthroughCoversDiagnosis} from './walkthrough.mjs';
33
33
  import {logFixEvent} from './start.mjs';
34
34
  import {inspectFixInvestigation,fixInvestigationRequest} from './investigation.mjs';
35
35
  import {finishFix,fixCompletionProjection,eventsAt,isFixObservationExit} from './finish.mjs';
36
36
  import {specsPermissionArgs} from '../cm-ai/codex-config.mjs';
37
37
  import {protectedFixBridge} from './protected-edits.mjs';
38
- import {fixArchiveRoot,fixDossierRelative} from './layout.mjs';
38
+ import {fixArchiveRoot,fixDossierRelative,assertFixEvidenceNamesFree} from './layout.mjs';
39
39
  import {isVisual,verifyVisualCarrier} from './visual.mjs';
40
40
 
41
41
  const observationId=(kind,cycle)=>`fix-observation-${cycle===1?'':cycle+'-'}${kind}`;
@@ -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){
@@ -121,6 +129,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
121
129
  shape(configuration.repair,['scope','requirements']);need(runBaseline,'baseline_configuration_required');
122
130
  validateDeveloperScope(configuration.repair.scope);
123
131
  }
132
+ if(create)assertFixEvidenceNamesFree(evidenceSpecsRoot,identity,configuration);
124
133
  if(create&&Object.hasOwn(configuration,'qaSource'))inspectFixQaSource({specsRoot,identity,configuration});
125
134
  const store=openExecutionStore({specsRoot,identity:{repositoryId:identity.repositoryId,runId:identity.runId},create,
126
135
  fingerprints:{workflow:digest('cm-fix-stages-v1'),config:digest(configuration),inputs:digest(identity)}});
@@ -134,14 +143,14 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
134
143
  const finalCycleRecord=(row,suffix)=>new RegExp(`^fix-final-(?:recovery-(?:[1-9]\\d*-)?)?${suffix}$`).test(row.id);
135
144
  const publishCause=(inspectOnly=false)=>{
136
145
  const records=store.snapshot().records;
137
- return publishCauseEvidence({specsRoot:evidenceSpecsRoot,configuration,inspectOnly,
146
+ return publishCauseEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,
138
147
  registration:records.find(record=>record.id==='fix-cause-registered')?.payload,
139
148
  started:records.find(record=>record.id==='fix-cause-started')?.payload.providerThreadId??null,
140
149
  result:records.find(record=>record.id==='fix-cause-result')?.payload});
141
150
  };
142
151
  const publishFinal=(inspectOnly=false)=>{
143
152
  const records=store.snapshot().records;
144
- return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration,inspectOnly,
153
+ return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,
145
154
  causeThread:records.find(record=>record.id==='fix-cause-started')?.payload.providerThreadId??null,
146
155
  registration:finalRecord(records,'registered')?.payload,
147
156
  started:finalRecord(records,'started')?.payload.providerThreadId??null,
@@ -151,7 +160,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
151
160
  const records=store.snapshot().records;
152
161
  const failed=records.find(row=>row.id==='fix-walkthrough-result')?.payload;
153
162
  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),
163
+ return {configuration:fixFinalReviewConfiguration(reviewConfiguration,records.find(row=>row.id==='fix-cause-started')?.payload.providerThreadId??null),
155
164
  registration:finalRecord(records,'registered')?.payload,
156
165
  started:finalRecord(records,'started')?.payload.providerThreadId??null,
157
166
  result:finalRecord(records,'result')?.payload,
@@ -164,7 +173,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
164
173
  };
165
174
  const publishRevisionFinal=(inspectOnly=false)=>{
166
175
  const records=store.snapshot().records;
167
- return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration,inspectOnly,reviewFeedback:revisionFeedback(),
176
+ return publishFixFinalEvidence({specsRoot:evidenceSpecsRoot,configuration:reviewConfiguration,inspectOnly,reviewFeedback:revisionFeedback(),
168
177
  registration:records.find(row=>row.id==='fix-revision-final-registered')?.payload,
169
178
  started:records.find(row=>row.id==='fix-revision-final-started')?.payload.providerThreadId??null,
170
179
  result:records.find(row=>row.id==='fix-revision-final-result')?.payload});
@@ -448,7 +457,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
448
457
  }
449
458
  if(record.id==='fix-revision-final-registered'){
450
459
  need(revision&&stage==='revision_final_review_required'&&record.kind==='intent','fix_history_invalid');
451
- revisionFinalRegistration=inspectFixFinalRegistration(record.payload,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity));
460
+ revisionFinalRegistration=inspectFixFinalRegistration(record.payload,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds));
452
461
  const {handoff:boundHandoff,packageDigest,...body}=revisionFinalRegistration.request.payload.reviewPackage;
453
462
  need(digest(body)===(revisionLearningPackage??revisionRetrospectivePackage).packageDigest&&boundHandoff.sha256===revisionHandoff.handoffSha256
454
463
  &&boundHandoff.path===path.basename(revisionHandoffPath()),'final_package_mismatch');
@@ -458,13 +467,13 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
458
467
  need(revision&&pending==='revision_final_review'&&revisionFinalStarted===null&&record.kind==='result','fix_history_invalid');
459
468
  need(record.payload.providerThreadId!==finalRecovery?.providerThreadId,'final_context_mismatch');
460
469
  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');
470
+ const config=fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds);
471
+ need(![...fixHostContexts(config),config.reviewer.contextId,...config.reviewer.excludedThreadIds].includes(record.payload.providerThreadId),'final_context_mismatch');
463
472
  revisionFinalStarted=record.payload.providerThreadId;continue;
464
473
  }
465
474
  if(record.id==='fix-revision-final-result'){
466
475
  need(revision&&pending==='revision_final_review'&&record.kind==='result','fix_history_invalid');
467
- revisionFinalResult=inspectFixFinalResult(record.payload,revisionFinalRegistration,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity),revisionFinalStarted);
476
+ revisionFinalResult=inspectFixFinalResult(record.payload,revisionFinalRegistration,fixRevisionReviewConfiguration(revisionFeedback(),revision.nextIdentity,hostContextIds),revisionFinalStarted);
468
477
  pending=null;stage=revisionFinalResult.observationStatus==='completed'
469
478
  ?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
479
  }
@@ -528,7 +537,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
528
537
  }
529
538
  if(record.id==='fix-final-registered'){
530
539
  need(stage==='final_review_required'&&record.kind==='intent','fix_history_invalid');
531
- finalRegistration=inspectFixFinalRegistration(record.payload,fixFinalReviewConfiguration(configuration,started));
540
+ finalRegistration=inspectFixFinalRegistration(record.payload,fixFinalReviewConfiguration(reviewConfiguration,started));
532
541
  need(!finalInvocations.has(finalRegistration.request.invocationId),'fix_review_recovery_mismatch');
533
542
  finalInvocations.add(finalRegistration.request.invocationId);
534
543
  if(finalRecovery)need(finalRegistration.request.invocationId!==finalRecovery.invocationId
@@ -541,14 +550,14 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
541
550
  if(record.id==='fix-final-started'){
542
551
  need(pending==='final_review'&&finalStarted===null&&record.kind==='result','fix_history_invalid');
543
552
  shape(record.payload,['providerThreadId']);id(record.payload.providerThreadId);
544
- const config=fixFinalReviewConfiguration(configuration,started);
553
+ const config=fixFinalReviewConfiguration(reviewConfiguration,started);
545
554
  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');
555
+ need(![...fixHostContexts(config),config.reviewer.contextId,...config.reviewer.excludedThreadIds].includes(record.payload.providerThreadId),'final_context_mismatch');
547
556
  finalStarted=record.payload.providerThreadId;finalThreads.add(finalStarted);continue;
548
557
  }
549
558
  if(record.id==='fix-final-result'){
550
559
  need(pending==='final_review'&&record.kind==='result','fix_history_invalid');
551
- finalResult=inspectFixFinalResult(record.payload,finalRegistration,fixFinalReviewConfiguration(configuration,started),finalStarted);
560
+ finalResult=inspectFixFinalResult(record.payload,finalRegistration,fixFinalReviewConfiguration(reviewConfiguration,started),finalStarted);
552
561
  pending=null;stage=finalResult.observationStatus==='completed'
553
562
  ?finalResult.review.verdict==='approved'?'final_review_evidence_required':finalResult.review.verdict==='changes_requested'?'final_review_changes_requested':'final_review_blocked':'unknown';
554
563
  continue;
@@ -682,7 +691,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
682
691
  need((stage==='cause_review_required'||late&&pending===null&&(!finalRegistration||prior)
683
692
  &&correctionStages.includes(resumeStage))
684
693
  &&cause===null&&record.kind==='intent','fix_history_invalid');
685
- cause=inspectCauseRegistration(record.payload,configuration);
694
+ cause=inspectCauseRegistration(record.payload,reviewConfiguration);
686
695
  const pkg=cause.request.payload.reviewPackage;
687
696
  if(late){
688
697
  let repairPackage=null;
@@ -720,11 +729,11 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
720
729
  if(record.id==='fix-cause-started'){
721
730
  need(pending==='cause_review'&&started===null&&record.kind==='result','fix_history_invalid');
722
731
  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;
732
+ need(![...hostContextIds,configuration.causeReview.contextId,finalStarted,...configuration.causeReview.excludedThreadIds].includes(started),'cause_registration_mismatch');continue;
724
733
  }
725
734
  if(record.id==='fix-cause-result'){
726
735
  need(pending==='cause_review'&&record.kind==='result','fix_history_invalid');
727
- causeResult=inspectCauseResult(record.payload,cause,configuration,started);pending=null;
736
+ causeResult=inspectCauseResult(record.payload,cause,reviewConfiguration,started);pending=null;
728
737
  stage=causeResult.observationStatus!=='completed'?'unknown':causeResult.review.verdict==='approved'
729
738
  ?(causeResumeStage??(diagnosed.status==='design_change'?'design_change_required':'red_test_required'))
730
739
  :causeResult.review.verdict==='changes_requested'?'rediagnosis_required':'cause_review_blocked';continue;
@@ -752,9 +761,17 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
752
761
  diagnosed=diagnosis(record.payload.value);
753
762
  stage=diagnosed.status==='needs_evidence'?'observation':diagnosed.status==='design_change'?'cause_review_required':
754
763
  diagnosed.crossLayer||diagnosed.affectedModules.length>=3?'cause_review_required':'red_test_required';
764
+
755
765
  }
756
766
  }
757
767
  }
768
+ // 走查声明的模块和诊断对不上,这一轮无论如何走不到收尾。原来要等走查那一步才
769
+ // 发现,而那已经在花钱做完独立审查之后——整轮白跑。诊断一落盘就判得出来。
770
+ // 只在「刚诊断完、还没往下走」时改阶段:已经跑过头的旧记录保持原样。回放循环
771
+ // 会拿当前阶段去校验下一条记录,所以这个判断必须放在循环之后,不能插在循环里。
772
+ if(configuration.walkthrough&&diagnosed?.status==='diagnosed'
773
+ &&['red_test_required','cause_review_required'].includes(stage)
774
+ &&!walkthroughCoversDiagnosis(configuration.walkthrough,diagnosed))stage='walkthrough_configuration_mismatch';
758
775
  if(causeResult?.review?.verdict==='approved'&&stage!=='cancelled'&&repairBaseline===null){
759
776
  try{
760
777
  const current=createFixCausePackage({codeProject:configuration.reproduction.cwd,defect:configuration.defect,
@@ -1110,7 +1127,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1110
1127
  const checks=reviewChecks(revising?start.revisionRegression:start.regression),selectedHandoff=revising?revisionHandoffPath():handoffPath();
1111
1128
  const pkg=createReviewPackage({root:configuration.reproduction.cwd,baseline,checks,handoffPath:selectedHandoff});
1112
1129
  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),
1130
+ const run=createFixFinalReview({reviewPackage:pkg,configuration:revising?fixRevisionReviewConfiguration(revisionFeedback(),start.revision.nextIdentity,hostContextIds):fixFinalReviewConfiguration(reviewConfiguration,start.causeReview?.providerThreadId??null),
1114
1131
  timeoutMs:configuration.reproduction.timeoutMs},finalReview);
1115
1132
  const controller=new AbortController();active=controller;let registered=false;
1116
1133
  try{
@@ -1403,7 +1420,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1403
1420
  if(types.isPromise(grant)){grant.catch(()=>{});need(false,'cause_authorization_invalid');}
1404
1421
  need(!controller.signal.aborted,'cancelled');
1405
1422
  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);
1423
+ const registration=inspectCauseRegistration({request,authorizationAt,registeredAt:Date.now(),grant},reviewConfiguration);
1407
1424
  append('fix-cause-registered','intent',registration);
1408
1425
  registered=true;
1409
1426
  const dispatchAt=Date.now();need(dispatchAt>=registration.registeredAt&&dispatchAt<grant.expiresAt,'grant_expired');
@@ -1414,7 +1431,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1414
1431
  try{
1415
1432
  const event=json(raw,64*1024);
1416
1433
  inspectProviderCauseReview(JSON.stringify({...observation({status:'failed',code:'in_progress'}),events:[...events,event]}),
1417
- JSON.stringify(causeExpectation(request,configuration)));
1434
+ JSON.stringify(causeExpectation(request,reviewConfiguration)));
1418
1435
  if(event.event==='thread.started'){
1419
1436
  append('fix-cause-started','result',{providerThreadId:event.provider_thread});started=event.provider_thread;
1420
1437
  }
@@ -1434,7 +1451,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
1434
1451
  }finally{sealed=true;controller.signal.removeEventListener('abort',rejectAbort);}
1435
1452
  if(invalid||controller.signal.aborted)return project();
1436
1453
  const value={dispatchAt,observation:observation(timedOut?{status:'failed',code:'timeout'}:result)};
1437
- inspectCauseResult(value,registration,configuration,started);
1454
+ inspectCauseResult(value,registration,reviewConfiguration,started);
1438
1455
  append('fix-cause-result','result',value);
1439
1456
  if(project().causeReview?.observationStatus==='completed')publishCause();
1440
1457
  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');
@@ -15,3 +15,29 @@ export function fixArchiveRoot(specsRoot,cwd,create=false){
15
15
  }
16
16
  export const fixDossierRelative=(configuration,name)=>configuration.archiveMode==='bare'?name:`fixes/${name}`;
17
17
  export const fixDossierDirectory=(root,configuration)=>configuration.archiveMode==='bare'?root:path.join(root,'fixes');
18
+
19
+ // 证据文件名由任务 slug 和轮次拼出来,跟 runId 无关——两次运行用同一个 taskId
20
+ // 就会写同一批文件。这个冲突原本要等到红灯测试去发布输出时才被发现,而那时
21
+ // intent 已经登记,运行留在 unknown 且不可重派,等于一整轮报废。名字在建运行
22
+ // 时就全都算得出来,所以在任何记录落盘之前先拒掉,并说清是哪一个名字被占了。
23
+ // 只在 create 时检查:恢复一次已有的运行,本来就该读到自己写下的证据。
24
+ export function fixEvidenceNames(identity,configuration){
25
+ const slug=/^T-FIX-([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(identity.taskId)?.[1];
26
+ if(!slug)return []; // 非法 taskId 由原有的 invalid_fix_slug 负责,不在这里抢答
27
+ const names=[`fix-${slug}-${identity.taskId}-a${identity.attempt}-handoff.json`,
28
+ `fix-${slug}-${identity.taskId}-r${identity.attempt}.md`];
29
+ // 只列这次配置真的会写的文件,免得拦下根本不会发生的冲突。
30
+ if(configuration.redTest&&configuration.redTest.kind!=='visual')
31
+ names.push(`fix-${slug}-a${identity.attempt}-red-output.md`);
32
+ if(configuration.causeReview)names.push(`fix-${slug}-cause-r1.md`);
33
+ return names;
34
+ }
35
+ export function assertFixEvidenceNamesFree(archiveRoot,identity,configuration){
36
+ const reviews=path.join(archiveRoot,'.reviews');
37
+ for(const name of fixEvidenceNames(identity,configuration)){
38
+ let taken=false;
39
+ try{taken=fs.lstatSync(path.join(reviews,name))!==undefined;}
40
+ catch(error){if(error.code!=='ENOENT'&&error.code!=='ENOTDIR')throw error;}
41
+ need(!taken,'fix_evidence_name_taken');
42
+ }
43
+ }
@@ -5,9 +5,7 @@ import path from 'node:path';
5
5
  import {types} from 'node:util';
6
6
  import {readReviewSourceFiles} from '../cm-ai/review-package.mjs';
7
7
  import {id,need,validIdentity} from '../cm-ai/effect-contract.mjs';
8
-
9
- const header='| 任务 | Feature | 开始 | 结束 | 审查轮次 | 独立审查拦截 | QA | 人工介入(次:原因) |';
10
- const separator='| --- | --- | --- | --- | --- | --- | --- | --- |';
8
+ import {METRICS_HEADER as header,METRICS_SEPARATOR as separator,hasMetricsHeader} from '../cm-ai/metrics-table.mjs';
11
9
  const cell=value=>String(value).replaceAll('|','&#124;').replace(/[\r\n]+/g,' ');
12
10
  const same=(event,identity)=>event.workflow==='cm-fix'&&event.node==='FIX'&&event.run_id===identity.runId
13
11
  &&event.repository_id===identity.repositoryId&&event.task===identity.taskId;
@@ -62,7 +60,7 @@ export function appendFixMetrics({specsRoot,identity,dossierFile},{assertOwned})
62
60
  const current=fs.lstatSync(target);need(!current.isSymbolicLink()&&current.dev===stat.dev&&current.ino===stat.ino&&current.size===stat.size,'metrics_file_changed');
63
61
  owned();return {...record,path:target,deduplicated:true};
64
62
  }
65
- if(before.length)need(content.split(/\r?\n/).includes(header),'metrics_table_invalid');
63
+ if(before.length)need(hasMetricsHeader(content),'metrics_table_invalid');
66
64
  const bytes=Buffer.from((before.length?(content.endsWith('\n')?'':'\n'):`${header}\n${separator}\n`)+record.line+'\n');
67
65
  need(before.length+bytes.length<=1024*1024,'limit_exceeded');owned();
68
66
  const current=fs.lstatSync(target);need(!current.isSymbolicLink()&&current.dev===stat.dev&&current.ino===stat.ino&&current.size===stat.size,'metrics_file_changed');
@@ -29,10 +29,16 @@ export function readFixWalkthrough(raw,cwd){
29
29
  return config;
30
30
  }
31
31
 
32
+ // 走查声明的模块要和诊断结论一一对上。抽成单独的判定,好让诊断刚落盘时就能问一次
33
+ // ——原来只有走查那一步会问,而那已经在花钱做完独立审查之后了。
34
+ export function walkthroughCoversDiagnosis(configuration,diagnosis){
35
+ const covered=new Set(configuration.flows.flatMap(flow=>flow.modules));
36
+ return diagnosis.affectedModules.length===covered.size
37
+ &&diagnosis.affectedModules.every(module=>covered.has(module));
38
+ }
32
39
  export function fixWalkthroughBinding({identity,packageDigest,diagnosis,configuration}){
33
40
  validIdentity(identity);hex(packageDigest);
34
- const covered=new Set(configuration.flows.flatMap(flow=>flow.modules));
35
- need(diagnosis.affectedModules.length===covered.size&&diagnosis.affectedModules.every(module=>covered.has(module)),'walkthrough_module_mismatch');
41
+ need(walkthroughCoversDiagnosis(configuration,diagnosis),'walkthrough_module_mismatch');
36
42
  return json({identity,packageDigest,diagnosisDigest:digest(diagnosis),configurationDigest:digest(configuration)});
37
43
  }
38
44
 
@@ -11,6 +11,7 @@ import {writeImmutableWorkflowFile} from '../cm-ai/review-evidence-file.mjs';
11
11
  import {mergeLessons} from '../cm-ai/cm-ai-learning-writer.mjs';
12
12
  import {readLearningRetrospectiveContent} from '../cm-ai/cm-ai-context-refresh.mjs';
13
13
  import {need,shape,json,digest} from '../cm-ai/effect-contract.mjs';
14
+ import {METRICS_HEADER,hasMetricsHeader} from '../cm-ai/metrics-table.mjs';
14
15
  import {inside,canonicalFuture,snapshotSource} from '../cm-test/source-snapshot.mjs';
15
16
  import {openRefactorRecords,readText,replaceText,sha} from './records.mjs';
16
17
  const nonempty=value=>typeof value==='string'&&value.trim().length>0;
@@ -431,8 +432,8 @@ export function createCmRefactorHost(raw,{call}){
431
432
  await publish('dossier',dossierPath(),'# Refactor dossier\n\n'+markdown({analysis,metricAfter:proposal.metricAfter,changed:proposal.changed,reports,
432
433
  delivery:'diff',hostCalls,commandCount,baselineCount:config.baselineCommands.length,differentialCount:judgeBefore.cases.length,
433
434
  learning:proposal.learning,unfixedDefects:proposal.unfixedDefects,deviations:[],usage}));
434
- if(specs){const header='| 任务 | Feature | 开始 | 结束 | 审查轮次 | 独立审查拦截 | QA | 人工介入(次:原因) |',old=context.metrics;
435
- need(!old||old.split(/\r?\n/).includes(header),'refactor_metrics_format');
435
+ if(specs){const header=METRICS_HEADER,old=context.metrics;
436
+ need(!old||hasMetricsHeader(old),'refactor_metrics_format');
436
437
  const at=await records.effect('finish-time','clock',{},()=>new Date().toISOString());
437
438
  const line=`| ${task} | refactor | ${context.startedAt} | ${at} | ${attempt} | ${interceptions} | 等价通过 | ${calls.filter(entry=>entry.input.kind==='refactor_confirm').length}:人门; delivery-diff; agents=${usage.agentCalls}; host_ms=${usage.hostDurationMs}; estimate_tokens=${usage.estimatedTokens??'unavailable'}; actual_tokens=unavailable; commands=${commandCount} |\n`;
438
439
  await write('metrics',path.join(specs,'METRICS.md'),old,(old??`${header}\n| --- | --- | --- | --- | --- | --- | --- | --- |\n`)+(old&&!old.endsWith('\n')?'\n':'')+line,context.metricsMode);}
@@ -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)$/;
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ // 盘点 runtime 里「只能取这几个值」的枚举,逐个看测试有没有碰过。
3
+ //
4
+ // 为什么要有这个:一轮真实实跑里修掉的四个缺陷是同一个形状——文档承诺了某个选项,
5
+ // 代码里也确实有那条分支,但从来没有测试走过它。交付方式三选一只测了一种、统计表
6
+ // 列名「语义升级」只测了新名字、跨会话恢复一条都没有、iOS 软链接没测过。它们不是
7
+ // 被写坏的,是没人走过。这个脚本把同一形状的其余候选一次性列出来。
8
+ //
9
+ // 输出是候选,不是待办:内部记录类型和 typeof 判断也会被匹配到,人得自己分类。
10
+ // 分好类的结果见 docs/untested-branches.md;改完代码后重跑本脚本对照。
11
+ //
12
+ // node scripts/audit-untested-enums.mjs 列出所有缺覆盖的枚举取值
13
+ // node scripts/audit-untested-enums.mjs --summary 只报数字
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import {fileURLToPath} from 'node:url';
17
+
18
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
19
+ const summaryOnly=process.argv.includes('--summary');
20
+
21
+ const walk=dir=>fs.readdirSync(dir,{withFileTypes:true}).flatMap(entry=>{
22
+ const full=path.join(dir,entry.name);
23
+ return entry.isDirectory()?walk(full):full.endsWith('.mjs')?[full]:[];
24
+ });
25
+
26
+ const tests=fs.readdirSync(path.join(root,'scripts'))
27
+ .filter(name=>name.endsWith('.test.mjs'))
28
+ .map(name=>fs.readFileSync(path.join(root,'scripts',name),'utf8')).join('\n');
29
+ const covered=value=>tests.includes(`'${value}'`)||tests.includes(`"${value}"`);
30
+
31
+ // 只认最常见的一种写法:['a','b'].includes(x)。漏掉别的写法好过误报一堆。
32
+ const pattern=/\[((?:'[a-z][a-z0-9_.-]*',\s*){1,8}'[a-z][a-z0-9_.-]*')\]\.includes\(/g;
33
+ const findings=[];
34
+ for(const file of walk(path.join(root,'runtime/js'))) {
35
+ fs.readFileSync(file,'utf8').split('\n').forEach((line,index)=>{
36
+ for(const match of line.matchAll(pattern)) {
37
+ const values=match[1].split(',').map(value=>value.trim().slice(1,-1));
38
+ const missing=values.filter(value=>!covered(value));
39
+ if(missing.length)findings.push({file:path.relative(root,file),line:index+1,values,missing});
40
+ }
41
+ });
42
+ }
43
+
44
+ const values=new Set(findings.flatMap(finding=>finding.missing));
45
+ if(!summaryOnly) {
46
+ const byModule=new Map();
47
+ for(const finding of findings) {
48
+ const module=finding.file.split('/')[2]??finding.file;
49
+ byModule.set(module,[...(byModule.get(module)??[]),finding]);
50
+ }
51
+ for(const [module,list] of [...byModule].sort((a,b)=>b[1].length-a[1].length)) {
52
+ process.stdout.write(`\n${module} (${list.length} 处)\n`);
53
+ for(const finding of list)
54
+ process.stdout.write(` ${finding.file}:${finding.line} 缺 ${finding.missing.join(',')}`
55
+ +` 枚举 ${finding.values.join('|')}\n`);
56
+ }
57
+ process.stdout.write('\n');
58
+ }
59
+ process.stdout.write(`缺覆盖的枚举取值 ${values.size} 个,分布在 ${findings.length} 处\n`);
@@ -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
+ });