@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
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import {inspectFixExecutionHistory} from '../cm-fix/execution.mjs';
|
|
2
|
+
// Reuse the existing SQLite ownership protocol; never unlock an unknown call.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {openExecutionStore} from './execution-store.mjs';
|
|
6
|
+
import {readExecutionSnapshot} from './execution-snapshot.mjs';
|
|
7
|
+
import {fixReviewLedger} from '../cm-fix/review-reconciliation.mjs';
|
|
8
|
+
import {inspectProviderReview,inspectProviderCauseReview} from './provider-review-observation.mjs';
|
|
9
|
+
import {validateReviewDispatchGrant} from './durable-runner-state.mjs';
|
|
10
|
+
import {readRunnerHistory} from './durable-runner-state.mjs';
|
|
11
|
+
import {oldWriterOpen} from './reviewed-evidence-supersede.mjs';
|
|
12
|
+
import {digest,need,shape,id} from './effect-contract.mjs';
|
|
13
|
+
import {readModelJsonRecord,writeModelJson} from './model-configuration-file.mjs';
|
|
14
|
+
function fixCallsResolved(records,configuration){
|
|
15
|
+
const ledger=fixReviewLedger(records,configuration);
|
|
16
|
+
const hosts=[configuration.hostContextId,...records.filter(r=>/^fix-host-joined-/.test(r.id)).map(r=>r.payload.hostContextId)];
|
|
17
|
+
for(const registration of records.filter(r=>/^fix-.*-registered$/.test(r.id))){
|
|
18
|
+
const prefix=registration.id.slice(0,-'-registered'.length),request=registration.payload.request;
|
|
19
|
+
const started=records.find(r=>r.id===prefix+'-started'),result=records.find(r=>r.id===prefix+'-result');
|
|
20
|
+
if(!started||!result)return false;
|
|
21
|
+
const cause=prefix.includes('cause'),reviewer=configuration.causeReview;
|
|
22
|
+
validateReviewDispatchGrant(registration.payload.grant,{request,reviewerId:cause?reviewer.reviewerId:'fix-final-reviewer',adapterId:cause?reviewer.adapterId:`${reviewer.provider}-review-adapter`,packageDigest:request.payload.reviewPackage.packageDigest,hostContextIds:hosts,authorizationAt:registration.payload.authorizationAt,registeredAt:registration.payload.registeredAt});
|
|
23
|
+
need(result.payload.dispatchAt>=registration.payload.registeredAt&&result.payload.dispatchAt<registration.payload.grant.expiresAt,'external_prior_run_unverifiable');
|
|
24
|
+
const proof=ledger.receipts.get(request.invocationId);
|
|
25
|
+
if(proof&&ledger.applied.has(request.invocationId))continue;
|
|
26
|
+
const excluded=[...reviewer.excludedThreadIds,...hosts.slice(1),request.contextId,...records.filter(r=>r.seq<registration.seq&&/-started$/.test(r.id)&&r.payload.providerThreadId).map(r=>r.payload.providerThreadId)];
|
|
27
|
+
const checked=(cause?inspectProviderCauseReview:inspectProviderReview)(JSON.stringify(result.payload.observation),JSON.stringify({request,developerThreadId:hosts[0],excludedThreadIds:[...new Set(excluded)]}));
|
|
28
|
+
if(checked.observationStatus!=='completed'||checked.providerThreadId!==started.payload.providerThreadId)return false;
|
|
29
|
+
}
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
const codeBinding=codeProject=>path.join(codeProject,'.cm-external-models-v1.json');
|
|
33
|
+
export const externalRunGuardExists=(specsDir,codeProject)=>fs.existsSync(path.join(specsDir,'.cm-external-models-v1'))||fs.existsSync(codeBinding(codeProject));
|
|
34
|
+
export function acquireExternalRunGuard(definition,{strictOnly=false}={}){
|
|
35
|
+
const {specsDir,codeProject,identity,feature}=definition;
|
|
36
|
+
for(const folder of [specsDir,codeProject])need(path.isAbsolute(folder)&&fs.realpathSync(folder)===folder,'external_run_guard_path');
|
|
37
|
+
// A code checkout belongs to one specs root; changing specs cannot hide an attempt.
|
|
38
|
+
const binding={version:1,kind:'cm-external-code-binding',specsDir},file=codeBinding(codeProject);
|
|
39
|
+
if(!fs.existsSync(file))try{writeModelJson(file,binding,{expectedSha256:null,replace:false});}
|
|
40
|
+
catch(error){if(!['model_configuration_exists','model_configuration_changed'].includes(error.code))throw error;}
|
|
41
|
+
need(digest(readModelJsonRecord(file).value)===digest(binding),'external_code_specs_conflict');
|
|
42
|
+
const root=path.join(specsDir,'.cm-external-models-v1');
|
|
43
|
+
try{fs.mkdirSync(root,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
|
|
44
|
+
const stat=fs.lstatSync(root);
|
|
45
|
+
need(stat.isDirectory()&&!stat.isSymbolicLink()&&(stat.mode&0o077)===0,'external_run_guard_path');
|
|
46
|
+
const leaseId='external-provider-'+digest(codeProject).slice(0,32);
|
|
47
|
+
const leaseDir=path.join(root,'.reviews/.execution',leaseId);
|
|
48
|
+
const fingerprint=digest('cm-external-models-serial-lease-v1');
|
|
49
|
+
const lease=openExecutionStore({specsRoot:root,identity:{repositoryId:identity.repositoryId,runId:leaseId},
|
|
50
|
+
fingerprints:{workflow:fingerprint,config:fingerprint,inputs:fingerprint},create:!fs.existsSync(leaseDir)});
|
|
51
|
+
try{
|
|
52
|
+
const execution=path.join(specsDir,'.reviews/.execution');
|
|
53
|
+
if(fs.existsSync(execution))for(const entry of fs.readdirSync(execution,{withFileTypes:true})){
|
|
54
|
+
if(entry.name===identity.runId)continue;
|
|
55
|
+
if(entry.name==='batch.lock'){
|
|
56
|
+
const file=path.join(execution,entry.name),stat=fs.lstatSync(file);
|
|
57
|
+
need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&(stat.mode&0o077)===0&&stat.size<=4096,'external_prior_run_unverifiable');
|
|
58
|
+
const lock=JSON.parse(fs.readFileSync(file,'utf8'));shape(lock,['batchId','pid','at']);id(lock.batchId);
|
|
59
|
+
need(Number.isSafeInteger(lock.pid)&&lock.pid>0&&typeof lock.at==='string','external_prior_run_unverifiable');
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
need(entry.isDirectory()&&!entry.isSymbolicLink(),'external_prior_run_unverifiable');
|
|
63
|
+
const snapshot=readExecutionSnapshot({specsRoot:specsDir,identity:{repositoryId:identity.repositoryId,runId:entry.name}});
|
|
64
|
+
const init=snapshot.records[0]?.payload,config=init?.config;
|
|
65
|
+
if(init?.workflow==='cm-fix-stages-v1'){
|
|
66
|
+
const fix=init.configuration;need(fix?.reproduction?.cwd,'external_prior_run_unverifiable');
|
|
67
|
+
if(fs.realpathSync(fix.reproduction.cwd)!==codeProject)continue;
|
|
68
|
+
if(strictOnly&&!(fix.externalModels||fix.executionPolicy))continue;
|
|
69
|
+
need(!oldWriterOpen(execution,entry.name),'external_prior_writer_active');
|
|
70
|
+
inspectFixExecutionHistory({specsRoot:specsDir,identity:{repositoryId:identity.repositoryId,runId:entry.name}});
|
|
71
|
+
// A completed parent may reopen read-only between its original serial child steps.
|
|
72
|
+
if(fix.qaSource&&digest(fix.qaSource.identity)===digest(identity))continue;
|
|
73
|
+
need(fixCallsResolved(snapshot.records,fix),'external_prior_attempt_unresolved');
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
// An unfinished initializer has no task identity and cannot safely be ignored.
|
|
77
|
+
need(config,'external_prior_run_unverifiable');
|
|
78
|
+
if(strictOnly&&!(config.externalModels||config.executionPolicy))continue;
|
|
79
|
+
if(config.root!==codeProject)continue;
|
|
80
|
+
const history=readRunnerHistory(snapshot.records,config,init.version);
|
|
81
|
+
// Unknown external work belongs to the code root, even across tasks/features.
|
|
82
|
+
if(config.externalModels||config.executionPolicy)need(!history.pending&&history.state.state!=='unknown'
|
|
83
|
+
&&history.state.reviewInvocation?.result?.reconciliationRequired!==true
|
|
84
|
+
&&!history.state.calls.some(call=>call.requestedModel!=='current-session'
|
|
85
|
+
&&!['succeeded','not_dispatched'].includes(call.terminal)
|
|
86
|
+
&&!snapshot.records.some(row=>row.payload.type==='review-invocation-reconciled'&&row.payload.invocationId===call.invocationId)),'external_prior_attempt_unresolved');
|
|
87
|
+
need(!oldWriterOpen(execution,entry.name),'external_prior_writer_active');
|
|
88
|
+
if(config.identity.taskId!==identity.taskId
|
|
89
|
+
||config.completion?.owner?.tasksPath!==path.join(specsDir,feature,'tasks.md'))continue;
|
|
90
|
+
need(!history.pending&&!['unknown','ready','awaiting_review','pending_review','changes_requested','approved'].includes(history.state.state)
|
|
91
|
+
&&history.state.reviewInvocation?.result?.reconciliationRequired!==true,'external_prior_attempt_unresolved');
|
|
92
|
+
need(!oldWriterOpen(execution,entry.name),'external_prior_writer_active');
|
|
93
|
+
}
|
|
94
|
+
return lease;
|
|
95
|
+
}catch(error){lease.close();throw error;}
|
|
96
|
+
}
|
|
@@ -7,7 +7,9 @@ import {cmInitRuleTargets,generateCmInitDraft,validateCmInitSelection} from '../
|
|
|
7
7
|
import {inspectCmInitDraft,readCmInitSource} from '../cm-init/draft-inspection.mjs';
|
|
8
8
|
import {replaceSessionFile} from '../cm-prd/session.mjs';
|
|
9
9
|
import {readReviewSourceFiles,readReviewBaseline} from './review-package.mjs';
|
|
10
|
-
import {inspectCmAiBootstrapTask,identifyApprovedBootstrapFeature} from './cm-ai-admission.mjs';
|
|
10
|
+
import {inspectCmAiBootstrapTask,identifyApprovedBootstrapFeature,parseFeatureTaskText} from './cm-ai-admission.mjs';
|
|
11
|
+
import {approvedTaskGrammar} from '../spec-task-line.mjs';
|
|
12
|
+
import {readCommittedRuleBasis} from './committed-rule-basis.mjs';
|
|
11
13
|
import {readProjectInstructionContext,createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective} from './cm-ai-context-refresh.mjs';
|
|
12
14
|
import {validateDeveloperScope,readDeveloperRequest} from './developer-adapter.mjs';
|
|
13
15
|
import {digest,json,shape,need,freeze,validIdentity,hex,requestFor,terminalFor,boundedReason} from './effect-contract.mjs';
|
|
@@ -20,17 +22,28 @@ const learningSection=source=>/^## 项目教训[ \t]*\r?$/gmu.test(source);
|
|
|
20
22
|
const canonical=root=>need(typeof root==='string'&&path.isAbsolute(root)&&fs.realpathSync(root)===root
|
|
21
23
|
&&fs.lstatSync(root).isDirectory(),'bootstrap_root_invalid');
|
|
22
24
|
|
|
23
|
-
export function
|
|
25
|
+
export function committedBootstrapBasis({specsDir,codeProject,feature,taskId,instructionPaths,requireCleanIndex=true}){
|
|
26
|
+
const parsed=parseFeatureTaskText(fs.readFileSync(path.join(specsDir,feature,'tasks.md'),'utf8'),
|
|
27
|
+
{allowDependencyPunctuation:true,grammar:approvedTaskGrammar(specsDir)});
|
|
28
|
+
need(!parsed.error,'bootstrap_task_required');
|
|
29
|
+
const index=parsed.tasks.findIndex(task=>task.id===taskId);
|
|
30
|
+
const priorRules=index>0&&parsed.tasks.slice(0,index).some(task=>task.completed&&!task.dropped
|
|
31
|
+
&&/(?:cm-init|\.claude\/|AGENTS\.md)/i.test(task.description)
|
|
32
|
+
&&/(?:生成|规范|规则|instruction|rules|generate)/i.test(task.description));
|
|
33
|
+
return priorRules?readCommittedRuleBasis(codeProject,instructionPaths,{requireCleanIndex}):undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function mergeBootstrapAgents(existing,generated,{refresh=false}={}){
|
|
24
37
|
need(typeof existing==='string'&&typeof generated==='string','bootstrap_instruction_conflict');
|
|
25
38
|
if(!existing)return generated;
|
|
26
39
|
const heading=/^## 项目教训[ \t]*\r?$/gmu.exec(existing);
|
|
27
|
-
if(!heading){need(generated.includes(existing),'bootstrap_instruction_conflict');return generated;}
|
|
40
|
+
if(!heading){need(refresh||generated.includes(existing),'bootstrap_instruction_conflict');return generated;}
|
|
28
41
|
const next=/^## [^\r\n]+\r?$/gmu;
|
|
29
42
|
next.lastIndex=heading.index+heading[0].length;
|
|
30
43
|
const end=next.exec(existing)?.index??existing.length;
|
|
31
44
|
const section=existing.slice(heading.index,end);
|
|
32
45
|
const before=existing.slice(0,heading.index),after=existing.slice(end);
|
|
33
|
-
need((!before||generated.includes(before))&&(!after||generated.includes(after)),'bootstrap_instruction_conflict');
|
|
46
|
+
need(refresh||(!before||generated.includes(before))&&(!after||generated.includes(after)),'bootstrap_instruction_conflict');
|
|
34
47
|
if(generated.includes(section))return generated;
|
|
35
48
|
need(!/^## 项目教训[ \t]*\r?$/gmu.test(generated),'bootstrap_instruction_conflict');
|
|
36
49
|
return generated+(generated.endsWith('\n')?'':'\n')+'\n'+section;
|
|
@@ -59,7 +72,15 @@ export function validateBootstrapReviewPackage(pkg,evidence,configuration,identi
|
|
|
59
72
|
for(const file of value.files){
|
|
60
73
|
const change=pkg.changes.find(item=>item.path===file.path);
|
|
61
74
|
const expected=file.path==='AGENTS.md'&&writeback.outcome==='written'?writeback.agentsFile.sha256:file.afterSha256;
|
|
62
|
-
need(
|
|
75
|
+
need(pkg.scope.includes(file.path),'bootstrap_review_mismatch');
|
|
76
|
+
if(change!==undefined){
|
|
77
|
+
// The package covers the whole delivery against the run's original
|
|
78
|
+
// baseline. Both a new attempt and a same-attempt retry may start from
|
|
79
|
+
// already-written rules. Write admission checks that starting content;
|
|
80
|
+
// package validation binds the final bytes, not this effect's before hash.
|
|
81
|
+
need(change.after?.sha256===expected,'bootstrap_review_mismatch');
|
|
82
|
+
}else need(pkg.unchangedScope?.some(item=>item.path===file.path&&item.sha256===expected),
|
|
83
|
+
'bootstrap_review_mismatch');
|
|
63
84
|
}
|
|
64
85
|
return value;
|
|
65
86
|
}
|
|
@@ -81,6 +102,9 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
|
|
|
81
102
|
const selected=inspectCmAiBootstrapTask({specsDir:data.specsDir,codeProject:data.codeProject,taskId:data.identity.taskId},true);
|
|
82
103
|
const mode=selected.mode,choice=mode==='scaffold'?null:validateCmInitSelection(selection);
|
|
83
104
|
const instructionPaths=mode==='scaffold'?[]:cmInitRuleTargets(choice);
|
|
105
|
+
const committedBasis=mode==='instructions'?committedBootstrapBasis({specsDir:data.specsDir,
|
|
106
|
+
codeProject:data.codeProject,feature:data.feature,taskId:data.identity.taskId,instructionPaths,
|
|
107
|
+
requireCleanIndex:false}):undefined;
|
|
84
108
|
need(Array.isArray(data.scope)&&new Set(data.scope).size===data.scope.length
|
|
85
109
|
&&instructionPaths.every(file=>data.scope.includes(file)),'bootstrap_scope_required');
|
|
86
110
|
const businessScope=data.scope.filter(file=>!instructionPaths.includes(file));
|
|
@@ -92,7 +116,8 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
|
|
|
92
116
|
const policyDigest=digest(instructionPaths.slice(2).map(file=>{
|
|
93
117
|
const relative='templates/rules/'+path.basename(file);return [relative,sha(readCmInitSource(workflowRoot,relative))];}));
|
|
94
118
|
const configuration=json({version:1,mode,codeProject:data.codeProject,specsDir:data.specsDir,feature:data.feature,
|
|
95
|
-
identity:data.identity,scope:data.scope,businessScope,instructionPaths,workflowRoot,selection:choice,policyDigest,bootstrapRequirements
|
|
119
|
+
identity:data.identity,scope:data.scope,businessScope,instructionPaths,workflowRoot,selection:choice,policyDigest,bootstrapRequirements,
|
|
120
|
+
...(committedBasis!==undefined?{committedBasisRequired:true,committedBasis}:{})});
|
|
96
121
|
const used=new Set();
|
|
97
122
|
const admission=baseline=>{
|
|
98
123
|
const original=readReviewBaseline(baseline);
|
|
@@ -100,7 +125,39 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
|
|
|
100
125
|
if(mode==='scaffold')need(original.files.length===0,'bootstrap_original_not_empty');
|
|
101
126
|
return inspectCmAiBootstrapTask({specsDir:data.specsDir,codeProject:data.codeProject,taskId:data.identity.taskId},mode==='scaffold').admission;
|
|
102
127
|
};
|
|
103
|
-
const
|
|
128
|
+
const instructionBaseline=({identity,previous=null,previousWriteback=null})=>{
|
|
129
|
+
need(mode==='instructions','bootstrap_task_required');
|
|
130
|
+
if(committedBasis===null){
|
|
131
|
+
const error=new Error('bootstrap_instruction_conflict');error.code='bootstrap_instruction_conflict';
|
|
132
|
+
error.paths=instructionPaths;throw error;
|
|
133
|
+
}
|
|
134
|
+
if(committedBasis!==undefined){
|
|
135
|
+
const current=readCommittedRuleBasis(data.codeProject,instructionPaths);
|
|
136
|
+
if(digest(current)!==digest(committedBasis)){
|
|
137
|
+
const error=new Error('bootstrap_instruction_conflict');error.code='bootstrap_instruction_conflict';
|
|
138
|
+
error.paths=instructionPaths;throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const retry=previous!==null&&previous.identity?.attempt===identity.attempt;
|
|
142
|
+
const prior=previous===null?null:readBootstrapEvidence(previous,configuration,
|
|
143
|
+
{...identity,attempt:retry?identity.attempt:identity.attempt-1});
|
|
144
|
+
need(identity.attempt===1?prior===null||retry:prior!==null,'bootstrap_prior_evidence_required');
|
|
145
|
+
const originals=instructionPaths.map(file=>({path:file,bytes:readCmInitSource(data.codeProject,file)}));
|
|
146
|
+
const conflicts=[];
|
|
147
|
+
for(const file of originals){
|
|
148
|
+
const initial=configuration.committedBasisRequired
|
|
149
|
+
?configuration.committedBasis.files.find(item=>item.path===file.path).sha256
|
|
150
|
+
:file.path==='AGENTS.md'&&file.bytes!==null
|
|
151
|
+
&&learningSection(new TextDecoder('utf8',{fatal:true}).decode(file.bytes))?sha(file.bytes):null;
|
|
152
|
+
const expected=file.path==='AGENTS.md'&&prior!==null&&previousWriteback?.outcome==='written'
|
|
153
|
+
?previousWriteback.agentsFile.sha256:prior?.files.find(item=>item.path===file.path).afterSha256??initial;
|
|
154
|
+
if(sha(file.bytes)!==expected)conflicts.push(file.path);
|
|
155
|
+
}
|
|
156
|
+
if(conflicts.length){const error=new Error('bootstrap_instruction_conflict');error.code='bootstrap_instruction_conflict';
|
|
157
|
+
error.paths=conflicts;throw error;}
|
|
158
|
+
return {originals,prior};
|
|
159
|
+
};
|
|
160
|
+
const capability={configuration,inspectAdmission:admission,assertInstructionBaseline:instructionBaseline,
|
|
104
161
|
assertWriteAuthorized(){need(allowWrite,'bootstrap_write_authorization_required');},
|
|
105
162
|
async run(request,control,develop,{previous=null,previousWriteback=null,baseline,verificationFailed=null}={}){
|
|
106
163
|
need(allowWrite,'bootstrap_write_authorization_required');
|
|
@@ -112,21 +169,13 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
|
|
|
112
169
|
// A revision binds to the previous attempt's evidence. A retryable develop
|
|
113
170
|
// block after this effect wrote the rules (develop_checks_not_passed) retries
|
|
114
171
|
// the same attempt, so it binds to that attempt's own recorded evidence.
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
{...request.identity,attempt:retry?request.identity.attempt:request.identity.attempt-1});
|
|
118
|
-
if(mode==='instructions')need(request.identity.attempt===1?prior===null||retry:prior!==null,'bootstrap_prior_evidence_required');
|
|
119
|
-
const originals=instructionPaths.map(file=>({path:file,bytes:readCmInitSource(data.codeProject,file)}));
|
|
120
|
-
for(const file of originals){
|
|
121
|
-
const expected=file.path==='AGENTS.md'&&prior!==null&&previousWriteback?.outcome==='written'
|
|
122
|
-
?previousWriteback.agentsFile.sha256:prior?.files.find(item=>item.path===file.path).afterSha256
|
|
123
|
-
??(file.path==='AGENTS.md'&&file.bytes!==null
|
|
124
|
-
&&learningSection(new TextDecoder('utf8',{fatal:true}).decode(file.bytes))?sha(file.bytes):null);
|
|
125
|
-
need(sha(file.bytes)===expected,'bootstrap_instruction_conflict');
|
|
126
|
-
}
|
|
172
|
+
const {originals}=mode==='instructions'?instructionBaseline({identity:request.identity,previous,previousWriteback})
|
|
173
|
+
:{originals:instructionPaths.map(file=>({path:file,bytes:readCmInitSource(data.codeProject,file)}))};
|
|
127
174
|
used.add(request.invocationId);
|
|
128
175
|
const current=()=>{
|
|
129
176
|
canonical(data.codeProject);
|
|
177
|
+
if(committedBasis!==undefined)need(digest(readCommittedRuleBasis(data.codeProject,instructionPaths))
|
|
178
|
+
===digest(committedBasis),'bootstrap_instruction_conflict');
|
|
130
179
|
for(const file of originals)need(sha(readCmInitSource(data.codeProject,file.path))===sha(file.bytes),'bootstrap_instruction_conflict');
|
|
131
180
|
};
|
|
132
181
|
let response=null;
|
|
@@ -153,7 +202,8 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
|
|
|
153
202
|
need(generated.status==='draft_generated'&&generated.inspection.status==='structurally_checked','bootstrap_generation_blocked');
|
|
154
203
|
const agentsBefore=originals.find(file=>file.path==='AGENTS.md').bytes;
|
|
155
204
|
const documents=generated.documents.map(document=>document.path==='AGENTS.md'
|
|
156
|
-
?{path:document.path,content:mergeBootstrapAgents(agentsBefore?.toString('utf8')??'',document.content
|
|
205
|
+
?{path:document.path,content:mergeBootstrapAgents(agentsBefore?.toString('utf8')??'',document.content,
|
|
206
|
+
{refresh:committedBasis!==undefined})}:document);
|
|
157
207
|
const inspection=inspectCmInitDraft({project:data.codeProject,documents,selection:choice});
|
|
158
208
|
need(inspection.status==='structurally_checked','bootstrap_generation_blocked');
|
|
159
209
|
const verified=json(await bridge.call('init_verify',{project:data.codeProject,selection:choice,documents,
|
|
@@ -9,18 +9,35 @@ import {StringDecoder} from 'node:string_decoder';
|
|
|
9
9
|
import {cleanEnvironment,specsPermissionArgs} from './codex-config.mjs';
|
|
10
10
|
import {json,shape,need,id,text,validCallTimeout,validIdentity} from './effect-contract.mjs';
|
|
11
11
|
|
|
12
|
-
export function
|
|
12
|
+
export function reportHostCheckProgress(event){
|
|
13
|
+
const message=event.phase==='start'?`开始检查 ${event.id}`:
|
|
14
|
+
`检查结束 ${event.id}: ${event.outcome} (exit ${event.exitCode??'unavailable'})`;
|
|
15
|
+
try{process.stderr.write(`[check] ${message}\n`);}catch{/* display is not a check verdict */}
|
|
16
|
+
}
|
|
17
|
+
export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,outputIncludes=null,onOutput=null,onProgress=null,reuseDeclared=false}){
|
|
18
|
+
need(typeof reuseDeclared==='boolean','invalid_check_config');
|
|
13
19
|
need(path.isAbsolute(cwd)&&fs.realpathSync(cwd)===cwd&&fs.statSync(cwd).isDirectory());
|
|
14
20
|
validCallTimeout(timeoutMs);
|
|
15
21
|
need(onOutput===null||typeof onOutput==='function');
|
|
22
|
+
need(onProgress===null||typeof onProgress==='function');
|
|
23
|
+
const notify=event=>{
|
|
24
|
+
try{
|
|
25
|
+
const returned=onProgress?.(Object.freeze(event));
|
|
26
|
+
if(types.isPromise(returned))Promise.prototype.then.call(returned,()=>{},()=>{});
|
|
27
|
+
}catch{/* observers cannot change results or prevent cleanup */}
|
|
28
|
+
};
|
|
16
29
|
if(outputIncludes!==null){text(outputIncludes);need(Buffer.byteLength(outputIncludes)<=1000&&!outputIncludes.includes('\0'));}
|
|
17
30
|
const signature=outputIncludes===null?null:Buffer.from(outputIncludes);
|
|
18
31
|
const selected=json(commands,32*1024),ids=new Set();
|
|
19
32
|
need(Array.isArray(selected)&&selected.length>0&&selected.length<=32);
|
|
20
|
-
for(const item of selected){
|
|
21
|
-
shape(item,['id','command']);id(item.id);need(!ids.has(item.id));ids.add(item.id);
|
|
33
|
+
for(const [index,item] of selected.entries()){
|
|
34
|
+
shape(item,['id','command',...(reuseDeclared&&Object.hasOwn(item,'sameExecutionAs')?['sameExecutionAs']:[])]);id(item.id);need(!ids.has(item.id));ids.add(item.id);
|
|
22
35
|
need(Array.isArray(item.command)&&item.command.length>0);
|
|
23
36
|
for(const arg of item.command){text(arg);need(!arg.includes('\0'));}
|
|
37
|
+
if(Object.hasOwn(item,'sameExecutionAs')){
|
|
38
|
+
const previous=selected[index-1];
|
|
39
|
+
need(previous&&item.sameExecutionAs===previous.id&&JSON.stringify(item.command)===JSON.stringify(previous.command),'check_reuse_binding');
|
|
40
|
+
}
|
|
24
41
|
}
|
|
25
42
|
return async(raw,{signal})=>{
|
|
26
43
|
shape(raw,['identity']);validIdentity(raw.identity);
|
|
@@ -29,6 +46,14 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
|
|
|
29
46
|
for(const item of selected){
|
|
30
47
|
let signatureMatched=false;
|
|
31
48
|
need(!signal.aborted,'cancelled');
|
|
49
|
+
if(Object.hasOwn(item,'sameExecutionAs')){
|
|
50
|
+
const original=results[results.length-1];need(original?.outcome==='passed','check_reuse_binding');
|
|
51
|
+
const evidence=`same execution as ${original.id}; ${original.evidence}`.slice(0,200);
|
|
52
|
+
notify({phase:'complete',id:item.id,outcome:original.outcome,exitCode:original.exitCode,sameExecutionAs:original.id});
|
|
53
|
+
results.push({id:item.id,command:item.command,outcome:original.outcome,exitCode:original.exitCode,evidence,
|
|
54
|
+
...(signature?{signatureMatched:original.signatureMatched}:{})});continue;
|
|
55
|
+
}
|
|
56
|
+
notify({phase:'start',id:item.id});
|
|
32
57
|
const result=await new Promise(resolve=>{
|
|
33
58
|
let child;
|
|
34
59
|
try{
|
|
@@ -99,8 +124,9 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
|
|
|
99
124
|
}
|
|
100
125
|
});
|
|
101
126
|
});
|
|
127
|
+
notify({phase:'complete',id:item.id,outcome:result.outcome,exitCode:result.exitCode});
|
|
102
128
|
need(!signal.aborted,'cancelled');
|
|
103
|
-
results.push({
|
|
129
|
+
results.push({id:item.id,command:item.command,...result,...(signature?{signatureMatched}:{})});
|
|
104
130
|
if(result.outcome!=='passed')break;
|
|
105
131
|
}
|
|
106
132
|
return json(results);
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {createNativeUsageLog} from './native-usage-log.mjs';
|
|
2
|
+
import {readExecutionPolicy} from './execution-policy.mjs';
|
|
3
|
+
import {selectExternalModels} from './external-models.mjs';
|
|
1
4
|
// Fixed current-conversation factory, separate from CLI top-level execution.
|
|
2
5
|
import fs from 'node:fs';
|
|
3
6
|
import {spawn} from 'node:child_process';
|
|
@@ -26,6 +29,7 @@ import {validateDocumentationPaths} from './host-documentation.mjs';
|
|
|
26
29
|
import {verifySpecificationMaterial} from './specification-material.mjs';
|
|
27
30
|
import {isFinalCmAiTask} from './cm-ai-admission.mjs';
|
|
28
31
|
import {createHostBootstrap} from './host-bootstrap.mjs';
|
|
32
|
+
import {withHostProgress} from './host-progress.mjs';
|
|
29
33
|
import {digest,id,hex,json,need,shape,freeze,arrayItems} from './effect-contract.mjs';
|
|
30
34
|
export const protectedTextInstructions='\nProtected current-host mode: do not write files or run commands. Return {status,value,edits} on success; '
|
|
31
35
|
+'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content[,mode]}], complete UTF-8 text or null for deletion; '
|
|
@@ -34,6 +38,8 @@ export const protectedTextInstructions='\nProtected current-host mode: do not wr
|
|
|
34
38
|
+'status must be exactly "succeeded" on success (with value and edits) or "failed" (with code). Return the object through the structured output schema; never wrap it in markdown fences.';
|
|
35
39
|
const protectedConversations=new WeakMap();
|
|
36
40
|
export const conversationProtection=execution=>protectedConversations.get(execution)??null;
|
|
41
|
+
const externalConversations=new WeakMap();
|
|
42
|
+
export const externalConversationDefinition=execution=>externalConversations.get(execution)??null;
|
|
37
43
|
// An explicit reviewer budget wins over the protected-mode budget: it is the
|
|
38
44
|
// narrower knob, and raising it must not require switching development mode.
|
|
39
45
|
// Absent both, the worker default applies. Returns a spread-ready fragment so
|
|
@@ -101,19 +107,27 @@ export const REVIEW_BOUND_MARGIN_MS=60000;
|
|
|
101
107
|
export const reviewRaceTimeout=(outerTimeoutMs,reviewTimeoutMs)=>Math.max(outerTimeoutMs,reviewTimeoutMs+REVIEW_BOUND_MARGIN_MS);
|
|
102
108
|
export function createConversationExecution(definition,hostContextId,bridge,review=null,allowedAttempt=null,workflow=null,allowQa=false,runtime='codex',options={}){
|
|
103
109
|
definition=json(definition);workflow=workflow===null?null:json(workflow);options=json(options);
|
|
104
|
-
shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
|
|
110
|
+
shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','externalModels','reviewerRuntime','parallelMember','verificationPrecheck','executionPolicy'].filter(key=>Object.hasOwn(options,key))]);
|
|
105
111
|
need(!Object.hasOwn(options,'verificationPrecheck')||typeof options.verificationPrecheck==='boolean','invalid_input');
|
|
112
|
+
const executionPolicy=options.executionPolicy?readExecutionPolicy(options.executionPolicy):null;
|
|
106
113
|
const parallelMember=options.parallelMember??false;need(typeof parallelMember==='boolean','invalid_input');
|
|
107
114
|
const provider=options.providerDevelopment??null;
|
|
108
115
|
if(provider){
|
|
109
|
-
shape(provider,['model','attempt','coderRuntime','reviewerRuntime']);
|
|
116
|
+
shape(provider,['model','attempt','coderRuntime','reviewerRuntime',...(Object.hasOwn(provider,'effort')?['effort']:[])]);
|
|
110
117
|
need(options.protection&&review!==null,'protected_configuration_required');
|
|
111
118
|
need([1,2].includes(provider.attempt),'provider_development_authorization_required');
|
|
112
119
|
need(/^[a-zA-Z0-9._-]+$/.test(provider.model),'invalid_model');
|
|
113
120
|
need(digest(resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),runtime))
|
|
114
121
|
===digest({coderRuntime:provider.coderRuntime,reviewerRuntime:provider.reviewerRuntime}),'runtime_selection_mismatch');
|
|
115
122
|
}
|
|
116
|
-
|
|
123
|
+
if(Object.hasOwn(options,'reviewerRuntime'))need(options.externalModels&&['codex','claude'].includes(options.reviewerRuntime)
|
|
124
|
+
&&options.reviewerRuntime===resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),runtime).reviewerRuntime,'runtime_selection_mismatch');
|
|
125
|
+
const coderRuntime=provider?.coderRuntime??runtime,reviewerRuntime=provider?.reviewerRuntime??options.reviewerRuntime??runtime;
|
|
126
|
+
const externalModels=options.externalModels?selectExternalModels(options.externalModels,provider?[coderRuntime,reviewerRuntime]:[reviewerRuntime]):null;
|
|
127
|
+
if(externalModels){
|
|
128
|
+
const selected=externalModels.providers[reviewerRuntime];need(review!==null&&review.model===selected.model&&review.effort===selected.effort,'external_model_configuration_conflict');
|
|
129
|
+
if(provider){const selected=externalModels.providers[coderRuntime];need(provider.model===selected.model&&provider.effort===selected.effort,'external_model_configuration_conflict');}
|
|
130
|
+
}else need(!Object.hasOwn(provider??{},'effort')&&!Object.hasOwn(review??{},'effort'),'external_model_feature_required');
|
|
117
131
|
let bootstrap=null;
|
|
118
132
|
if(options.bootstrap){
|
|
119
133
|
shape(options.bootstrap,['selection','allowWrite']);
|
|
@@ -123,7 +137,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
123
137
|
const protection=options.protection??null;
|
|
124
138
|
if(protection){shape(protection,['checkCommands','timeoutMs']);specsPermissionArgs({cwd:definition.codeProject,specsRoot:definition.specsDir});}
|
|
125
139
|
need(!definition.codeProjects||protection,'multi_root_protection_required');
|
|
126
|
-
const projectExecution=protection?createProjectExecution({definition,protection}):null;
|
|
140
|
+
const projectExecution=protection?createProjectExecution({definition,protection,executionPolicy}):null;
|
|
127
141
|
const check=projectExecution?.check??null;
|
|
128
142
|
const documentationPaths=workflow?validateDocumentationPaths(workflow.documentationPaths,definition.scope):[];
|
|
129
143
|
need(['codex','claude'].includes(runtime),'invalid_runtime');
|
|
@@ -140,13 +154,15 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
140
154
|
need(protection||!definition.specsDir.startsWith(definition.codeProject+path.sep),'nested_specs_protection_required');
|
|
141
155
|
const configuration={kind:'cm-current-conversation-v1',...(parallelMember?{parallelMember}:{}),definitionDigest:digest(definition),hostContextId:durableHostContextId,
|
|
142
156
|
...(runtime==='claude'?{runtime}:{}),
|
|
143
|
-
...(
|
|
157
|
+
...(executionPolicy?{executionPolicy}:{}),
|
|
158
|
+
...(externalModels?{externalModels}:{}),
|
|
159
|
+
...(provider?{providerDevelopment:{model:provider.model,coderRuntime,reviewerRuntime,...(externalModels?{effort:provider.effort}:{})}}:{}),
|
|
144
160
|
...(protection?{protection}:{}),
|
|
145
161
|
...(bootstrap?{bootstrap:bootstrap.configuration}:{}),
|
|
146
162
|
...(options.batchWorkflowsDigest?{batchWorkflowsDigest:options.batchWorkflowsDigest}:{}),
|
|
147
|
-
...(review?{review:{version:1,model:review.model,disabledSkills:review.disabledSkills}}:{}),
|
|
163
|
+
...(review?{review:{version:1,model:review.model,disabledSkills:review.disabledSkills,...(externalModels?{effort:review.effort}:{})}}:{}),
|
|
148
164
|
...(workflow?{workflow}: {})};
|
|
149
|
-
const reviewOptions={cwd:definition.codeProject,model:review?.model??'unconfigured',preflight:review?.preflight??null,
|
|
165
|
+
const reviewOptions={cwd:definition.codeProject,model:review?.model??'unconfigured',...(externalModels?{effort:review.effort}:{}),preflight:review?.preflight??null,
|
|
150
166
|
disabledSkills:review?.disabledSkills??[],
|
|
151
167
|
...resolveReviewTimeout(review,protection),
|
|
152
168
|
promptTransport:'stdin',schemaPath:fileURLToPath(new URL('./review-result.schema.json',import.meta.url))};
|
|
@@ -201,8 +217,10 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
201
217
|
return {satisfied:verdict.satisfied};
|
|
202
218
|
}:null;
|
|
203
219
|
const outerTimeoutMs=provider?protection.timeoutMs:1800000;
|
|
220
|
+
const progress=(request,control,stage,run,selectedRuntime=runtime)=>withHostProgress({definition,
|
|
221
|
+
identity:request.identity,runtime:selectedRuntime,stage,signal:control.signal},run);
|
|
204
222
|
const execution={configuration,timeoutMs:outerTimeoutMs,excludedContexts:[durableHostContextId],hostDecision:null,applicableAgentFiles:[],
|
|
205
|
-
...(verificationGate?{verificationGate}:{}),
|
|
223
|
+
...(verificationGate?{verificationGate:(request,control)=>progress(request,control,'verifying',()=>verificationGate(request,control))}:{}),
|
|
206
224
|
...(bootstrap?{bootstrap}:{}),
|
|
207
225
|
...(provider?{developmentAttempt:provider.attempt}:{}),
|
|
208
226
|
...(workflow?createHostWorkflowCapabilities({definition,configuration:workflow,bridge,allowQa,runtime,protectedExecution:protection!==null,bootstrap,parallelMember}):{}),
|
|
@@ -215,14 +233,18 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
215
233
|
need(!used.has(bound.invocationId),'duplicate_dispatch');used.add(bound.invocationId);
|
|
216
234
|
}
|
|
217
235
|
const route=provider?null:resolveHostRole({definition,identity:bound.identity,role:'coder',signal:control.signal,runtime});
|
|
236
|
+
let developerUsage=null;const developerLog=executionPolicy&&provider?createNativeUsageLog({definition,request:bound,provider:coderRuntime,role:'developer'}):null;
|
|
218
237
|
const processWorker=provider?(coderRuntime==='codex'?codexDeveloperWorker:claudeDeveloperWorker)({
|
|
219
|
-
|
|
238
|
+
...(developerLog?{onUsageClaim:()=>developerLog.claimed(),onUsage:value=>{developerUsage=value;}}:{}),
|
|
239
|
+
cwd:definition.codeProject,model:provider.model,...(externalModels?{effort:provider.effort}:{}),timeoutMs:protection.timeoutMs,
|
|
220
240
|
...(coderRuntime==='codex'?{specsRoot:definition.specsDir}:{}),
|
|
221
241
|
spawnProcess:dispatchSpawn('coder',bound.identity,control.signal)}):null;
|
|
222
242
|
const worker=async({prompt})=>{
|
|
223
243
|
if(provider&&coderRuntime==='codex'){
|
|
224
244
|
if(documentationPaths.length)prompt='Synchronize approved documentation inside this invocation: '+JSON.stringify(documentationPaths)+'\n'+prompt;
|
|
225
|
-
|
|
245
|
+
const response=await processWorker({prompt},control);
|
|
246
|
+
developerLog?.complete(developerUsage??{usage_state:'unavailable'},response.status==='succeeded'?'success':response.status==='cancelled'?'cancelled':'error');
|
|
247
|
+
return response;
|
|
226
248
|
}
|
|
227
249
|
const expected=projectExecution?projectExecution.expected(bound.payload.scope):null;
|
|
228
250
|
if(protection){
|
|
@@ -234,6 +256,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
234
256
|
...(definition.codeProjects?{codeProjects:resolveCodeProjects(definition.codeProject,definition.codeProjects),
|
|
235
257
|
projectInstructions:definition.codeProjects.map(root=>({codeProject:root,files:readProjectInstructionContext(root)}))}:{}),
|
|
236
258
|
...(protection?{editMode:'protected-text-v1',expected}: {})},control.signal));
|
|
259
|
+
if(provider)developerLog?.complete(developerUsage??{usage_state:'unavailable'},response.status==='succeeded'?'success':response.status==='cancelled'?'cancelled':'error');
|
|
237
260
|
if(response.status==='succeeded'){
|
|
238
261
|
const edits=[];
|
|
239
262
|
try{
|
|
@@ -282,10 +305,11 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
282
305
|
if(provider){const {providerThread,...failure}=response;shape(failure,['status','code']);return failure;}
|
|
283
306
|
shape(response,['status','code']);return response;
|
|
284
307
|
};
|
|
285
|
-
return createDeveloperRun({worker,provider:coderRuntime,requestedModel:provider?.model??'current-session',
|
|
286
|
-
protectedCurrentSession:protection!==null&&provider===null})(bound,control);
|
|
308
|
+
return progress(bound,control,'developing',()=>createDeveloperRun({worker,provider:coderRuntime,requestedModel:provider?.model??'current-session',
|
|
309
|
+
protectedCurrentSession:protection!==null&&provider===null})(bound,control),coderRuntime);
|
|
287
310
|
}},
|
|
288
|
-
check:
|
|
311
|
+
check:(request,control)=>progress(request,control,'checking',()=>{
|
|
312
|
+
if(check)return check(request,control);
|
|
289
313
|
const route=resolveHostRole({definition,identity:request.identity,role:'tester',signal:control.signal,runtime});
|
|
290
314
|
return bridge.call('check',{...request,codeProject:definition.codeProject,
|
|
291
315
|
scope:definition.scope,requirements:definition.requirements,route},control.signal);
|
|
@@ -296,9 +320,18 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
296
320
|
allowed:true,available:true,contexts:reviewContexts,
|
|
297
321
|
run:(request,control)=>{
|
|
298
322
|
need(review!==null,'review_configuration_required');
|
|
299
|
-
const
|
|
300
|
-
|
|
301
|
-
|
|
323
|
+
let observedUsage=null;const usageLog=executionPolicy?createNativeUsageLog({definition,request,provider:reviewerRuntime,role:'reviewer'}):null;
|
|
324
|
+
const selectedOptions={...reviewOptions,...(usageLog?{onUsageClaim:()=>usageLog.claimed(),onUsage:value=>{observedUsage=value;}}:{}),...(provider?{spawnProcess:dispatchSpawn('reviewer',request.identity,control.signal)}:{})};
|
|
325
|
+
return progress(request,control,'review_starting',async observation=>{
|
|
326
|
+
const observedControl={...control,onEvent:event=>{
|
|
327
|
+
control.onEvent(event);
|
|
328
|
+
if(event.event==='thread.started')observation.reviewStarted();
|
|
329
|
+
}};
|
|
330
|
+
const result=await (reviewerRuntime==='codex'?createCodexReviewRun(codexWorker(selectedOptions),executionPolicy)(request,observedControl)
|
|
331
|
+
:createClaudeReviewRun(claudeWorker(selectedOptions),executionPolicy)(request,observedControl));
|
|
332
|
+
usageLog?.complete(observedUsage??{usage_state:'unavailable'},result.status==='succeeded'?'success':result.status==='cancelled'?'cancelled':'error');
|
|
333
|
+
return result;
|
|
334
|
+
},reviewerRuntime);
|
|
302
335
|
}}],
|
|
303
336
|
reviewInvocation:{developerThreadId:author,excludedThreadIds:[durableHostContextId],hostContextId,
|
|
304
337
|
// Not journaled (unlike timeoutMs above), so a resumed run may raise it.
|
|
@@ -310,5 +343,6 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
310
343
|
.filter(file=>file!=='AGENTS.md'&&fs.existsSync(path.join(definition.codeProject,file)))])];
|
|
311
344
|
if(protection){freeze(execution);protectedConversations.set(execution,freeze({codeProject:definition.codeProject,
|
|
312
345
|
specsRoot:definition.specsDir,definitionDigest:digest(definition)}));}
|
|
346
|
+
if(externalModels||executionPolicy){freeze(execution);externalConversations.set(execution,digest(definition));}
|
|
313
347
|
return execution;
|
|
314
348
|
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Event-based operator feedback. Failure here never changes a runner verdict.
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {spawnSync} from 'node:child_process';
|
|
4
|
+
import {randomUUID} from 'node:crypto';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {need} from './effect-contract.mjs';
|
|
7
|
+
import {readStatusProjection,writeStatusProjection} from './status-projection.mjs';
|
|
8
|
+
|
|
9
|
+
const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
|
|
10
|
+
const phases={developing:['N3','正在开发'],checking:['N3','正在执行检查'],
|
|
11
|
+
verifying:['N3','正在核对交付要求'],review_starting:['N4','正在启动独立审查'],reviewing:['N4','正在独立审查']};
|
|
12
|
+
const diagnostic=()=>{try{process.stderr.write('{"diagnostic":"progress_projection_failed"}\n');}catch{}};
|
|
13
|
+
function logProgress({definition,identity,runtime,operationId,stage,phase,outcome}){
|
|
14
|
+
const [node,detail]=phases[stage];
|
|
15
|
+
const result=spawnSync('python3',[writer,'--workflow','cm-ai','--event','progress','--phase',phase,
|
|
16
|
+
'--runtime',runtime,'--project-root',definition.codeProject,'--specs-dir',definition.specsDir,
|
|
17
|
+
'--run-id',identity.runId,'--detail',detail+(phase==='complete'?':调用已结束':''),'--data-json',JSON.stringify({node,
|
|
18
|
+
feature:definition.feature,task:identity.taskId,attempt:identity.attempt,operation_id:operationId,
|
|
19
|
+
phase_name:stage,...(outcome?{outcome}:{})})],
|
|
20
|
+
{timeout:10000,maxBuffer:64*1024,env:{...process.env,
|
|
21
|
+
CM_WORKFLOW_LOG_HOME:path.join(definition.specsDir,'.reviews','host-log-mirror')}});
|
|
22
|
+
need(!result.error&&result.status===0&&result.signal===null,'progress_log_failed');
|
|
23
|
+
}
|
|
24
|
+
export function startHostProgress({definition,identity,runtime='codex',stage,signal}){
|
|
25
|
+
need(phases[stage]&&!signal.aborted,'cancelled');
|
|
26
|
+
const operationId=randomUUID();let token=null,closed=false,observedReview=false;
|
|
27
|
+
const record=(phase,outcome)=>{
|
|
28
|
+
try{logProgress({definition,identity,runtime,operationId,stage,phase,outcome});}catch{diagnostic();}
|
|
29
|
+
};
|
|
30
|
+
const project=(selected,claim)=>{
|
|
31
|
+
try{
|
|
32
|
+
const receipt=writeStatusProjection({specsDir:definition.specsDir,feature:definition.feature,identity,
|
|
33
|
+
node:phases[selected][0],state:selected,detail:phases[selected][1],claim,expectedToken:claim?null:token});
|
|
34
|
+
token=receipt.written?receipt.token:null;
|
|
35
|
+
}catch{token=null;diagnostic();}
|
|
36
|
+
};
|
|
37
|
+
record('start');project(stage,true);
|
|
38
|
+
return Object.freeze({
|
|
39
|
+
reviewStarted(){
|
|
40
|
+
if(closed||signal.aborted||observedReview)return;observedReview=true;
|
|
41
|
+
if(token!==null)project('reviewing',false);
|
|
42
|
+
},
|
|
43
|
+
complete(outcome){
|
|
44
|
+
if(closed)return;closed=true;
|
|
45
|
+
record('complete',signal.aborted?'aborted':outcome);
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
export async function withHostProgress(options,run){
|
|
50
|
+
const progress=startHostProgress(options);
|
|
51
|
+
try{const result=await run(progress);progress.complete('returned');return result;}
|
|
52
|
+
catch(error){progress.complete('failed');throw error;}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const states={awaiting_review:['N4','检查已结束,等待独立审查'],pending_review:['N4','独立审查等待处理'],
|
|
56
|
+
changes_requested:['N4','审查要求修改'],approved:['N5','审查已通过,等待完成检查'],
|
|
57
|
+
fixture_completed:['N5','开发完成检查已通过,等待 QA/收尾'],
|
|
58
|
+
blocked:['N3','运行受阻'],unknown:['N3','执行结果待核对'],cancelled:['N3','运行已取消']};
|
|
59
|
+
export function projectHostResult({specsDir,feature,result,readCurrent}){
|
|
60
|
+
if(!result?.operation||result.operation==='status'||!result.state||!result.identity)return;
|
|
61
|
+
const selected=states[result.state];if(!selected)return;
|
|
62
|
+
// A late control response is not the runner's current state. Derived QA and
|
|
63
|
+
// documentation summaries have their own existing projections.
|
|
64
|
+
try{
|
|
65
|
+
// Read lazily, after eligibility, and keep display-read failures advisory.
|
|
66
|
+
// Eligible results still need fresh state after an asynchronous effect.
|
|
67
|
+
const current=readCurrent();
|
|
68
|
+
if(current.state!==result.state||current.identity.runId!==result.identity.runId
|
|
69
|
+
||current.identity.taskId!==result.identity.taskId||current.identity.attempt!==result.identity.attempt)return;
|
|
70
|
+
const previous=readStatusProjection(specsDir);
|
|
71
|
+
if(previous===null)return;
|
|
72
|
+
// QA and finalization must never be replaced by an earlier N3/N4 response.
|
|
73
|
+
if(['N6','N7','N8'].includes(previous.node))return;
|
|
74
|
+
const node=['blocked','unknown','cancelled'].includes(result.state)?previous.node:selected[0];
|
|
75
|
+
writeStatusProjection({specsDir,feature,identity:result.identity,node,state:result.state,
|
|
76
|
+
detail:(result.guidance?.summary??selected[1])+(result.code?`(${result.code})`:''),code:result.code,
|
|
77
|
+
...(result.state==='changes_requested'&&result.identity.attempt>1?{previousAttempt:result.identity.attempt-1}:{}),
|
|
78
|
+
expectedToken:previous.progress_id??null});
|
|
79
|
+
}catch{diagnostic();}
|
|
80
|
+
}
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
// Root selection is data, not a second scheduler or a task completion authority.
|
|
3
3
|
import {captureProtectedEdits,commitProtectedEdits} from '../cm-fix/protected-edits.mjs';
|
|
4
4
|
import {groupCodeProjectPaths,resolveCodeProjects} from './code-projects.mjs';
|
|
5
|
-
import {createHostCheck} from './host-check.mjs';
|
|
5
|
+
import {createHostCheck,reportHostCheckProgress} from './host-check.mjs';
|
|
6
6
|
import {specsPermissionArgs} from './codex-config.mjs';
|
|
7
7
|
import {digest,json,need,shape,id} from './effect-contract.mjs';
|
|
8
8
|
|
|
9
|
-
export function createProjectExecution({definition,protection}){
|
|
9
|
+
export function createProjectExecution({definition,protection,executionPolicy=null}){
|
|
10
10
|
const data=json(definition),config=json(protection);
|
|
11
11
|
const roots=data.codeProjects?resolveCodeProjects(data.codeProject,data.codeProjects):[data.codeProject];
|
|
12
12
|
for(const root of roots)specsPermissionArgs({cwd:root,specsRoot:data.specsDir});
|
|
@@ -16,15 +16,20 @@ export function createProjectExecution({definition,protection}){
|
|
|
16
16
|
const commands=config.checkCommands;
|
|
17
17
|
need(Array.isArray(commands)&&commands.length>0&&commands.length<=32,'invalid_check_config');
|
|
18
18
|
const ids=new Set();
|
|
19
|
-
const
|
|
20
|
-
|
|
19
|
+
const plans=[];
|
|
20
|
+
for(const command of commands){
|
|
21
|
+
shape(command,['id','command',...(data.codeProjects?['codeProject']:[]),
|
|
22
|
+
...(executionPolicy&&Object.hasOwn(command,'sameExecutionAs')?['sameExecutionAs']:[])]);id(command.id);
|
|
21
23
|
need(!ids.has(command.id),'invalid_check_config');ids.add(command.id);
|
|
22
24
|
const cwd=data.codeProjects?command.codeProject:data.codeProject;
|
|
23
25
|
need(roots.includes(cwd),'execution_root_mismatch');
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
26
|
+
if(Object.hasOwn(command,'sameExecutionAs'))need(plans.at(-1)?.cwd===cwd,'check_reuse_binding');
|
|
27
|
+
if(plans.at(-1)?.cwd!==cwd)plans.push({cwd,commands:[]});
|
|
28
|
+
const {codeProject,...local}=command;plans.at(-1).commands.push(local);
|
|
29
|
+
}
|
|
30
|
+
const checks=plans.map(plan=>({cwd:plan.cwd,check:createHostCheck({cwd:plan.cwd,specsRoot:data.specsDir,
|
|
31
|
+
timeoutMs:config.timeoutMs,onProgress:reportHostCheckProgress,commands:plan.commands,
|
|
32
|
+
reuseDeclared:executionPolicy?.checkReuse==='declared-adjacent-v1'})}));
|
|
28
33
|
need(roots.every(root=>checks.some(item=>item.cwd===root)),'code_project_checks_required');
|
|
29
34
|
const recheck=()=>{if(data.codeProjects)need(digest(resolveCodeProjects(data.codeProject,roots))===digest(roots),'execution_root_mismatch');};
|
|
30
35
|
return Object.freeze({
|
|
@@ -48,9 +53,9 @@ export function createProjectExecution({definition,protection}){
|
|
|
48
53
|
async check(request,control){
|
|
49
54
|
recheck();const result=[];
|
|
50
55
|
for(const item of checks){
|
|
51
|
-
const
|
|
52
|
-
result.push(data.codeProjects?{...row,evidence:`cwd=${item.cwd}; ${row.evidence}`}:row);
|
|
53
|
-
if(row.outcome!=='passed')break;
|
|
56
|
+
const rows=await item.check(request,control);
|
|
57
|
+
result.push(...rows.map(row=>data.codeProjects?{...row,evidence:`cwd=${item.cwd}; ${row.evidence}`}:row));
|
|
58
|
+
if(rows.some(row=>row.outcome!=='passed'))break;
|
|
54
59
|
}
|
|
55
60
|
return result;
|
|
56
61
|
},
|