@aibyzero/cm-workflow 0.16.5 → 0.16.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +14 -0
- package/CHANGELOG.md +7 -0
- package/README.md +11 -4
- package/THIRD_PARTY_NOTICES.md +9 -0
- package/VERSION +1 -1
- package/docs/architecture.md +43 -0
- package/docs/execution-optimizations.md +33 -0
- package/docs/external-models.md +114 -0
- package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
- package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
- package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
- package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
- package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
- package/docs/human-correction.md +31 -0
- package/docs/installation.md +28 -7
- package/docs/js-workflow-control.md +48 -0
- package/docs/live-evidence-drivers.md +62 -0
- package/docs/next-steps.md +15 -10
- package/docs/untested-branches.md +27 -4
- package/docs/user-guide.md +23 -8
- package/install-codex.sh +28 -11
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
- package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +79 -20
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +1 -4
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
- package/runtime/js/cm-ai/codex-config.mjs +3 -2
- package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
- package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
- package/runtime/js/cm-ai/drive-bootstrap.mjs +20 -10
- package/runtime/js/cm-ai/drive-core.mjs +9 -3
- package/runtime/js/cm-ai/durable-runner-state.mjs +117 -14
- package/runtime/js/cm-ai/effect-contract.mjs +1 -1
- package/runtime/js/cm-ai/execution-policy.mjs +58 -0
- package/runtime/js/cm-ai/external-group-models.mjs +53 -0
- package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
- package/runtime/js/cm-ai/external-models.mjs +52 -0
- package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
- package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
- package/runtime/js/cm-ai/host-check.mjs +30 -4
- package/runtime/js/cm-ai/host-conversation-execution.mjs +50 -16
- package/runtime/js/cm-ai/host-progress.mjs +80 -0
- package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
- package/runtime/js/cm-ai/host-qa-executor.mjs +2 -2
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
- package/runtime/js/cm-ai/host-session.mjs +1 -1
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
- package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
- package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
- package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
- package/runtime/js/cm-ai/live-evidence.mjs +96 -0
- package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
- package/runtime/js/cm-ai/model_configuration_write.py +214 -0
- package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
- package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
- package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
- package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
- package/runtime/js/cm-ai/provider-usage.mjs +39 -0
- package/runtime/js/cm-ai/review-package.mjs +11 -0
- package/runtime/js/cm-ai/review-presentation.mjs +45 -0
- package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
- package/runtime/js/cm-ai/status-projection.mjs +93 -0
- package/runtime/js/cm-ai/task-runner.mjs +171 -25
- package/runtime/js/cm-ai/tool-preview.mjs +8 -4
- package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
- package/runtime/js/cm-ai/worker-claude.mjs +63 -19
- package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
- package/runtime/js/cm-ai/worker-codex.mjs +45 -19
- package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
- package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
- package/runtime/js/cm-fix/cause-package.mjs +10 -1
- package/runtime/js/cm-fix/execution.mjs +183 -40
- package/runtime/js/cm-fix/final-review.mjs +18 -10
- package/runtime/js/cm-fix/host-review.mjs +25 -6
- package/runtime/js/cm-fix/host.mjs +4 -1
- package/runtime/js/cm-fix/layout.mjs +1 -1
- package/runtime/js/cm-fix/progress.mjs +4 -0
- package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
- package/runtime/js/cm-prd/response-recovery.mjs +23 -0
- package/runtime/js/cm-prd/review-publication.mjs +23 -13
- package/runtime/js/cm-prd/review-time.mjs +29 -0
- package/runtime/js/cm-prd/session.mjs +53 -6
- package/runtime/js/cm-security/finalize.mjs +32 -0
- package/runtime/review.md +5 -0
- package/runtime/task-gates.md +6 -0
- package/runtime/workflow-config.md +10 -1
- package/scripts/cm-ai-batch-drive.mjs +50 -21
- package/scripts/cm-ai-batch-drive.test.mjs +47 -2
- package/scripts/cm-ai-batch-host.mjs +37 -14
- package/scripts/cm-ai-batch-run.mjs +71 -27
- package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
- package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
- package/scripts/cm-ai-bootstrap.test.mjs +80 -87
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
- package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
- package/scripts/cm-ai-drive.mjs +59 -25
- package/scripts/cm-ai-drive.test.mjs +97 -1
- package/scripts/cm-ai-host.mjs +64 -24
- package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
- package/scripts/cm-ai-progress.test.mjs +521 -0
- package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
- package/scripts/cm-ai-review-failure.test.mjs +71 -11
- package/scripts/cm-ai-run.mjs +58 -14
- package/scripts/cm-ai-run.test.mjs +2 -1
- package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
- package/scripts/cm-check-drive.test.mjs +1 -0
- package/scripts/cm-check-runtime.sh +11 -0
- package/scripts/cm-claude-install-layout.test.mjs +26 -0
- package/scripts/cm-claude-probe.test.mjs +1 -1
- package/scripts/cm-codex-plugin-metadata.py +83 -0
- package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
- package/scripts/cm-efficiency-checks.test.mjs +37 -0
- package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
- package/scripts/cm-efficiency-offline.mjs +35 -0
- package/scripts/cm-efficiency-policy.test.mjs +48 -0
- package/scripts/cm-efficiency-presentation.test.mjs +35 -0
- package/scripts/cm-efficiency-response.test.mjs +117 -0
- package/scripts/cm-efficiency-usage.test.mjs +148 -0
- package/scripts/cm-external-batch-host.test.mjs +157 -0
- package/scripts/cm-external-fix-host.test.mjs +281 -0
- package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
- package/scripts/cm-external-group-models.test.mjs +60 -0
- package/scripts/cm-external-model-host.test.mjs +180 -0
- package/scripts/cm-external-model-recovery.test.mjs +108 -0
- package/scripts/cm-external-models.test.mjs +89 -0
- package/scripts/cm-external-process-cleanup.test.mjs +71 -0
- package/scripts/cm-external-qa-fix.test.mjs +170 -0
- package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
- package/scripts/cm-fix-drive.mjs +28 -13
- package/scripts/cm-fix-final-review.test.mjs +11 -6
- package/scripts/cm-fix-host.mjs +17 -10
- package/scripts/cm-fix-protected-edits.test.mjs +12 -0
- package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
- package/scripts/cm-fix-review-budget.test.mjs +7 -1
- package/scripts/cm-host-qa-executor.test.mjs +21 -0
- package/scripts/cm-knowledge-closeout.test.mjs +160 -0
- package/scripts/cm-live-evidence.test.mjs +64 -0
- package/scripts/cm-log-event.mjs +8 -2
- package/scripts/cm-log-event.py +15 -0
- package/scripts/cm-model-setup.mjs +79 -0
- package/scripts/cm-prd-drive.mjs +32 -11
- package/scripts/cm-prd-drive.test.mjs +15 -0
- package/scripts/cm-prd-host.mjs +13 -4
- package/scripts/cm-release-smoke.sh +5 -1
- package/scripts/cm-runtime-i18n.mjs +15 -4
- package/scripts/cm-runtime-install.mjs +8 -4
- package/scripts/cm-runtime.mjs +116 -23
- package/scripts/cm-runtime.test.mjs +121 -12
- package/scripts/cm-security.test.mjs +32 -0
- package/scripts/cm-task-gate-correction.test.mjs +117 -0
- package/scripts/cm-task-gate.mjs +146 -10
- package/scripts/cm-task-gate.py +1 -0
- package/scripts/cm-test-drive.mjs +10 -4
- package/scripts/cm-test-drive.test.mjs +14 -1
- package/scripts/cm-tool-preview-context.test.mjs +12 -0
- package/scripts/cm-usage-report.py +22 -3
- package/scripts/cm-workflow-config.mjs +10 -1
- package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
- package/scripts/fixtures/live-evidence-driver.mjs +35 -0
- package/scripts/fixtures/process-cleanup.mjs +3 -1
- package/scripts/test-cm-native-usage.py +62 -0
- package/scripts/test-external-model-setup.py +91 -0
- package/scripts/test-model-configuration-write.py +201 -0
- package/scripts/test-npm-install.py +10 -1
- package/skills/cm-ai/SKILL.md +2 -2
- package/skills/cm-ai/references/N8-finish.md +5 -0
- package/skills/cm-ai/references/js-host.md +13 -5
- package/skills/cm-ai/references/knowledge-closeout.md +90 -0
- package/skills/cm-fix/SKILL.md +1 -1
- package/skills/cm-fix/references/js-host.md +30 -2
- package/skills/cm-runtime/SKILL.md +29 -6
- package/skills/cm-security/SKILL.md +4 -2
- package/skills/cm-security/references/scan-contract.md +1 -0
- package/templates/cm-workflow.yml +1 -1
package/scripts/cm-task-gate.mjs
CHANGED
|
@@ -472,7 +472,135 @@ function verifyLearningRecord(payload,projectRoot){
|
|
|
472
472
|
throw new GateError('Learning requires a content-bound handoff');
|
|
473
473
|
}
|
|
474
474
|
|
|
475
|
-
|
|
475
|
+
// A single explicitly authorized human continuation after a blocked second
|
|
476
|
+
// round. The ordinary two-attempt chain and original evidence stay intact.
|
|
477
|
+
function correctionPaths(reviewsDir,feature,task){
|
|
478
|
+
requireFeature(feature);requireTaskId(task,'task');
|
|
479
|
+
const info=fs.lstatSync(reviewsDir);
|
|
480
|
+
if(!info.isDirectory()||info.isSymbolicLink())throw new GateError('correction reviews directory must be real');
|
|
481
|
+
const root=fs.realpathSync(reviewsDir),prefix=path.join(root,`${feature}-${task}-human-correction`);
|
|
482
|
+
return {record:prefix+'.json',handoff:prefix+'-handoff.json',review:prefix+'.md',receipt:prefix+'-receipt.json'};
|
|
483
|
+
}
|
|
484
|
+
function absent(file){
|
|
485
|
+
try{fs.lstatSync(file);throw new GateError(`human correction evidence already exists: ${file}`);}
|
|
486
|
+
catch(error){if(error.code!=='ENOENT')throw error;}
|
|
487
|
+
}
|
|
488
|
+
function exactFields(value,fields,label){
|
|
489
|
+
if(value===null||typeof value!=='object'||Array.isArray(value)
|
|
490
|
+
||!sameSet(new Set(Object.keys(value)),new Set(fields)))throw new GateError(`invalid ${label} fields`);
|
|
491
|
+
}
|
|
492
|
+
function correctionHistory({reviewsDir,feature,task,projectRoot}){
|
|
493
|
+
const handoff=expectedHandoff(reviewsDir,feature,task,2);
|
|
494
|
+
requireExpectedHandoff(handoff,{reviewsDir,feature,task,attempt:2});
|
|
495
|
+
const payload=loadHandoff(handoff,{task,attempt:2});
|
|
496
|
+
if(payload.status!=='ready_for_review'||!payload.implementation_sha256)
|
|
497
|
+
throw new GateError('human correction requires a bound ready attempt 2 handoff');
|
|
498
|
+
validateAttemptChain(reviewsDir,feature,task,2,payload,projectRoot);
|
|
499
|
+
const review=reviewPath(reviewsDir,feature,task,2);
|
|
500
|
+
const header=validateReview(review,{task,attempt:2,handoff,changedFiles:payload.changed_files});
|
|
501
|
+
if(header.verdict!=='blocked'||header.independent!=='true')
|
|
502
|
+
throw new GateError('human correction requires an independent blocked round 2');
|
|
503
|
+
const files=[expectedHandoff(reviewsDir,feature,task,1),reviewPath(reviewsDir,feature,task,1),handoff,review];
|
|
504
|
+
const revisions=files.map(file=>fileRevision(file,PREPARATION_FILE_LIMIT));
|
|
505
|
+
requireRevisions(revisions);
|
|
506
|
+
return {payload,revisions,history:revisions.map(item=>({file:path.basename(item.path),
|
|
507
|
+
sha256:createHash('sha256').update(item.bytes).digest('hex')}))};
|
|
508
|
+
}
|
|
509
|
+
function boundCorrectionHandoff(handoff,task,projectRoot){
|
|
510
|
+
const payload=loadHandoff(handoff,{task,attempt:2});
|
|
511
|
+
if(payload.status!=='ready_for_review')throw new GateError('human correction requires ready_for_review');
|
|
512
|
+
verifyLearningRecord(payload,projectRoot);verifyImplementationBinding(payload,{projectRoot});
|
|
513
|
+
return payload;
|
|
514
|
+
}
|
|
515
|
+
export function prepareHumanCorrection(selectors){
|
|
516
|
+
const {reviewsDir,feature,task,handoff,projectRoot,humanAuthorized,reason}=selectors;
|
|
517
|
+
if(humanAuthorized!==true)throw new GateError('human correction requires explicit human authorization');
|
|
518
|
+
if(typeof reason!=='string'||!reason.trim()||reason.length>2000)
|
|
519
|
+
throw new GateError('human correction requires a concrete bounded reason');
|
|
520
|
+
const paths=correctionPaths(reviewsDir,feature,task);
|
|
521
|
+
absent(paths.record);absent(paths.review);absent(paths.receipt);
|
|
522
|
+
const original=correctionHistory(selectors),draft=fileRevision(handoff,PREPARATION_FILE_LIMIT);
|
|
523
|
+
const payload=boundCorrectionHandoff(handoff,task,projectRoot);
|
|
524
|
+
if(!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
|
|
525
|
+
throw new GateError('human correction must retain the full original reviewed file scope');
|
|
526
|
+
requireRevisions([...original.revisions,draft]);
|
|
527
|
+
// Permit only an identical orphan handoff after interruption before record
|
|
528
|
+
// creation. Published authorization/review/receipt are never overwritten.
|
|
529
|
+
try{absent(paths.handoff);fs.writeFileSync(paths.handoff,draft.bytes,{flag:'wx',mode:0o600});}
|
|
530
|
+
catch(error){
|
|
531
|
+
if(error instanceof GateError&&!fs.existsSync(paths.record)&&fileRevision(paths.handoff,PREPARATION_FILE_LIMIT).bytes.equals(draft.bytes)){}
|
|
532
|
+
else throw error;
|
|
533
|
+
}
|
|
534
|
+
const record={version:1,protocol:'cm-human-correction',feature,task,attempt:2,
|
|
535
|
+
authorization:'explicit-human-confirmation',at:new Date().toISOString(),reason:reason.trim(),
|
|
536
|
+
history:original.history,handoff_sha256:sha256(paths.handoff)};
|
|
537
|
+
requireRevisions(original.revisions);
|
|
538
|
+
boundCorrectionHandoff(paths.handoff,task,projectRoot);
|
|
539
|
+
fs.writeFileSync(paths.record,JSON.stringify(record,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
540
|
+
return {outcome:'ready_for_correction_review',correction:paths.record,handoff:paths.handoff,
|
|
541
|
+
review:paths.review,correction_sha256:sha256(paths.record),attempt:2};
|
|
542
|
+
}
|
|
543
|
+
function inspectHumanCorrection(selectors){
|
|
544
|
+
const {reviewsDir,feature,task,correction,handoff,projectRoot}=selectors;
|
|
545
|
+
const paths=correctionPaths(reviewsDir,feature,task);
|
|
546
|
+
if(typeof correction!=='string'||typeof handoff!=='string'||path.resolve(correction)!==paths.record||path.resolve(handoff)!==paths.handoff)
|
|
547
|
+
throw new GateError('human correction must use its fixed evidence paths');
|
|
548
|
+
const pinned=fileRevision(paths.record,PREPARATION_FILE_LIMIT);
|
|
549
|
+
const record=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(pinned.bytes));
|
|
550
|
+
exactFields(record,['version','protocol','feature','task','attempt','authorization','at','reason','history','handoff_sha256'],'human correction');
|
|
551
|
+
if(record.version!==1n||record.protocol!=='cm-human-correction'||record.feature!==feature||record.task!==task
|
|
552
|
+
||record.attempt!==2n||record.authorization!=='explicit-human-confirmation'
|
|
553
|
+
||typeof record.reason!=='string'||!record.reason.trim()||record.reason.length>2000
|
|
554
|
+
||typeof record.at!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(record.at)||Number.isNaN(Date.parse(record.at)))
|
|
555
|
+
throw new GateError('invalid human correction authorization record');
|
|
556
|
+
const original=correctionHistory(selectors);
|
|
557
|
+
if(canonical(record.history)!==canonical(original.history))throw new GateError('human correction history changed');
|
|
558
|
+
const payload=boundCorrectionHandoff(paths.handoff,task,projectRoot);
|
|
559
|
+
fileRevision(paths.handoff,PREPARATION_FILE_LIMIT);
|
|
560
|
+
if(record.handoff_sha256!==sha256(paths.handoff)
|
|
561
|
+
||!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
|
|
562
|
+
throw new GateError('human correction handoff changed or omitted original scope');
|
|
563
|
+
requireRevisions([pinned,...original.revisions]);
|
|
564
|
+
return {paths,payload,correctionDigest:sha256(paths.record)};
|
|
565
|
+
}
|
|
566
|
+
export function publishHumanCorrectionReview(selectors){
|
|
567
|
+
const {paths,payload,correctionDigest}=inspectHumanCorrection(selectors);
|
|
568
|
+
absent(paths.receipt);
|
|
569
|
+
const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
|
|
570
|
+
const header=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
|
|
571
|
+
if(header.independent!=='true'||header.correction_sha256!==correctionDigest)
|
|
572
|
+
throw new GateError('human correction requires fresh independent review bound to the correction record');
|
|
573
|
+
requireRevisions([pinned]);
|
|
574
|
+
inspectHumanCorrection(selectors);
|
|
575
|
+
const receipt={version:1,protocol:'cm-human-correction-review',correction_sha256:correctionDigest,
|
|
576
|
+
review_sha256:createHash('sha256').update(pinned.bytes).digest('hex'),verdict:header.verdict};
|
|
577
|
+
fs.writeFileSync(paths.receipt,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
578
|
+
return {outcome:header.verdict,receipt:paths.receipt};
|
|
579
|
+
}
|
|
580
|
+
function checkHumanCorrection(selectors,stage){
|
|
581
|
+
const {paths,payload,correctionDigest}=inspectHumanCorrection(selectors);
|
|
582
|
+
if(stage==='n4'){
|
|
583
|
+
absent(paths.receipt);
|
|
584
|
+
return {gate:'n4',task:selectors.task,attempt:2,outcome:'ready_for_review',content_bound:true,
|
|
585
|
+
handoff_sha256:sha256(paths.handoff),correction_sha256:correctionDigest};
|
|
586
|
+
}
|
|
587
|
+
const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
|
|
588
|
+
const result=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
|
|
589
|
+
const receiptRevision=fileRevision(paths.receipt,PREPARATION_FILE_LIMIT);
|
|
590
|
+
const receipt=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(receiptRevision.bytes));
|
|
591
|
+
exactFields(receipt,['version','protocol','correction_sha256','review_sha256','verdict'],'human correction receipt');
|
|
592
|
+
if(receipt.version!==1n||receipt.protocol!=='cm-human-correction-review'
|
|
593
|
+
||receipt.correction_sha256!==correctionDigest||result.correction_sha256!==correctionDigest
|
|
594
|
+
||receipt.review_sha256!==sha256(paths.review)||receipt.verdict!==result.verdict)
|
|
595
|
+
throw new GateError('human correction review or receipt changed');
|
|
596
|
+
if(result.verdict!=='approved'||result.independent!=='true')throw new GateError('human correction remains blocked');
|
|
597
|
+
requireRevisions([pinned,receiptRevision]);
|
|
598
|
+
return {gate:'n5',task:selectors.task,attempt:2,outcome:'approved',review:paths.review,
|
|
599
|
+
content_bound:true,correction_sha256:correctionDigest};
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null}){
|
|
603
|
+
if(correction!==null)return checkHumanCorrection({handoff,reviewsDir,feature,task,projectRoot,correction},'n4');
|
|
476
604
|
requireTaskId(task,'task');
|
|
477
605
|
const payload=loadHandoff(handoff,{task});
|
|
478
606
|
if(payload.status!=='ready_for_review')throw new GateError('N4 requires a ready_for_review handoff');
|
|
@@ -484,7 +612,8 @@ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowL
|
|
|
484
612
|
return {gate:'n4',task,attempt,outcome:'ready_for_review',handoff_sha256:sha256(handoff),content_bound:contentBound};
|
|
485
613
|
}
|
|
486
614
|
|
|
487
|
-
export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false}){
|
|
615
|
+
export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null}){
|
|
616
|
+
if(correction!==null)return checkHumanCorrection({handoff,reviewsDir,feature,task,projectRoot,correction},'n5');
|
|
488
617
|
requireTaskId(task,'task');
|
|
489
618
|
const payload=loadHandoff(handoff,{task});
|
|
490
619
|
if(payload.status!=='ready_for_review')throw new GateError('N5 requires a ready_for_review handoff');
|
|
@@ -554,6 +683,10 @@ function pinApproval(selectors){
|
|
|
554
683
|
if(!revisions.some(revision=>revision.path===pinned.path))revisions.push(pinned);
|
|
555
684
|
}
|
|
556
685
|
}
|
|
686
|
+
if(selectors.correction){
|
|
687
|
+
const paths=correctionPaths(reviewsDir,feature,task);
|
|
688
|
+
for(const file of [paths.record,paths.review,paths.receipt])revisions.push(fileRevision(file,preparationReadLimit));
|
|
689
|
+
}
|
|
557
690
|
const approval={...checkN5(selectors)};
|
|
558
691
|
requireRevisions(revisions);
|
|
559
692
|
return {approval,revisions};
|
|
@@ -659,7 +792,7 @@ export function prepareMarkDone(selectors){
|
|
|
659
792
|
if(existing&&!sameRevision(existing,pinned))throw new GateError('conflicting revisions for physical preparation evidence');
|
|
660
793
|
physical.set(pinned.path,pinned);
|
|
661
794
|
}
|
|
662
|
-
if(physical.size>4)throw new GateError('preparation evidence count exceeds bound');
|
|
795
|
+
if(physical.size>(selectors.correction?8:4))throw new GateError('preparation evidence count exceeds bound');
|
|
663
796
|
const plan={
|
|
664
797
|
version:1,protocol:'cm-mark-done-plan',feature:selectors.feature,taskId:selectors.task,
|
|
665
798
|
attempt:approval.attempt,tasksPath:revision.path,mode:Number(BigInt(revision.stat[2])&0o7777n),
|
|
@@ -801,17 +934,18 @@ export function checkParallelWrite({repo,assignment}){
|
|
|
801
934
|
return {gate:'parallel-write',outcome:'isolated',assignments:result};
|
|
802
935
|
}
|
|
803
936
|
|
|
804
|
-
function usage(){return 'usage: cm-task-gate.mjs {validate-handoff|hash-implementation|check-n4|check-n5|prepare-mark-done|verify-mark-done-plan|check-parallel-write} [options]';}
|
|
937
|
+
function usage(){return 'usage: cm-task-gate.mjs {validate-handoff|hash-implementation|check-n4|check-n5|prepare-mark-done|verify-mark-done-plan|prepare-human-correction|publish-human-correction-review|check-parallel-write} [options]';}
|
|
805
938
|
|
|
806
939
|
function parseCli(argv){
|
|
807
940
|
if(argv.length===0||argv.includes('--help')||argv.includes('-h'))return {help:true};
|
|
808
941
|
const command=argv[0];
|
|
809
|
-
if(!['validate-handoff','hash-implementation','check-n4','check-n5','prepare-mark-done','verify-mark-done-plan','mark-done-locked','check-parallel-write'].includes(command))
|
|
942
|
+
if(!['validate-handoff','hash-implementation','check-n4','check-n5','prepare-mark-done','verify-mark-done-plan','mark-done-locked','prepare-human-correction','publish-human-correction-review','check-parallel-write'].includes(command))
|
|
810
943
|
throw new GateError('unsupported command');
|
|
811
944
|
const allowed=command==='validate-handoff'?new Set(['--handoff','--task','--attempt'])
|
|
812
945
|
:command==='hash-implementation'?new Set(['--project-root','--file'])
|
|
813
946
|
:command==='check-parallel-write'?new Set(['--repo','--assignment'])
|
|
814
|
-
:new Set(['--handoff','--reviews-dir','--feature','--task','--project-root','--allow-legacy-unbound','--require-learning',
|
|
947
|
+
:new Set(['--handoff','--reviews-dir','--feature','--task','--project-root','--allow-legacy-unbound','--require-learning','--correction',
|
|
948
|
+
...(command==='prepare-human-correction'?['--human-authorized','--reason']:[]),
|
|
815
949
|
...(['prepare-mark-done','verify-mark-done-plan','mark-done-locked'].includes(command)?['--tasks']:[]),
|
|
816
950
|
...(['verify-mark-done-plan','mark-done-locked'].includes(command)?['--expected-plan-digest']:[])]);
|
|
817
951
|
const required=command==='validate-handoff'?new Set(['--handoff','--task','--attempt'])
|
|
@@ -824,15 +958,15 @@ function parseCli(argv){
|
|
|
824
958
|
for(let index=1;index<argv.length;){
|
|
825
959
|
const flag=argv[index];
|
|
826
960
|
if(!allowed.has(flag))throw new GateError('invalid arguments');
|
|
827
|
-
if(flag==='--allow-legacy-unbound'||flag==='--require-learning'){
|
|
828
|
-
const key=flag==='--require-learning'?'requireLearning':'allowLegacyUnbound';
|
|
961
|
+
if(flag==='--allow-legacy-unbound'||flag==='--require-learning'||flag==='--human-authorized'){
|
|
962
|
+
const key=flag==='--human-authorized'?'humanAuthorized':flag==='--require-learning'?'requireLearning':'allowLegacyUnbound';
|
|
829
963
|
if(Object.hasOwn(values,key))throw new GateError(`duplicate argument: ${flag}`);
|
|
830
964
|
values[key]=true;index++;continue;
|
|
831
965
|
}
|
|
832
966
|
const value=argv[index+1];if(value===undefined)throw new GateError('invalid arguments');
|
|
833
967
|
const key={'--handoff':'handoff','--reviews-dir':'reviewsDir','--feature':'feature','--task':'task','--attempt':'attempt',
|
|
834
968
|
'--tasks':'tasksPath','--expected-plan-digest':'expectedPlanDigest','--repo':'repo','--assignment':'assignment',
|
|
835
|
-
'--project-root':'projectRoot','--file':'file'}[flag];
|
|
969
|
+
'--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason'}[flag];
|
|
836
970
|
if(['assignment','file'].includes(key)){
|
|
837
971
|
if(!Object.hasOwn(values,key))values[key]=[];
|
|
838
972
|
values[key].push(value);
|
|
@@ -845,7 +979,7 @@ function parseCli(argv){
|
|
|
845
979
|
for(const flag of required){
|
|
846
980
|
const key={'--handoff':'handoff','--reviews-dir':'reviewsDir','--feature':'feature','--task':'task','--attempt':'attempt',
|
|
847
981
|
'--tasks':'tasksPath','--expected-plan-digest':'expectedPlanDigest','--repo':'repo','--assignment':'assignment',
|
|
848
|
-
'--project-root':'projectRoot','--file':'file'}[flag];
|
|
982
|
+
'--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason'}[flag];
|
|
849
983
|
if(!Object.hasOwn(values,key))throw new GateError(`missing argument: ${flag}`);
|
|
850
984
|
}
|
|
851
985
|
if(Object.hasOwn(values,'attempt')){
|
|
@@ -866,6 +1000,8 @@ export function main(argv=process.argv.slice(2),environment=process.env){
|
|
|
866
1000
|
result={gate:'handoff',task:payload.task_id,attempt:payload.attempt,outcome:payload.status};
|
|
867
1001
|
}else if(args.command==='hash-implementation')result={gate:'implementation-hash',
|
|
868
1002
|
implementation_sha256:implementationSha256(args.projectRoot,args.file),changed_files:[...args.file].sort((left,right)=>Buffer.compare(Buffer.from(left),Buffer.from(right)))};
|
|
1003
|
+
else if(args.command==='prepare-human-correction')result=prepareHumanCorrection(args);
|
|
1004
|
+
else if(args.command==='publish-human-correction-review')result=publishHumanCorrectionReview(args);
|
|
869
1005
|
else if(args.command==='check-n4')result=checkN4(args);
|
|
870
1006
|
else if(args.command==='check-n5')result=checkN5(args);
|
|
871
1007
|
else if(args.command==='prepare-mark-done')result=prepareMarkDone(args);
|
package/scripts/cm-task-gate.py
CHANGED
|
@@ -271,6 +271,7 @@ def mark_parser() -> argparse.ArgumentParser:
|
|
|
271
271
|
parser.add_argument("--task", required=True)
|
|
272
272
|
parser.add_argument("--tasks", required=True)
|
|
273
273
|
parser.add_argument("--project-root")
|
|
274
|
+
parser.add_argument("--correction")
|
|
274
275
|
parser.add_argument("--allow-legacy-unbound", action="store_true")
|
|
275
276
|
parser.add_argument("--require-learning", action="store_true")
|
|
276
277
|
return parser
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// status, none host.mjs handle status/cancel.
|
|
11
11
|
// cancel
|
|
12
12
|
// host.mjs 自己运行 config.commands 并记录真实退出码;没有 host_request 命令证据。
|
|
13
|
-
// qa_browser
|
|
13
|
+
// qa_browser 由显式 liveEvidence 当前会话执行;未配置时发送前拒绝。
|
|
14
14
|
import fs from 'node:fs';
|
|
15
15
|
import path from 'node:path';
|
|
16
16
|
import {fileURLToPath} from 'node:url';
|
|
@@ -25,6 +25,9 @@ import {inspectDeclaredTestCommand} from '../runtime/js/cm-test/declared-command
|
|
|
25
25
|
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
26
26
|
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
27
27
|
|
|
28
|
+
import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
|
|
29
|
+
|
|
30
|
+
// PLAN.liveEvidence: fresh current-session evidence; see docs/live-evidence-drivers.md.
|
|
28
31
|
const HOST=fileURLToPath(new URL('./cm-test-host.mjs',import.meta.url));
|
|
29
32
|
const KNOWN=new Set(['start','resume','status','cancel']);
|
|
30
33
|
const FILES={change_impact:'change-impact.json',test_cases:'test-cases.json',qa_logic:'qa-logic.json'};
|
|
@@ -34,7 +37,7 @@ const safeFile=file=>fs.existsSync(file)&&fs.lstatSync(file).isFile()&&!fs.lstat
|
|
|
34
37
|
|
|
35
38
|
function main(){
|
|
36
39
|
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
37
|
-
process.stdout.write('用法: cm-test-drive.mjs --plan PLAN.json <start|resume|status|cancel>\nPLAN: config, answers, sessionDir (resume), resolution:null
|
|
40
|
+
process.stdout.write('用法: cm-test-drive.mjs --plan PLAN.json <start|resume|status|cancel>\nPLAN: config, answers, sessionDir (resume), resolution:null。浏览器执行用 PLAN.liveEvidence {directory,kinds:["qa_browser"],timeoutMs?};未配置时预检拒绝。\n');return;
|
|
38
41
|
}
|
|
39
42
|
const {operation,plan,base}=loadPlanFile({name:'cm-test-drive.mjs',known:KNOWN});
|
|
40
43
|
requireFields(plan,['config']);
|
|
@@ -116,9 +119,12 @@ function main(){
|
|
|
116
119
|
return value;
|
|
117
120
|
};
|
|
118
121
|
const answers=preflightAnswers(asks,loadAnswer);
|
|
122
|
+
let live;
|
|
123
|
+
try{live=driverLiveEvidence(plan,{base,protectedRoots:[admission.project,admission.specs],allowedKinds:['qa_browser']});}
|
|
124
|
+
catch(error){stop(2,error.message);}
|
|
119
125
|
if(['start','resume'].includes(operation)&&admission.operation!=='impact'){
|
|
120
126
|
if(admission.modes.includes('browser')&&(admission.operation==='explore'||contract?.cases?.some(item=>item.kind==='browser')))
|
|
121
|
-
stop(2,'缺少真实执行 runner: qa_browser;不能从静态答案文件应答');
|
|
127
|
+
if(!live.has('qa_browser'))stop(2,'缺少真实执行 runner: qa_browser;不能从静态答案文件应答');
|
|
122
128
|
if(admission.modes.includes('logic')&&contract?.cases?.some(item=>item.kind==='logic'))
|
|
123
129
|
answers.qa_logic=loadAnswer('qa_logic');
|
|
124
130
|
}
|
|
@@ -127,6 +133,6 @@ function main(){
|
|
|
127
133
|
&&(['start','resume'].includes(operation)||operation==='status'&&existingSession)
|
|
128
134
|
?['--session-dir',path.resolve(base,plan.sessionDir)]:[])],
|
|
129
135
|
cwd:admission.project,operation,request:operation==='resume'?{resolution:null}:{},answers,paths:{},
|
|
130
|
-
answerFor:row=>answers[row.kind]??null});
|
|
136
|
+
answerFor:(row,answers,paths,control)=>live.has(row.kind)?live.answer(row,control):answers[row.kind]??null});
|
|
131
137
|
}
|
|
132
138
|
main();
|
|
@@ -6,6 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import {spawnSync} from 'node:child_process';
|
|
7
7
|
import {fileURLToPath} from 'node:url';
|
|
8
8
|
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
9
|
+
import {runLiveDriver} from './fixtures/live-evidence-driver.mjs';
|
|
9
10
|
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
10
11
|
const driver=path.join(root,'scripts/cm-test-drive.mjs');
|
|
11
12
|
const write=(file,value)=>fs.writeFileSync(file,JSON.stringify(value));
|
|
@@ -27,6 +28,18 @@ function setup(t,kind='logic'){
|
|
|
27
28
|
t.after(()=>fs.rmSync(temp,{recursive:true,force:true}));
|
|
28
29
|
return {temp,project,config,answers,session,planPath,run};
|
|
29
30
|
}
|
|
31
|
+
test('browser live handoff reaches the real host and preserves an unavailable-device BLOCKED observation',async t=>{
|
|
32
|
+
const f=setup(t,'browser');
|
|
33
|
+
write(f.planPath,{config:'config.json',answers:'answers',sessionDir:'session',
|
|
34
|
+
liveEvidence:{directory:'exchange',kinds:['qa_browser'],timeoutMs:1000}});
|
|
35
|
+
const out=await runLiveDriver(driver,f.planPath,'start',row=>{
|
|
36
|
+
assert.equal(row.kind,'qa_browser');assert.equal(row.payload.case.id,'TC-001');
|
|
37
|
+
return {verdict:'BLOCKED',evidence:[],environment:row.payload.environment,cleanup:'not_needed'};
|
|
38
|
+
});
|
|
39
|
+
assert.equal(out.status,0,out.stderr);assert.equal(out.requests.length,1);
|
|
40
|
+
assert.equal(JSON.parse(out.stdout).result.overall,'BLOCKED');
|
|
41
|
+
assert.equal(JSON.parse(out.stdout).result.executionPassed,0);
|
|
42
|
+
});
|
|
30
43
|
test('real host: status is read-only, logic start and historical resume',t=>{
|
|
31
44
|
const f=setup(t);let out=f.run('status');assert.equal(out.status,0,out.stderr);
|
|
32
45
|
assert.equal(JSON.parse(out.stdout).result.stage,'ready');assert.equal(fs.existsSync(f.session),false);
|
|
@@ -72,7 +85,7 @@ test('mutation probes catch static browser answer, omitted schema check, dropped
|
|
|
72
85
|
};
|
|
73
86
|
const browser=setup(t,'browser');let out=browser.run('start');assert.equal(out.status,2);
|
|
74
87
|
const changed=source.replace("if(admission.modes.includes('browser')&&(admission.operation==='explore'||contract?.cases?.some(item=>item.kind==='browser')))","if(false)")
|
|
75
|
-
.replace('answerFor:row=>answers[row.kind]??null',"answerFor:row=>row.kind==='qa_browser'?readJson(path.join(answerRoot,'qa-browser.json'),'qa_browser'):answers[row.kind]??null");
|
|
88
|
+
.replace('answerFor:(row,answers,paths,control)=>live.has(row.kind)?live.answer(row,control):answers[row.kind]??null',"answerFor:row=>row.kind==='qa_browser'?readJson(path.join(answerRoot,'qa-browser.json'),'qa_browser'):answers[row.kind]??null");
|
|
76
89
|
const staticFile=path.join(root,'scripts',`.cm-test-drive-static-mutant-${process.pid}.mjs`);fs.writeFileSync(staticFile,changed);
|
|
77
90
|
t.after(()=>fs.rmSync(staticFile,{force:true}));
|
|
78
91
|
const report=path.join(browser.project,'docs/test-reports','fake.md');fs.mkdirSync(path.dirname(report),{recursive:true});fs.writeFileSync(report,'Fabricated browser result');
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import {skillContext} from '../runtime/js/cm-ai/tool-preview.mjs';
|
|
4
|
+
const retainedPreamble = "Each entry includes a name, description, and location for its `SKILL.md`. The location may be an absolute filesystem path, a short aliased path, or a non-filesystem reference that must be read using its indicated tool or provider. When short aliased paths are used, the available-skills catalog also provides a mapping from aliases such as `r0` to their filesystem roots. Expand the alias before accessing the skill.\n\nThe user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.\n\nThe first time in a conversation that you decide to apply a skill, inform the user in the commentary channel.\n\nIf a skill causes you to ask for permission or confirmation, pause, or leave requested work unfinished, name the skill and summarize the specific instruction in the skill that led to your decision. Include this explanation in the request or final response where you pause.";
|
|
5
|
+
const input = text => ({input:[{content:[{text}]}]});
|
|
6
|
+
test('Codex 0.159.2 retained empty skill preamble is not a catalog',()=>{
|
|
7
|
+
assert.equal(skillContext(input('<skills_instructions>\n### Available skills\n'+retainedPreamble+'\n</skills_instructions>')).present,false);
|
|
8
|
+
});
|
|
9
|
+
test('real, unresolved and unknown catalogs remain blocked',()=>{
|
|
10
|
+
for(const content of ['- sample (file: /tmp/sample/SKILL.md)','- sample (file: r99/sample/SKILL.md)','Unrecognized catalog content'])
|
|
11
|
+
assert.equal(skillContext(input('<skills_instructions>\n### Available skills\n'+retainedPreamble+'\n'+content+'\n</skills_instructions>')).present,true);
|
|
12
|
+
});
|
|
@@ -179,12 +179,14 @@ def usage_row_error(row: Dict[str, Any]) -> Optional[str]:
|
|
|
179
179
|
return "invalid input count"
|
|
180
180
|
if not is_nonnegative_int(row.get("output_tokens")):
|
|
181
181
|
return "invalid output count"
|
|
182
|
-
for field in ("cache_read_tokens", "cache_write_tokens"):
|
|
182
|
+
for field in ("cache_read_tokens", "cache_write_tokens", "reasoning_tokens"):
|
|
183
183
|
if field in row and not is_nonnegative_int(row[field]):
|
|
184
184
|
return "invalid cache count"
|
|
185
|
+
if "reasoning_tokens" in row and row["reasoning_tokens"] > row["output_tokens"]:
|
|
186
|
+
return "invalid reasoning subset"
|
|
185
187
|
return None
|
|
186
188
|
if usage_state == "unavailable":
|
|
187
|
-
if any(field in row for field in TOKEN_FIELDS):
|
|
189
|
+
if any(field in row for field in TOKEN_FIELDS + ("reasoning_tokens",)):
|
|
188
190
|
return "unavailable row contains token counts"
|
|
189
191
|
return None
|
|
190
192
|
return "invalid usage state"
|
|
@@ -242,6 +244,8 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
|
|
|
242
244
|
usage_candidates: List[Tuple[RunRef, Path, int, Dict[str, Any]]] = []
|
|
243
245
|
seen_event_ids: Set[str] = set()
|
|
244
246
|
seen_call_ids: Set[Tuple[str, str]] = set()
|
|
247
|
+
native_calls = 0
|
|
248
|
+
native_components = {field: {"tokens": 0, "observed_calls": 0} for field in TOKEN_FIELDS + ("reasoning_tokens",)}
|
|
245
249
|
|
|
246
250
|
for ref in refs:
|
|
247
251
|
log_path = safe_log_path(log_home, ref.log_file)
|
|
@@ -307,7 +311,7 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
|
|
|
307
311
|
continue
|
|
308
312
|
seen_call_ids.add(call_key)
|
|
309
313
|
claim = claims.get(call_key)
|
|
310
|
-
if row.get("adapter") == "openai-compatible" and claim is None:
|
|
314
|
+
if (row.get("adapter") == "openai-compatible" or row.get("source") == "native-cli-terminal") and claim is None:
|
|
311
315
|
summary["invalid_calls"] += 1
|
|
312
316
|
print(
|
|
313
317
|
f"warning: ignored managed model_usage without prior claim at "
|
|
@@ -333,6 +337,12 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
|
|
|
333
337
|
stage = str(row["stage"])
|
|
334
338
|
role = str(row["role"])
|
|
335
339
|
usage_state = row.get("usage_state")
|
|
340
|
+
if row.get("source") == "native-cli-terminal":
|
|
341
|
+
native_calls += 1
|
|
342
|
+
for field, component in native_components.items():
|
|
343
|
+
if usage_state == "observed" and field in row:
|
|
344
|
+
component["tokens"] += row[field]
|
|
345
|
+
component["observed_calls"] += 1
|
|
336
346
|
outcome = str(row["outcome"])
|
|
337
347
|
summary["outcomes"][outcome] += 1
|
|
338
348
|
if usage_state == "unavailable":
|
|
@@ -446,6 +456,11 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
|
|
|
446
456
|
"groups": groups,
|
|
447
457
|
"unavailable_groups": unavailable_groups,
|
|
448
458
|
"unresolved_groups": unresolved_groups,
|
|
459
|
+
**({"native_components": {"calls": native_calls, "reasoning_is_output_subset": True,
|
|
460
|
+
"cache_counts_are_separate": True, "fields": {field: {
|
|
461
|
+
"tokens": value["tokens"] if value["observed_calls"] else None,
|
|
462
|
+
"observed_calls": value["observed_calls"], "unavailable_calls": native_calls - value["observed_calls"]
|
|
463
|
+
} for field, value in native_components.items()}}} if native_calls else {}),
|
|
449
464
|
}
|
|
450
465
|
|
|
451
466
|
|
|
@@ -490,6 +505,10 @@ def print_human(report: Dict[str, Any]) -> None:
|
|
|
490
505
|
f"{group['role']} | {group['adapter']} | "
|
|
491
506
|
f"{group['requested_model']} | claims {group['claims']}"
|
|
492
507
|
)
|
|
508
|
+
if "native_components" in report:
|
|
509
|
+
for field, value in report["native_components"]["fields"].items():
|
|
510
|
+
known = value["tokens"] if value["tokens"] is not None else "unavailable"
|
|
511
|
+
print(f"- native {field}: {known}; observed {value['observed_calls']}, unavailable {value['unavailable_calls']}")
|
|
493
512
|
print(
|
|
494
513
|
"- 缺失 usage 保持 unavailable;未完成 claim 单独报告且不计调用/Token;"
|
|
495
514
|
"未推测缺失用量,也未换算费用。"
|
|
@@ -464,6 +464,15 @@ export function loadUserRuntimes(){
|
|
|
464
464
|
}
|
|
465
465
|
|
|
466
466
|
export function loadConfig(input){
|
|
467
|
+
return loadConfigUsing(input,loadUserRuntimes);
|
|
468
|
+
}
|
|
469
|
+
// Read-only candidate resolution; use the same merge and validation as the real loader.
|
|
470
|
+
// Keep the public loadConfig input and effective-config JSON contracts unchanged.
|
|
471
|
+
export function previewUserRuntimeConfig(input,preset){
|
|
472
|
+
runtimePreset(preset);
|
|
473
|
+
return loadConfigUsing(input,()=>({preset}));
|
|
474
|
+
}
|
|
475
|
+
function loadConfigUsing(input,userDefaults){
|
|
467
476
|
if(!object(input)||!Object.hasOwn(input,'projectRoot')
|
|
468
477
|
||Object.keys(input).some(key=>!['projectRoot','configPath','text'].includes(key)))throw new ConfigError('invalid config input');
|
|
469
478
|
const root=realDirectory(input.projectRoot,'project root');
|
|
@@ -486,7 +495,7 @@ export function loadConfig(input){
|
|
|
486
495
|
const raw=parseDocument(configPath,text);walkForSecrets(raw);validateRaw(raw);
|
|
487
496
|
const normalizedRaw={...raw,version:Number(raw.version)};
|
|
488
497
|
const projectDeclared=raw.runtimes?.available!==undefined;
|
|
489
|
-
const user=projectDeclared?null:
|
|
498
|
+
const user=projectDeclared?null:userDefaults();
|
|
490
499
|
const defaults=user?deepMerge(DEFAULT_CONFIG,runtimePreset(user.preset)):DEFAULT_CONFIG;
|
|
491
500
|
const effective=deepMerge(defaults,normalizedRaw),policy=effective.roles.external_expert.model_policy;
|
|
492
501
|
RUNTIME_SOURCES.set(effective,projectDeclared?'project':user?'user':'none');
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import {buildManifest} from '../cm-spec-manifest.mjs';
|
|
2
|
+
import {after} from 'node:test';
|
|
3
|
+
import assert from 'node:assert/strict';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {createHostBootstrap} from '../../runtime/js/cm-ai/host-bootstrap.mjs';
|
|
9
|
+
import {cmInitRuleTargets} from '../../runtime/js/cm-init/draft-generation.mjs';
|
|
10
|
+
import {createTaskRunner} from '../../runtime/js/cm-ai/task-runner.mjs';
|
|
11
|
+
import {openTaskExecutionStore} from '../../runtime/js/cm-ai/task-owner.mjs';
|
|
12
|
+
import {createDeveloperRun} from '../../runtime/js/cm-ai/developer-adapter.mjs';
|
|
13
|
+
import {inspectCmAiTaskLearningInput} from '../../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
|
|
14
|
+
import {digest} from '../../runtime/js/cm-ai/effect-contract.mjs';
|
|
15
|
+
import {createHostCheck} from '../../runtime/js/cm-ai/host-check.mjs';
|
|
16
|
+
import {reviewPaths} from '../../runtime/js/cm-ai/review-runner.mjs';
|
|
17
|
+
|
|
18
|
+
// Keep runtime declarations and log mirrors independent of the invoking user's home.
|
|
19
|
+
const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-ai-bootstrap-home-'));
|
|
20
|
+
process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
|
|
21
|
+
process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
|
|
22
|
+
after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
|
|
23
|
+
|
|
24
|
+
export const workflowRoot=fileURLToPath(new URL('../..',import.meta.url)).replace(/\/$/,'');
|
|
25
|
+
export const selection={versionControl:'none',modules:['frontend'],analysis:'Approved synthetic JavaScript project'};
|
|
26
|
+
const checks=()=>Object.fromEntries(['commands','globs','file_references','constraint_preservation','rule_applicability']
|
|
27
|
+
.map(name=>[name,{status:'verified',evidence:'Synthetic semantic report for the local fixture'}]));
|
|
28
|
+
export function fixture(t){
|
|
29
|
+
const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-bootstrap-')));
|
|
30
|
+
t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
|
|
31
|
+
const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs');
|
|
32
|
+
fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,'0.bootstrap'),{recursive:true});fs.mkdirSync(path.join(specsDir,'.reviews'));
|
|
33
|
+
fs.writeFileSync(path.join(specsDir,'0.bootstrap','requirements.md'),'# Requirements\nSynthetic approved scaffold and project instructions.\n');
|
|
34
|
+
fs.writeFileSync(path.join(specsDir,'0.bootstrap','design.md'),'# Design\nJavaScript; no Git; frontend module.\n');
|
|
35
|
+
fs.writeFileSync(path.join(specsDir,'0.bootstrap','tasks.md'),'- [ ] T-001: 生成项目骨架 scaffold\n- [ ] T-002: 生成 .claude/ 规范(cm-init)\n');
|
|
36
|
+
fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['0.bootstrap'],specFiles:buildManifest(specsDir)}));
|
|
37
|
+
return {root,codeProject,specsDir,calls:[],reviews:[],businessCalls:0};
|
|
38
|
+
}
|
|
39
|
+
export function definition(f,taskId){
|
|
40
|
+
return {version:1,codeProject:f.codeProject,specsDir:f.specsDir,feature:'0.bootstrap',
|
|
41
|
+
identity:{repositoryId:'bootstrap-fixture',runId:'run-'+taskId,taskId,attempt:1},
|
|
42
|
+
scope:taskId==='T-001'?['app.mjs']:[...cmInitRuleTargets(selection)],requirements:[]};
|
|
43
|
+
}
|
|
44
|
+
export function reply(f,kind,payload){
|
|
45
|
+
f.calls.push(kind);
|
|
46
|
+
if(kind==='init_generate')return {status:'generated',documents:payload.targets.map(file=>({path:file,
|
|
47
|
+
content:file==='AGENTS.md'&&fs.existsSync(path.join(f.codeProject,file))?fs.readFileSync(path.join(f.codeProject,file),'utf8'):
|
|
48
|
+
file==='.claude/CLAUDE.md'?'# Fixture instructions\n'+payload.targets.filter(p=>p.startsWith('.claude/rules/'))
|
|
49
|
+
.map(p=>'@rules/'+path.basename(p)).join('\n')+'\n':'# Fixture instructions\nUse approved scope.\n'
|
|
50
|
+
// A revision must change the rejected bytes (develop_unchanged_after_review).
|
|
51
|
+
+(payload.bootstrap?.priorReview?'Revised for the review findings.\n':'')}))};
|
|
52
|
+
if(kind==='init_verify')return {checks:checks(),constraintChanges:[],application:{status:'no_relevant_lesson',note:null},
|
|
53
|
+
retrospective:f.lesson&&f.calls.filter(kind=>kind==='init_verify').length===1
|
|
54
|
+
?{status:'lesson_candidate',candidates:[{classification:'structured',trigger:'Bootstrap recovery',
|
|
55
|
+
action:'Preserve reviewed instruction lessons across attempts',evidence:['app.mjs']}],reason:null}
|
|
56
|
+
:{status:'no_new_lesson',candidates:[],reason:null}};
|
|
57
|
+
assert.fail('unexpected host call '+kind);
|
|
58
|
+
}
|
|
59
|
+
export function open(f,taskId,mode='create',overrides={}){
|
|
60
|
+
const d=definition(f,taskId),bridge={call:async(kind,payload)=>overrides.reply?overrides.reply(kind,payload):reply(f,kind,payload)};
|
|
61
|
+
const bootstrap=createHostBootstrap({definition:d,workflowRoot,selection:taskId==='T-001'?null:selection,bridge,
|
|
62
|
+
allowWrite:overrides.allowWrite??true});
|
|
63
|
+
const store=openTaskExecutionStore({tasksPath:path.join(f.specsDir,'0.bootstrap','tasks.md'),feature:'bootstrap',specsRoot:f.specsDir,
|
|
64
|
+
identity:{repositoryId:d.identity.repositoryId,runId:d.identity.runId},
|
|
65
|
+
fingerprints:{workflow:digest('bootstrap-test'),config:digest({d,bootstrap:bootstrap.configuration}),inputs:digest(taskId)},create:mode==='create'});
|
|
66
|
+
const developer={provider:'codex',requestedModel:'synthetic',contextId:'scaffold-author',run:createDeveloperRun({provider:'codex',requestedModel:'synthetic',worker:async request=>{
|
|
67
|
+
f.businessCalls++;assert(!request.prompt.includes('"scope":["AGENTS.md"'));
|
|
68
|
+
assert(request.prompt.includes(Buffer.from('JavaScript; no Git; frontend module.').toString('base64').slice(0,12))
|
|
69
|
+
||request.prompt.includes('0.bootstrap/design.md'));
|
|
70
|
+
fs.writeFileSync(path.join(f.codeProject,'app.mjs'),'export const fixture = true;\n');
|
|
71
|
+
return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
|
|
72
|
+
retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
|
|
73
|
+
}})};
|
|
74
|
+
const hostCheck=createHostCheck({cwd:f.codeProject,timeoutMs:1000,commands:[{id:'syntax',command:[process.execPath,'--check','app.mjs']}]});
|
|
75
|
+
const runner=createTaskRunner({root:f.codeProject,identity:d.identity,scope:d.scope,requirements:d.requirements,bootstrap,
|
|
76
|
+
taskLearning:{feature:'0.bootstrap',hostHandoff:true},developer,excludedContexts:['main'],timeoutMs:5000,
|
|
77
|
+
reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic-review',allowed:true,available:true,contexts:['review-one','review-two'],
|
|
78
|
+
run:async(request,{onEvent})=>{f.reviews.push(request.payload.reviewPackage);
|
|
79
|
+
onEvent({event:'thread.started',provider_thread:'actual-review-'+request.identity.attempt});
|
|
80
|
+
onEvent({event:'turn.started',item_type:null});onEvent({event:'item.completed',item_type:'agent_message'});
|
|
81
|
+
onEvent({event:'turn.completed',item_type:null});onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
|
|
82
|
+
const revise=f.requestRevision&&taskId==='T-002'&&request.identity.attempt===1;
|
|
83
|
+
return {status:'succeeded',value:{verdict:revise?'changes_requested':'approved',packageDigest:request.payload.reviewPackage.packageDigest,
|
|
84
|
+
examinedPaths:reviewPaths(request.payload.reviewPackage),findings:revise?[{id:'F1',severity:'P2',path:'AGENTS.md',
|
|
85
|
+
message:'Reverify instruction applicability',evidence:'Synthetic revision fixture'}]:[],summary:'Synthetic independent review'}};}}],
|
|
86
|
+
reviewInvocation:{developerThreadId:'scaffold-author',excludedThreadIds:['main'],authorize:(request,{authorizationAt})=>{
|
|
87
|
+
const body={version:1,kind:'cm-review-dispatch-grant',grantId:'grant-'+request.identity.attempt,adapterId:'codex-review-adapter',
|
|
88
|
+
invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,reviewerId:'reviewer',
|
|
89
|
+
logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,hostContextId:'main',
|
|
90
|
+
decisionId:'decision-'+request.identity.attempt,decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
|
|
91
|
+
return {...body,grantDigest:digest(body)};
|
|
92
|
+
}},
|
|
93
|
+
check:overrides.afterCheck?async (input,control)=>{const result=await hostCheck(input,control);overrides.afterCheck();return result;}:hostCheck,
|
|
94
|
+
taskCompletion:{reviewsDir:path.join(f.specsDir,'.reviews'),handoffs:[1,2].map(a=>path.join(f.specsDir,'.reviews',`bootstrap-${taskId}-a${a}-handoff.json`))},
|
|
95
|
+
persistence:{store,mode,version:3}});
|
|
96
|
+
return {runner,store,definition:d,close:()=>store.close(),effect:(kind,suffix='')=>{
|
|
97
|
+
const identity=runner.status().identity;
|
|
98
|
+
return runner.executeEffect({version:1,id:kind+'-'+identity.attempt+suffix,kind,identity,...(kind==='develop'?{
|
|
99
|
+
learningInput:inspectCmAiTaskLearningInput({specsDir:f.specsDir,codeProject:f.codeProject,feature:'0.bootstrap',identity,
|
|
100
|
+
applicableAgentFiles:[]},{admission:runner.inspectBootstrapAdmission()})}:{})});
|
|
101
|
+
}};
|
|
102
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Local fixture responder for the actual driver/host transport. No provider,
|
|
2
|
+
// account or browser is contacted; each test supplies its synthetic observation.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import {spawn} from 'node:child_process';
|
|
5
|
+
export function runLiveDriver(driver,plan,operation,respond,{env=process.env,timeoutMs=30000}={}){
|
|
6
|
+
return new Promise((resolve,reject)=>{
|
|
7
|
+
const child=spawn(process.execPath,[driver,'--plan',plan,operation],{env,stdio:['ignore','pipe','pipe']});
|
|
8
|
+
let stdout='',stderr='',buffer='',failure=null;const requests=[];
|
|
9
|
+
const startedAt=Date.now();
|
|
10
|
+
const timer=setTimeout(()=>{
|
|
11
|
+
failure=Object.assign(Error('fixture driver timeout'),{code:'fixture_driver_timeout',
|
|
12
|
+
diagnostic:{timeoutMs,elapsedMs:Date.now()-startedAt,requestCount:requests.length,
|
|
13
|
+
stdoutBytes:Buffer.byteLength(stdout),stderrBytes:Buffer.byteLength(stderr)}});
|
|
14
|
+
child.kill();
|
|
15
|
+
},timeoutMs);
|
|
16
|
+
child.stdout.on('data',chunk=>{stdout+=chunk;});
|
|
17
|
+
child.stderr.on('data',chunk=>{
|
|
18
|
+
stderr+=chunk;buffer+=chunk;
|
|
19
|
+
let at;while((at=buffer.indexOf('\n'))!==-1){
|
|
20
|
+
const line=buffer.slice(0,at);buffer=buffer.slice(at+1);
|
|
21
|
+
if(!line.startsWith('[drive] live_evidence_request: '))continue;
|
|
22
|
+
const file=line.slice('[drive] live_evidence_request: '.length);
|
|
23
|
+
try{
|
|
24
|
+
const row=JSON.parse(fs.readFileSync(file,'utf8'));requests.push(row);
|
|
25
|
+
const result=respond(row),target=file.replace('.request.json','.result.json');
|
|
26
|
+
fs.writeFileSync(target+'.tmp',JSON.stringify({type:'host_result',sessionId:row.sessionId,
|
|
27
|
+
callId:row.callId,requestDigest:row.requestDigest,result}),{flag:'wx',mode:0o600});
|
|
28
|
+
fs.renameSync(target+'.tmp',target);
|
|
29
|
+
}catch(error){failure=error;child.kill();}
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
child.on('error',error=>{clearTimeout(timer);reject(error);});
|
|
33
|
+
child.on('close',status=>{clearTimeout(timer);if(failure)reject(failure);else resolve({status,stdout,stderr,requests});});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -35,7 +35,9 @@ export function guardFixtureSource(source,options){
|
|
|
35
35
|
|
|
36
36
|
function listProcesses(){
|
|
37
37
|
const listed=spawnSync('ps',['-axww','-o','pid=,ppid=,pgid=,command='],{encoding:'utf8',maxBuffer:64*1024*1024});
|
|
38
|
-
if(listed.status!==0)throw Error(
|
|
38
|
+
if(listed.status!==0)throw Object.assign(Error('fixture process listing failed'),{
|
|
39
|
+
code:'fixture_process_listing_failed',diagnostic:{command:'ps',status:listed.status??null,
|
|
40
|
+
signal:listed.signal??null,systemCode:listed.error?.code??null}});
|
|
39
41
|
const rows=[];
|
|
40
42
|
for(const line of listed.stdout.split('\n')){
|
|
41
43
|
const match=line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
|