@aibyzero/cm-workflow 0.16.3 → 0.16.5
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 +8 -0
- package/CHANGELOG.md +59 -0
- package/README.md +55 -3
- package/VERSION +1 -1
- package/docs/installation.md +21 -1
- package/docs/js-workflow-control.md +245 -33
- package/docs/next-steps.md +14 -24
- package/docs/runtime-failover.md +1 -1
- package/package.json +1 -1
- package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
- package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
- package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
- package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
- package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
- package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
- package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
- package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
- package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
- package/runtime/js/cm-ai/drive-core.mjs +39 -7
- package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
- package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
- package/runtime/js/cm-ai/effect-contract.mjs +44 -2
- package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
- package/runtime/js/cm-ai/execution-store.mjs +6 -4
- package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
- package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
- package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
- package/runtime/js/cm-ai/host-handoff.mjs +13 -6
- package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
- package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
- package/runtime/js/cm-ai/host-session.mjs +20 -5
- package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
- package/runtime/js/cm-ai/host.mjs +1 -1
- package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
- package/runtime/js/cm-ai/log-rows.mjs +21 -0
- package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
- package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
- package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
- package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
- package/runtime/js/cm-ai/review-package.mjs +427 -31
- package/runtime/js/cm-ai/review-runner.mjs +47 -1
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
- package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
- package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
- package/runtime/js/cm-ai/specification-material.mjs +154 -12
- package/runtime/js/cm-ai/task-commit.mjs +2 -2
- package/runtime/js/cm-ai/task-runner.mjs +502 -65
- package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
- package/runtime/js/cm-fix/execution.mjs +109 -25
- package/runtime/js/cm-fix/host-review.mjs +7 -3
- package/runtime/js/cm-fix/host.mjs +3 -1
- package/runtime/js/cm-fix/progress.mjs +1 -0
- package/runtime/js/cm-fix/protected-edits.mjs +15 -4
- package/runtime/js/cm-fix/qa-source.mjs +6 -4
- package/runtime/js/cm-prd/analysis.mjs +2 -1
- package/runtime/js/cm-prd/change.mjs +28 -10
- package/runtime/js/cm-prd/draft.mjs +5 -2
- package/runtime/js/cm-prd/review-preparation.mjs +10 -3
- package/runtime/js/cm-prd/review-publication.mjs +4 -2
- package/runtime/js/cm-prd/self-check.mjs +6 -3
- package/runtime/js/cm-prd/summary.mjs +6 -2
- package/runtime/js/cm-prd/validation-reason.mjs +20 -0
- package/runtime/js/spec-task-line.mjs +117 -0
- package/runtime/js/specs-status.mjs +14 -3
- package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
- package/scripts/cm-ai-admission.mjs +19 -10
- package/scripts/cm-ai-admission.test.mjs +65 -1
- package/scripts/cm-ai-batch-drive.mjs +93 -21
- package/scripts/cm-ai-batch-drive.test.mjs +171 -3
- package/scripts/cm-ai-batch-host.mjs +37 -13
- package/scripts/cm-ai-batch-host.test.mjs +26 -0
- package/scripts/cm-ai-batch-run.mjs +33 -10
- package/scripts/cm-ai-batch-run.test.mjs +56 -5
- package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
- package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
- package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
- package/scripts/cm-ai-bootstrap.test.mjs +99 -7
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
- package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
- package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
- package/scripts/cm-ai-drive.mjs +480 -47
- package/scripts/cm-ai-drive.test.mjs +247 -10
- package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
- package/scripts/cm-ai-host.mjs +89 -25
- package/scripts/cm-ai-host.test.mjs +274 -12
- package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
- package/scripts/cm-ai-multi-root.test.mjs +9 -3
- package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
- package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
- package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
- package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
- package/scripts/cm-ai-review-failure.test.mjs +917 -0
- package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
- package/scripts/cm-ai-review-timeout.test.mjs +199 -4
- package/scripts/cm-ai-run.mjs +160 -60
- package/scripts/cm-ai-run.test.mjs +4 -3
- package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
- package/scripts/cm-ai-selection-guard.test.mjs +100 -0
- package/scripts/cm-ai-session-chain.test.mjs +7 -3
- package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
- package/scripts/cm-ai-supersede.test.mjs +571 -17
- package/scripts/cm-ai-verification-gate.test.mjs +2 -1
- package/scripts/cm-capability-gate.test.mjs +21 -2
- package/scripts/cm-check-drive.mjs +4 -3
- package/scripts/cm-check-drive.test.mjs +17 -1
- package/scripts/cm-check-entry.mjs +13 -2
- package/scripts/cm-check-host.mjs +2 -2
- package/scripts/cm-check-host.test.mjs +57 -1
- package/scripts/cm-check-runtime.sh +16 -7
- package/scripts/cm-claude-developer-worker.test.mjs +43 -2
- package/scripts/cm-claude-probe.test.mjs +9 -1
- package/scripts/cm-claude-review-stream.test.mjs +68 -0
- package/scripts/cm-claude-worker.test.mjs +11 -4
- package/scripts/cm-codex-developer-worker.test.mjs +4 -2
- package/scripts/cm-failover.mjs +8 -8
- package/scripts/cm-fix-abandon.test.mjs +123 -5
- package/scripts/cm-fix-cause-package.test.mjs +2 -0
- package/scripts/cm-fix-drive.mjs +45 -13
- package/scripts/cm-fix-drive.test.mjs +36 -1
- package/scripts/cm-fix-host.mjs +9 -6
- package/scripts/cm-fix-review-budget.test.mjs +141 -0
- package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
- package/scripts/cm-host-check.test.mjs +6 -3
- package/scripts/cm-host-qa-executor.test.mjs +192 -17
- package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
- package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
- package/scripts/cm-log-event.mjs +17 -0
- package/scripts/cm-log-event.test.mjs +31 -0
- package/scripts/cm-prd-completion.test.mjs +105 -2
- package/scripts/cm-prd-draft.test.mjs +14 -0
- package/scripts/cm-prd-drive.mjs +13 -7
- package/scripts/cm-prd-drive.test.mjs +10 -0
- package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
- package/scripts/cm-prd-review-gate.mjs +126 -81
- package/scripts/cm-prd-review-gate.test.mjs +105 -1
- package/scripts/cm-prd-review-preparation.test.mjs +15 -0
- package/scripts/cm-prd-review-publication.test.mjs +6 -0
- package/scripts/cm-prd-self-check.test.mjs +6 -0
- package/scripts/cm-prd-summary.test.mjs +40 -0
- package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
- package/scripts/cm-review-inventory.test.mjs +253 -1
- package/scripts/cm-spec-manifest.mjs +28 -10
- package/scripts/cm-spec-manifest.test.mjs +8 -4
- package/scripts/cm-spec-task-line.test.mjs +138 -0
- package/scripts/cm-specs-status.test.mjs +31 -1
- package/scripts/cm-task-gate.mjs +18 -10
- package/scripts/cm-task-gate.py +1 -1
- package/scripts/cm-test-branch-impact.test.mjs +6 -3
- package/scripts/fixtures/claude-review-process.mjs +1 -0
- package/scripts/fixtures/process-cleanup.mjs +99 -0
- package/scripts/test-cm-log-event.py +2 -0
- package/scripts/test-cm-prd-review-gate.py +2 -1
- package/scripts/test-npm-install.py +1 -1
- package/scripts/test-scan-public-safety.py +1 -1
- package/scripts/test-shell-compat.sh +67 -0
- package/scripts/test-spec-manifest.py +16 -8
- package/scripts/test-task-gate.py +2 -2
- package/scripts/test-workflow-config.py +1 -0
- package/scripts/validate-public-repo.py +1 -0
- package/skills/cm-ai/references/N1-init.md +1 -1
- package/skills/cm-ai/references/js-host.md +264 -40
- package/skills/cm-check/SKILL.md +6 -1
- package/skills/cm-check/references/js-host.md +3 -3
- package/skills/cm-fix/references/js-host.md +22 -1
- package/skills/cm-prd/references/js-change-recovery.md +30 -0
- package/skills/cm-prd/references/js-host.md +6 -0
package/scripts/cm-ai-drive.mjs
CHANGED
|
@@ -5,7 +5,10 @@
|
|
|
5
5
|
// host-qa-executor.mjs logic/browser 和 host-documentation.mjs sync、
|
|
6
6
|
// host-qa-fix-owner.mjs fix_* 转发 cm-fix。保守预检整个 operation 可达的反问。
|
|
7
7
|
// operation possible host_request kinds; proving route
|
|
8
|
-
// advance develop, check;
|
|
8
|
+
// advance develop, check; bootstrap instructions replace develop with
|
|
9
|
+
// init_generate (answer file) and init_verify (answer file plus
|
|
10
|
+
// commands this driver runs; drive-bootstrap.mjs);
|
|
11
|
+
// workflow adds documentation_sync,
|
|
9
12
|
// qa_assess, qa_logic, qa_browser, documentation_inspect;
|
|
10
13
|
// auto QA-fix adds fix_* below.
|
|
11
14
|
// cm-ai-conversation-entry.mjs advance -> start/complete/qa/finish;
|
|
@@ -22,7 +25,7 @@
|
|
|
22
25
|
// fix_repair, fix_retrospective; host-qa-fix-owner.mjs
|
|
23
26
|
// forwards to cm-fix host.run/handle.
|
|
24
27
|
// fix_action selected cm-fix step; host-qa-fix-owner.mjs fix_action.
|
|
25
|
-
// status/cancel/fix_status/context_refresh: none; cm-ai-conversation-entry.mjs
|
|
28
|
+
// status/cancel/abandon_review/fix_status/context_refresh: none; cm-ai-conversation-entry.mjs
|
|
26
29
|
// status/cancel/context_refresh; host-qa-fix-owner.mjs fix_status.
|
|
27
30
|
// verification_precheck optional execution.verificationGate in
|
|
28
31
|
// host-conversation-execution.mjs; CLI has no runner for it.
|
|
@@ -31,6 +34,7 @@
|
|
|
31
34
|
// For unsupported evidence kinds, preflight refuses before the host starts.
|
|
32
35
|
import fs from 'node:fs';
|
|
33
36
|
import path from 'node:path';
|
|
37
|
+
import {createHash} from 'node:crypto';
|
|
34
38
|
import {fileURLToPath} from 'node:url';
|
|
35
39
|
import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
|
|
36
40
|
import {decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
|
|
@@ -38,11 +42,25 @@ import {createHostQaExecutor} from '../runtime/js/cm-ai/host-qa-executor.mjs';
|
|
|
38
42
|
import {inspectCmAiQaTaskContext} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
|
|
39
43
|
import {readLearningRetrospectiveContent} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
|
|
40
44
|
import {inspectFixInvestigation} from '../runtime/js/cm-fix/investigation.mjs';
|
|
41
|
-
import {readRunDefinition} from './cm-ai-run.mjs';
|
|
42
|
-
import {
|
|
45
|
+
import {readRunDefinition,assertCreatableRunId} from './cm-ai-run.mjs';
|
|
46
|
+
import {REVIEW_MATERIAL_LIMITS,captureReviewBaseline,reviewMaterialSizes,projectedReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
|
|
47
|
+
import {JOURNAL_PAYLOAD_LIMIT,developCheckpointReserve,taskReviewScope} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
48
|
+
import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
|
|
49
|
+
import {hostHandoffDocument} from '../runtime/js/cm-ai/host-handoff.mjs';
|
|
50
|
+
import {taskLearningHandoffBytes} from '../runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs';
|
|
51
|
+
import {projectLearningWriteback} from '../runtime/js/cm-ai/cm-ai-learning-writer.mjs';
|
|
52
|
+
import {inspectCmAiTaskLearningInput,createCmAiTaskLearningApplication,
|
|
53
|
+
createCmAiTaskLearningRetrospective} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
|
|
54
|
+
import {codeProjectPaths,resolveCodeProjects} from '../runtime/js/cm-ai/code-projects.mjs';
|
|
55
|
+
import {parseHostInputLimit} from '../runtime/js/cm-ai/host-session.mjs';
|
|
56
|
+
import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
|
|
57
|
+
import {readRunnerHistory,attemptBaseline} from '../runtime/js/cm-ai/durable-runner-state.mjs';
|
|
58
|
+
import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
|
|
59
|
+
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
60
|
+
import {attemptAnswerName,inspectDriverBootstrap,readBootstrapRulesAnswers,createBootstrapRulesResponder} from '../runtime/js/cm-ai/drive-bootstrap.mjs';
|
|
43
61
|
|
|
44
62
|
const HOST=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
|
|
45
|
-
const OPERATIONS=new Set(['advance','start','resume','status','cancel','decision','complete','qa','qa_result',
|
|
63
|
+
const OPERATIONS=new Set(['advance','start','resume','status','cancel','abandon_review','abandon_effect','decision','complete','qa','qa_result',
|
|
46
64
|
'fix_status','fix_advance','fix_action','fix_run','run_finalize','context_refresh','finish']);
|
|
47
65
|
const ADVANCE=new Set(['advance','start','resume']);
|
|
48
66
|
const PACKAGE_OPERATIONS=new Set(['decision','complete','qa','qa_result','context_refresh','finish','run_finalize']);
|
|
@@ -54,24 +72,364 @@ const FIX_ASKS={advance:['fix_learning','fix_diagnose'],author_tests:['fix_learn
|
|
|
54
72
|
const FIX_ACTIONS=new Set(['red_test','baseline','author_tests','repair','regression','retrospective',
|
|
55
73
|
'learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5',
|
|
56
74
|
'post_review_regression','publish_dossier','walkthrough','finish','prepare_revision',
|
|
57
|
-
'cause_review_package','cause_review','abandon_step']);
|
|
75
|
+
'cause_review_package','cause_review','abandon_step','abandon_review']);
|
|
58
76
|
const FILES={develop:'develop.json',qa_assess:'qa-assess.json',documentation_inspect:'documentation-inspect.json',
|
|
59
77
|
documentation_sync:'documentation-sync.json',fix_learning:'learning.json',fix_diagnose:'diagnosis.json',
|
|
60
78
|
fix_test_author:'test-edits.json',fix_repair:'repair-edits.json',fix_retrospective:'retrospective.json'};
|
|
61
79
|
const PAIR_FLAGS=new Set(['--allow-review-attempt','--review-config','--workflow-config',
|
|
62
|
-
'--
|
|
80
|
+
'--input-limit',
|
|
81
|
+
'--protected-conversation-config','--protected-config','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure',
|
|
63
82
|
'--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--browser-qa',
|
|
64
|
-
'--bootstrap-config','--allow-provider-development-attempt','--supersede-reason']);
|
|
83
|
+
'--bootstrap-config','--allow-provider-development-attempt','--supersede-reason','--spec-rebind-reason']);
|
|
65
84
|
const FLAG_FLAGS=new Set(['--allow-development','--allow-qa','--allow-qa-fix-start','--auto-qa-fix',
|
|
66
|
-
'--allow-bootstrap-write','--rerun-unknown-qa','--rerun-blocked-qa','--failover',
|
|
67
|
-
'--supersede-reviewed-evidence',
|
|
68
|
-
...['red-test','baseline','regression','learning-writeback','walkthrough','finish','abandon',
|
|
85
|
+
'--allow-bootstrap-write','--allow-abandon-review','--allow-abandon-effect','--rerun-unknown-qa','--rerun-blocked-qa','--failover',
|
|
86
|
+
'--supersede-reviewed-evidence','--accept-superseded-code-drift','--rebind-spec-material',
|
|
87
|
+
...['red-test','baseline','regression','learning-writeback','walkthrough','finish','abandon','abandon-review',
|
|
69
88
|
'test-author','repair','cause-review','final-review'].map(name=>`--allow-qa-fix-${name}`)]);
|
|
70
89
|
const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
71
90
|
const nonempty=value=>typeof value==='string'&&value.trim().length>0;
|
|
91
|
+
// Needs the resolved --bootstrap-config path in permissions.
|
|
92
|
+
export const bootstrapDriverGap=(operation,definition,permissions)=>
|
|
93
|
+
inspectDriverBootstrap({advance:ADVANCE.has(operation),definition,permissions}).gap;
|
|
94
|
+
export const abandonReviewPlanError=(operation,plan,permissions)=>operation!=='abandon_review'?null:
|
|
95
|
+
plan.mode==='resume'&&permissions.includes('--allow-abandon-review')
|
|
96
|
+
&&typeof plan.reason==='string'&&plan.reason.trim().length>0
|
|
97
|
+
&&Buffer.byteLength(plan.reason,'utf8')<=500&&!/[\r\n\0]/.test(plan.reason)?null:
|
|
98
|
+
'abandon_review 需要 resume、--allow-abandon-review 与单行 reason(最多 500 UTF-8 字节)';
|
|
99
|
+
export const abandonEffectPlanError=(operation,plan,permissions)=>operation!=='abandon_effect'?null:
|
|
100
|
+
plan.mode==='resume'&&permissions.includes('--allow-abandon-effect')
|
|
101
|
+
&&typeof plan.reason==='string'&&plan.reason.trim().length>0
|
|
102
|
+
&&Buffer.byteLength(plan.reason,'utf8')<=500&&!/[\r\n\0]/.test(plan.reason)?null:
|
|
103
|
+
'abandon_effect 需要 resume、--allow-abandon-effect 与单行 reason(最多 500 UTF-8 字节)';
|
|
72
104
|
function requireShape(ok,label){if(!ok)stop(2,`答案格式错误:${label}`);}
|
|
73
105
|
function exact(value,allowed,label){requireShape(object(value)&&Object.keys(value).every(key=>allowed.includes(key)),label);}
|
|
74
106
|
function answerPath(root,file){return path.join(root,file);}
|
|
107
|
+
export const developFilename=(root,attempt)=>attemptAnswerName(root,'develop',attempt);
|
|
108
|
+
// develop.json.edits maps an approved scope path to one of:
|
|
109
|
+
// "content-file" write these bytes (existing mode kept, new file 0644)
|
|
110
|
+
// {file:"content-file",mode} write, then set mode
|
|
111
|
+
// {mode:"0755"|"0644"} only change the permission bits of an existing file
|
|
112
|
+
// {delete:true} delete an existing file
|
|
113
|
+
// A rename is a delete of the old path plus a write of the new one, both in scope.
|
|
114
|
+
const DEVELOP_MODES=new Map([['0644',0o644],['0755',0o755]]);
|
|
115
|
+
const answerError=message=>Object.assign(new Error(message),{answerShape:true});
|
|
116
|
+
function safeContentFile(local,root,label){
|
|
117
|
+
if(!(typeof local==='string'&&local.length>0&&!path.isAbsolute(local)&&!local.split(/[\\/]/).includes('..')))
|
|
118
|
+
throw answerError(`${label} 路径无效`);
|
|
119
|
+
const file=answerPath(root,local);
|
|
120
|
+
if(!(fs.existsSync(file)&&fs.lstatSync(file).isFile()&&!fs.lstatSync(file).isSymbolicLink()
|
|
121
|
+
&&fs.realpathSync(file).startsWith(fs.realpathSync(root)+path.sep)))throw answerError(`${label} 缺少安全的内容文件 ${file}`);
|
|
122
|
+
return local;
|
|
123
|
+
}
|
|
124
|
+
export function readDevelopEntry(target,entry,root,label='develop.json.edits'){
|
|
125
|
+
if(!nonempty(target))throw answerError(`${label} 路径无效`);
|
|
126
|
+
if(typeof entry==='string')return {kind:'write',local:safeContentFile(entry,root,label)};
|
|
127
|
+
const at=`${label}.${target}`;
|
|
128
|
+
if(!object(entry))throw answerError(`${at} 应为内容文件名,或 {file,mode} / {mode} / {delete:true}`);
|
|
129
|
+
const keys=Object.keys(entry).sort().join(',');
|
|
130
|
+
if(Object.hasOwn(entry,'delete')){
|
|
131
|
+
if(keys!=='delete')throw answerError(`${at}: delete 不能与 file、mode 同时出现`);
|
|
132
|
+
if(entry.delete!==true)throw answerError(`${at}.delete 只能是 true`);
|
|
133
|
+
return {kind:'delete'};
|
|
134
|
+
}
|
|
135
|
+
if(!['file','file,mode','mode'].includes(keys))throw answerError(`${at} 只允许 file、mode 或 delete 字段`);
|
|
136
|
+
if(Object.hasOwn(entry,'mode')&&!DEVELOP_MODES.has(entry.mode))throw answerError(`${at}.mode 只能是字符串 "0644" 或 "0755"`);
|
|
137
|
+
return Object.hasOwn(entry,'file')?{kind:'write',local:safeContentFile(entry.file,root,label),
|
|
138
|
+
...(Object.hasOwn(entry,'mode')?{mode:entry.mode}:{})}:{kind:'mode',mode:entry.mode};
|
|
139
|
+
}
|
|
140
|
+
function developEntries(map,root,label){
|
|
141
|
+
if(!object(map))throw answerError(`${label} 应为路径到内容文件或权限/删除声明的对象`);
|
|
142
|
+
return Object.entries(map).map(([target,entry])=>[target,readDevelopEntry(target,entry,root,label)]);
|
|
143
|
+
}
|
|
144
|
+
// Protected text mode carries content as JSON strings. Only well-formed UTF-8
|
|
145
|
+
// survives that round trip byte for byte (BOM and CRLF included); anything else
|
|
146
|
+
// would be silently replaced, so it is refused instead.
|
|
147
|
+
const strictUtf8=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
|
|
148
|
+
function protectedText(bytes,target){
|
|
149
|
+
try{return strictUtf8.decode(bytes);}
|
|
150
|
+
catch{throw answerError(`${target} 不是合法 UTF-8 文本;受保护模式只能提交 UTF-8 文本,二进制文件(图片、证书等)请移出 scope 或改用非受保护模式`);}
|
|
151
|
+
}
|
|
152
|
+
export function protectedDevelopEdits(map,answersRoot,codeProject,expected){
|
|
153
|
+
return developEntries(map,answersRoot,'develop.json.edits').map(([target,entry])=>{
|
|
154
|
+
const beforeSha256=expected?.[target]??null;
|
|
155
|
+
if(entry.kind==='delete')return {path:target,beforeSha256,content:null};
|
|
156
|
+
const source=entry.kind==='mode'?path.join(codeProject,target):answerPath(answersRoot,entry.local);
|
|
157
|
+
return {path:target,beforeSha256,content:protectedText(fs.readFileSync(source),target),
|
|
158
|
+
...(entry.mode?{mode:entry.mode}:{})};
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
export function applyDevelopEdits(map,answersRoot,codeProject,allowed){
|
|
162
|
+
const entries=developEntries(map,answersRoot,'develop.json.edits');
|
|
163
|
+
for(const [target,entry] of entries){
|
|
164
|
+
if(!allowed.includes(target))throw Error(`${target} 不在宿主允许的范围`);
|
|
165
|
+
const file=path.resolve(codeProject,target);
|
|
166
|
+
if(!file.startsWith(codeProject+path.sep))throw Error('编辑路径越界');
|
|
167
|
+
for(let parent=path.dirname(file);parent!==codeProject;parent=path.dirname(parent))
|
|
168
|
+
if(fs.existsSync(parent)&&fs.lstatSync(parent).isSymbolicLink())throw Error('编辑路径经过符号链接');
|
|
169
|
+
if(fs.existsSync(file)&&fs.lstatSync(file).isSymbolicLink())throw Error('编辑路径是符号链接');
|
|
170
|
+
if(entry.kind!=='write'&&!(fs.existsSync(file)&&fs.lstatSync(file).isFile()))throw Error(`${target} 不存在,无法删除或改权限`);
|
|
171
|
+
}
|
|
172
|
+
for(const [target,entry] of entries){
|
|
173
|
+
const file=path.resolve(codeProject,target);
|
|
174
|
+
if(entry.kind==='delete'){fs.unlinkSync(file);continue;}
|
|
175
|
+
if(entry.kind==='mode'){fs.chmodSync(file,DEVELOP_MODES.get(entry.mode));continue;}
|
|
176
|
+
const existed=fs.existsSync(file);
|
|
177
|
+
fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,fs.readFileSync(answerPath(answersRoot,entry.local)));
|
|
178
|
+
if(entry.mode||!existed)fs.chmodSync(file,entry.mode?DEVELOP_MODES.get(entry.mode):0o644);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
182
|
+
function diskScopeEntry(codeProject,target){
|
|
183
|
+
const file=path.join(codeProject,target);let stat;
|
|
184
|
+
try{stat=fs.lstatSync(file);}catch(error){if(error.code==='ENOENT'||error.code==='ENOTDIR')return null;throw error;}
|
|
185
|
+
if(!stat.isFile()||stat.isSymbolicLink())return {unsupported:true};
|
|
186
|
+
return {size:stat.size,mode:stat.mode&0o7777,source:file,
|
|
187
|
+
sha256:stat.size<=REVIEW_MATERIAL_LIMITS.file?sha256(fs.readFileSync(file)):null};
|
|
188
|
+
}
|
|
189
|
+
const kib=bytes=>`${bytes} 字节`;
|
|
190
|
+
// Everything the runner would refuse only after the answer is written and the
|
|
191
|
+
// checks have run is refused here instead, with the path and the limit. The
|
|
192
|
+
// runner stays the authority; this is the same rule applied earlier.
|
|
193
|
+
// What the next develop starts from, read the way the runner will read it: the
|
|
194
|
+
// baseline (the one the host is about to capture for a new run, or the run's own
|
|
195
|
+
// journaled one), the material the review package snapshot selects from the
|
|
196
|
+
// current tree (scope, requirements and every AGENTS.md), and the journal bytes
|
|
197
|
+
// the rest of the develop checkpoint already takes. Null when the host itself
|
|
198
|
+
// will report the problem.
|
|
199
|
+
// The develop checkpoint is the package (projected exactly below, handoff
|
|
200
|
+
// included) plus the rest of the runner frame. For the rest the driver takes the
|
|
201
|
+
// previous checkpoint of this run and adds upper bounds for what the new
|
|
202
|
+
// develop adds: its call, its cache entry (the previous status plus that call),
|
|
203
|
+
// the Learning result and the check evidence the stand-in checks cannot know.
|
|
204
|
+
const FRAME_ALLOWANCE=16*1024,CHECK_EVIDENCE_ALLOWANCE=512;
|
|
205
|
+
const size=value=>Buffer.byteLength(JSON.stringify(value??null));
|
|
206
|
+
export function journalRestBytes(records){
|
|
207
|
+
const last=records.findLast(row=>row.payload.type==='effect-checkpoint');
|
|
208
|
+
if(!last)return {restBytes:0,resultBytes:0,receiptsBytes:2,callsBytes:2};
|
|
209
|
+
const frame=last.payload.checkpoint;
|
|
210
|
+
return {restBytes:size(last.payload)-size(frame.reviewPackage),resultBytes:size(frame.cache.at(-1)?.result),
|
|
211
|
+
receiptsBytes:size(frame.receipts),callsBytes:size(frame.calls)};
|
|
212
|
+
}
|
|
213
|
+
export function developPreview({definition,codeProject=definition.codeProject,journal=null,parallelSelection=null,exact=true}){
|
|
214
|
+
let baseline=journal?.baseline??null;
|
|
215
|
+
try{
|
|
216
|
+
if(baseline===null){
|
|
217
|
+
// The same baseline the runner captures (taskReviewScope, specsRoot, specification).
|
|
218
|
+
baseline=captureReviewBaseline({root:codeProject,specsRoot:definition.specsDir,identity:definition.identity,
|
|
219
|
+
scope:taskReviewScope(definition.scope),requirements:definition.requirements,specification:{specsRoot:definition.specsDir,feature:definition.feature},
|
|
220
|
+
...(definition.codeProjects?{codeProjectPaths:codeProjectPaths(codeProject,resolveCodeProjects(codeProject,definition.codeProjects))}:{})});
|
|
221
|
+
// The new run journals this baseline as one record, next to its own metadata.
|
|
222
|
+
const bytes=Buffer.byteLength(JSON.stringify(baseline));
|
|
223
|
+
if(bytes+FRAME_ALLOWANCE>JOURNAL_PAYLOAD_LIMIT){
|
|
224
|
+
const largest=baseline.files.filter(file=>Object.hasOwn(file,'contentBase64')).sort((a,b)=>b.size-a.size).slice(0,3)
|
|
225
|
+
.map(file=>`${file.path} ${kib(file.size)}`).join(',');
|
|
226
|
+
stop(2,`任务基线的运行存档记录约 ${kib(bytes)},超过单条记录上限 ${JOURNAL_PAYLOAD_LIMIT}(含运行元数据);最大的基线材料是 ${largest};请把大文件移出 scope/requirements 后再建运行`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return {definition,baseline,material:reviewMaterialSizes({root:codeProject,baseline}),parallelSelection,
|
|
230
|
+
exact:exact&&!definition.codeProjects,...(journal?.frame??journalRestBytes([]))};
|
|
231
|
+
}catch(error){
|
|
232
|
+
if(error.code==='limit_exceeded')stop(2,`交付前的审查材料已超出审查包上限:${error.message}`);
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
// The package the runner will build for this delivery, byte for byte: the same
|
|
237
|
+
// Learning records, AGENTS.md writeback, handoff and package assembly, applied to
|
|
238
|
+
// the projected scope files. Digest values do not change any length, so the
|
|
239
|
+
// implementation hash stands in as 64 hex digits. Null when the runner would not
|
|
240
|
+
// build a package from it at all (blocked outcome, pending writeback, no change).
|
|
241
|
+
export function projectDevelopCheckpoint({preview,codeProject,attempt,value,projected,checks}){
|
|
242
|
+
const {definition}=preview,identity={...definition.identity,attempt};
|
|
243
|
+
if(value.value?.outcome!=='implemented')return null;
|
|
244
|
+
const learningInput=inspectCmAiTaskLearningInput({specsDir:definition.specsDir,codeProject,feature:definition.feature,
|
|
245
|
+
identity,applicableAgentFiles:[]},{admission:null,parallelSelection:preview.parallelSelection});
|
|
246
|
+
const binding={feature:definition.feature,identity,learningDigest:learningInput.learningDigest};
|
|
247
|
+
const application=createCmAiTaskLearningApplication({...binding,...value.value.application});
|
|
248
|
+
const retrospective=createCmAiTaskLearningRetrospective({...binding,...value.value.retrospective});
|
|
249
|
+
const files=new Map(projected);let includeAgents=false;
|
|
250
|
+
if(retrospective.status==='writeback_pending')return null;
|
|
251
|
+
if(retrospective.status==='lesson_candidate'){
|
|
252
|
+
const current=files.get('AGENTS.md'),disk=path.join(codeProject,'AGENTS.md');
|
|
253
|
+
const exists=current?current.contentBase64!==null:fs.existsSync(disk);
|
|
254
|
+
const source=!exists?'':current?Buffer.from(current.contentBase64,'base64').toString('utf8'):fs.readFileSync(disk,'utf8');
|
|
255
|
+
const plan=projectLearningWriteback({source,retrospective});
|
|
256
|
+
if(plan.outcome==='writeback_pending')return null;
|
|
257
|
+
if(plan.outcome==='written'){includeAgents=true;files.set('AGENTS.md',{path:'AGENTS.md',
|
|
258
|
+
contentBase64:Buffer.from(plan.content).toString('base64'),
|
|
259
|
+
mode:current?.mode??(exists?fs.statSync(disk).mode&0o7777:0o644)});}
|
|
260
|
+
}
|
|
261
|
+
const baseline=attemptBaseline(preview.baseline,attempt),scopeFiles=[...files.values()];
|
|
262
|
+
let initial;
|
|
263
|
+
try{initial=projectedReviewPackage({root:codeProject,baseline,checks,scopeFiles});}
|
|
264
|
+
catch(error){if(['empty_changes','out_of_scope','read_failed'].includes(error.code))return null;throw error;}
|
|
265
|
+
const {payload}=hostHandoffDocument({baseline,checks,reviewPackage:initial,implementationSha256:'0'.repeat(64)});
|
|
266
|
+
const handoff=taskLearningHandoffBytes({handoff:payload,feature:definition.feature,identity,learningInput,
|
|
267
|
+
application,retrospective,includeAgents});
|
|
268
|
+
const pkg=projectedReviewPackage({root:codeProject,baseline,checks,scopeFiles,handoff:{
|
|
269
|
+
name:`${definition.feature.replace(/^\d+\./,'')}-${identity.taskId}-a${attempt}-handoff.json`,
|
|
270
|
+
contentBase64:handoff.toString('base64'),mode:0o600}});
|
|
271
|
+
return {pkg,learningBytes:size({application,retrospective})};
|
|
272
|
+
}
|
|
273
|
+
// Stand-in results for the declared checks: the package carries their ids and
|
|
274
|
+
// commands, and their real evidence is only known once they run.
|
|
275
|
+
export const plannedCheckResults=commands=>(Array.isArray(commands)&&commands.length?commands:[{id:'check',command:['check']}])
|
|
276
|
+
.map(({id,command})=>({id,command,outcome:'passed',exitCode:0,evidence:'host check exited 0'}));
|
|
277
|
+
export function preflightDevelopDeliveries({deliveries,answersRoot,codeProject,scope,requirements,
|
|
278
|
+
baseline='disk',diskChecks=true,protectedMode=false,inputLimit=65536,preview=null,checks=plannedCheckResults(null)}){
|
|
279
|
+
const {file:FILE,total:TOTAL,count:COUNT}=REVIEW_MATERIAL_LIMITS;
|
|
280
|
+
let material=diskChecks&&preview?new Map(preview.material.map(item=>[item.path,item.size])):null;
|
|
281
|
+
const projected=new Map();
|
|
282
|
+
let previous=diskChecks?new Map(scope.map(target=>[target,diskScopeEntry(codeProject,target)])):null;
|
|
283
|
+
const base=!diskChecks?null:baseline==='disk'?previous:baseline;
|
|
284
|
+
// Without the tree (a later batch task), the scope files the answers write are
|
|
285
|
+
// still known to exist in the review material with exactly these sizes; the
|
|
286
|
+
// unknown rest can only add to the total. Their count is at most the scope's,
|
|
287
|
+
// which the run definition already caps at the package's file count. Which of
|
|
288
|
+
// them the package carries in full depends on the baseline that task starts
|
|
289
|
+
// from, so the driver cannot size its journal record here; an oversized
|
|
290
|
+
// delivery is caught by the runner after it is written and stays retryable
|
|
291
|
+
// (blocked/develop_package_too_large).
|
|
292
|
+
const delivered=diskChecks?null:new Map();
|
|
293
|
+
for(const {file,value,attempt=1} of deliveries){
|
|
294
|
+
if(value.status!=='succeeded')continue;
|
|
295
|
+
const label=path.basename(file);let entries;
|
|
296
|
+
try{entries=developEntries(value.edits,answersRoot,`${label}.edits`);}catch(error){stop(2,`答案格式错误:${error.message}`);}
|
|
297
|
+
const next=previous&&new Map(previous);
|
|
298
|
+
for(const [target,entry] of entries){
|
|
299
|
+
const before=previous?.get(target)??null;
|
|
300
|
+
// Scope and requirements may overlap; every review package must still carry
|
|
301
|
+
// each requirement file, so a delivery cannot delete one.
|
|
302
|
+
if(entry.kind==='delete'&&requirements.includes(target))
|
|
303
|
+
stop(2,`${label}.edits.${target}: 该路径同时列在运行定义的 requirements 中,审查包要求它存在,不能删除;可改写其内容,或先在新运行定义里把它移出 requirements`);
|
|
304
|
+
if(entry.kind!=='write'){
|
|
305
|
+
if(entry.kind==='delete')delivered?.delete(target);
|
|
306
|
+
if(previous&&(before===null||before.unsupported))
|
|
307
|
+
stop(2,`${label}.edits.${target}: 要${entry.kind==='delete'?'删除':'改权限'}的文件在交付前不存在或不是普通文件`);
|
|
308
|
+
next?.set(target,entry.kind==='delete'?null:{...before,mode:DEVELOP_MODES.get(entry.mode)});
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const source=answerPath(answersRoot,entry.local),size=fs.lstatSync(source).size;
|
|
312
|
+
if(size>FILE)stop(2,`${label}.edits.${target}: 内容 ${kib(size)},超过审查包单文件上限 ${FILE}(1 MiB);大文件请移出 scope`);
|
|
313
|
+
if(scope.includes(target))delivered?.set(target,size);
|
|
314
|
+
next?.set(target,{size,source,sha256:sha256(fs.readFileSync(source)),
|
|
315
|
+
mode:entry.mode?DEVELOP_MODES.get(entry.mode):before&&!before.unsupported?before.mode:0o644});
|
|
316
|
+
}
|
|
317
|
+
if(protectedMode){
|
|
318
|
+
const edits=[];
|
|
319
|
+
try{
|
|
320
|
+
for(const [target,entry] of entries){
|
|
321
|
+
if(entry.kind==='delete'){edits.push({path:target,beforeSha256:'0'.repeat(64),content:null});continue;}
|
|
322
|
+
const source=entry.kind==='write'?answerPath(answersRoot,entry.local):previous?.get(target)?.source??path.join(codeProject,target);
|
|
323
|
+
if(!fs.existsSync(source))continue;
|
|
324
|
+
edits.push({path:target,beforeSha256:'0'.repeat(64),content:protectedText(fs.readFileSync(source),target),
|
|
325
|
+
...(entry.mode?{mode:entry.mode}:{})});
|
|
326
|
+
}
|
|
327
|
+
}catch(error){stop(2,`${label}.edits: ${error.message}`);}
|
|
328
|
+
const uuid='00000000-0000-4000-8000-000000000000';
|
|
329
|
+
const bytes=Buffer.byteLength(JSON.stringify({type:'host_result',sessionId:uuid,callId:uuid,requestDigest:'0'.repeat(64),
|
|
330
|
+
result:{status:'succeeded',value:value.value,edits}}));
|
|
331
|
+
const max=4*1024*1024;
|
|
332
|
+
if(bytes>inputLimit)stop(2,`${label} 在受保护模式下的应答约 ${kib(bytes)},超过宿主输入上限 ${inputLimit}(--input-limit,默认 65536);`
|
|
333
|
+
+(bytes<=max?`在 PLAN.permissions 加 "--input-limit","${Math.min(max,2**Math.ceil(Math.log2(bytes)))}" 后重试`
|
|
334
|
+
:`已超过 --input-limit 最大值 ${max},受保护模式无法一次送达,请缩小本任务 scope 或拆分任务`));
|
|
335
|
+
}
|
|
336
|
+
if(delivered){
|
|
337
|
+
const total=[...delivered.values()].reduce((sum,size)=>sum+size,0);
|
|
338
|
+
const largest=[...delivered].sort((a,b)=>b[1]-a[1]).slice(0,3).map(([target,size])=>`${target} ${kib(size)}`).join(',');
|
|
339
|
+
if(total>TOTAL)stop(2,`${label}: 仅答案写入的 scope 文件就合计 ${kib(total)},超过审查包上限 ${TOTAL}(2 MiB),与该任务开跑时的树无关;最大的是 ${largest}`);
|
|
340
|
+
}
|
|
341
|
+
if(!next)continue;
|
|
342
|
+
for(const [target,entry] of next)if(entry&&!entry.unsupported&&entry.size>FILE)
|
|
343
|
+
stop(2,`${label}: 交付后 ${target} 为 ${kib(entry.size)},超过审查包单文件上限 ${FILE}(1 MiB);大文件请移出 scope`);
|
|
344
|
+
// The snapshot's material with this delivery's scope files applied on top.
|
|
345
|
+
if(material){
|
|
346
|
+
const after=new Map(material);
|
|
347
|
+
for(const [target,entry] of next){if(entry&&!entry.unsupported)after.set(target,entry.size);else after.delete(target);}
|
|
348
|
+
const total=[...after.values()].reduce((sum,size)=>sum+size,0);
|
|
349
|
+
const largest=[...after].sort((a,b)=>b[1]-a[1]).slice(0,3).map(([target,size])=>`${target} ${kib(size)}`).join(',');
|
|
350
|
+
if(total>TOTAL)stop(2,`${label}: 交付后审查材料(scope、requirements 与树中全部 AGENTS.md 正文)合计 ${kib(total)},超过审查包上限 ${TOTAL}(2 MiB);最大的是 ${largest}`);
|
|
351
|
+
if(after.size>COUNT)stop(2,`${label}: 交付后审查材料共 ${after.size} 个文件,超过审查包上限 ${COUNT}`);
|
|
352
|
+
material=after;
|
|
353
|
+
}
|
|
354
|
+
// The develop checkpoint journals the review package as one record. Build the
|
|
355
|
+
// package this delivery would produce with the runner's own assembly code and
|
|
356
|
+
// check it, plus the rest of the checkpoint, against the same budget.
|
|
357
|
+
const projectable=material&&entries.every(([target])=>!next.get(target)?.unsupported);
|
|
358
|
+
if(projectable){
|
|
359
|
+
for(const [target] of entries){
|
|
360
|
+
const after=next.get(target);
|
|
361
|
+
projected.set(target,after===null?{path:target,contentBase64:null,mode:null}
|
|
362
|
+
:{path:target,contentBase64:fs.readFileSync(after.source).toString('base64'),mode:after.mode});
|
|
363
|
+
}
|
|
364
|
+
const projection=preview.exact?projectDevelopCheckpoint({preview,codeProject,attempt,value,projected,checks}):null;
|
|
365
|
+
if(projection){
|
|
366
|
+
const {pkg}=projection,packageBytes=size(pkg);
|
|
367
|
+
const bytes=packageBytes+preview.restBytes+preview.resultBytes+projection.learningBytes
|
|
368
|
+
+FRAME_ALLOWANCE+CHECK_EVIDENCE_ALLOWANCE*checks.length;
|
|
369
|
+
const reserve=developCheckpointReserve({examinedPathsBytes:size(reviewPaths(pkg)),receiptsBytes:preview.receiptsBytes,
|
|
370
|
+
callsBytes:preview.callsBytes+1024,writebackBytes:1024});
|
|
371
|
+
const budget=JOURNAL_PAYLOAD_LIMIT-reserve;
|
|
372
|
+
if(bytes>budget){
|
|
373
|
+
const largest=pkg.changes.filter(change=>change.after).map(change=>change.after).sort((a,b)=>b.size-a.size).slice(0,3)
|
|
374
|
+
.map(file=>`${file.path} ${kib(file.size)}`).join(',');
|
|
375
|
+
stop(2,`${label}: 交付后的开发检查点约 ${kib(bytes)}(其中审查包 ${kib(packageBytes)},含 handoff),超过运行存档单条记录上限 ${JOURNAL_PAYLOAD_LIMIT} `
|
|
376
|
+
+`减去为有界审查与完成记录预留的 ${reserve}(即 ${budget});最大的改动文件是 ${largest};请缩小这些文件或移出 scope`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
// A Learning writeback can still change AGENTS.md, so only a delivery that
|
|
381
|
+
// cannot write it is known to be empty before the runner sees it.
|
|
382
|
+
const lessonFree=value.value?.outcome==='implemented'&&value.value.retrospective?.status==='no_new_lesson';
|
|
383
|
+
if(base&&lessonFree&&scope.every(target=>{
|
|
384
|
+
const a=base.get(target)??null,b=next.get(target)??null;
|
|
385
|
+
return a===null&&b===null||a!==null&&b!==null&&!a.unsupported&&!b.unsupported&&a.sha256!==null&&a.sha256===b.sha256&&a.mode===b.mode;
|
|
386
|
+
}))stop(2,`${label}: 交付后与任务基线相比没有任何改动(edits 为空,或内容和权限都与基线相同);审查包不能为空,请写入实际修改后再试`);
|
|
387
|
+
previous=next;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
// The original baseline of an existing run, keyed by scope path, from its journal.
|
|
391
|
+
export function baselineScope(baseline,scope){
|
|
392
|
+
const files=new Map((baseline?.files??[]).map(file=>[file.path,file]));
|
|
393
|
+
return new Map(scope.map(target=>{const file=files.get(target);
|
|
394
|
+
return [target,file?{size:file.size,mode:file.mode,sha256:file.sha256}:null];}));
|
|
395
|
+
}
|
|
396
|
+
export const inputLimitFrom=permissions=>{
|
|
397
|
+
const at=permissions.indexOf('--input-limit');
|
|
398
|
+
try{return parseHostInputLimit(at===-1?undefined:permissions[at+1]);}
|
|
399
|
+
catch{stop(2,'--input-limit 需要 65536–4194304 的整数(字节)');}
|
|
400
|
+
};
|
|
401
|
+
// Read-only view of an existing run: its runner state and original baseline.
|
|
402
|
+
export function readRunJournal(definition){
|
|
403
|
+
const snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,identity:{
|
|
404
|
+
repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});
|
|
405
|
+
const first=snapshot.records[0];
|
|
406
|
+
return {history:readRunnerHistory(snapshot.records,first.payload.config,3),baseline:first.payload.baseline,
|
|
407
|
+
frame:journalRestBytes(snapshot.records)};
|
|
408
|
+
}
|
|
409
|
+
function reachableDevelopAttempts({plan,operation,journal,permissions}){
|
|
410
|
+
if(plan.mode==='create'){
|
|
411
|
+
const reviewAfterDevelop=operation==='advance'
|
|
412
|
+
&&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&permissions[index+1]==='1');
|
|
413
|
+
return {attempts:reviewAfterDevelop?[1,2]:[1],reviewFirst:false,reviewAfterDevelop,packageDigest:null,learning:null};
|
|
414
|
+
}
|
|
415
|
+
if(journal.error)stop(2,`无法只读检查恢复存档: ${journal.error.code??journal.error.message}`);
|
|
416
|
+
// learning is the journal's Learning result the next develop effect starts from
|
|
417
|
+
// (bootstrap rules bind their on-disk files to its recorded evidence).
|
|
418
|
+
return {...projectDevelopAttempts(journal.history.state,operation,permissions),learning:journal.history.state.learningResult??null};
|
|
419
|
+
}
|
|
420
|
+
export function projectDevelopAttempts(status,operation,permissions){
|
|
421
|
+
const {state,attempt,reviewPackage}=status;
|
|
422
|
+
if(developmentRetryable(status))return {attempts:[attempt],reviewFirst:false,packageDigest:null};
|
|
423
|
+
if(state==='ready'&&attempt===1&&operation==='advance'
|
|
424
|
+
&&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&permissions[index+1]==='1'))
|
|
425
|
+
return {attempts:[1,2],reviewFirst:false,reviewAfterDevelop:true,packageDigest:null};
|
|
426
|
+
if(['ready','changes_requested'].includes(state))return {attempts:[attempt],reviewFirst:false,packageDigest:null};
|
|
427
|
+
if(operation==='advance'&&['awaiting_review','pending_review'].includes(state)
|
|
428
|
+
&&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&Number(permissions[index+1])===attempt)
|
|
429
|
+
&&attempt<2)return {attempts:[attempt+1],reviewFirst:true,
|
|
430
|
+
packageDigest:reviewPackage?.packageDigest??null};
|
|
431
|
+
return {attempts:[],reviewFirst:false,packageDigest:null};
|
|
432
|
+
}
|
|
75
433
|
function predictedQaAsks(definition,qa){
|
|
76
434
|
// Reuse the executor's validated initial plan for policy applicability.
|
|
77
435
|
// QA runs after this task completes, so project its task
|
|
@@ -124,7 +482,8 @@ export function validateCmAiAnswer(kind,value,root){
|
|
|
124
482
|
if(value.value.application)exact(value.value.application,['status','note'],'develop.json.value.application');
|
|
125
483
|
if(value.value.outcome==='implemented')try{readLearningRetrospectiveContent(value.value.retrospective);}
|
|
126
484
|
catch{stop(2,'答案格式错误:develop.json.value.retrospective');}
|
|
127
|
-
requireShape(object(value.edits),'develop.json.edits');
|
|
485
|
+
requireShape(object(value.edits),'develop.json.edits');
|
|
486
|
+
try{developEntries(value.edits,root,'develop.json.edits');}catch(error){stop(2,`答案格式错误:${error.message}`);}
|
|
128
487
|
}else {exact(value,['status','code'],'develop.json');requireShape(nonempty(value.code),'develop.json.code');}
|
|
129
488
|
}else if(kind==='qa_assess'){
|
|
130
489
|
try{decideHostQaPolicy({assessment:value,pending:1,mergeEligible:false,unassessedTasks:1});}
|
|
@@ -162,15 +521,18 @@ export function validateCmAiAnswer(kind,value,root){
|
|
|
162
521
|
}
|
|
163
522
|
function load(){
|
|
164
523
|
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
165
|
-
process.stdout.write('用法: cm-ai-drive.mjs --plan PLAN.json <operation>\nPLAN: config, mode, hostContext, originalHostContext (resume), runtime, permissions, answers, checks。\n人工答案放 answers/;check 只运行 PLAN.checks
|
|
524
|
+
process.stdout.write('用法: cm-ai-drive.mjs --plan PLAN.json <operation>\nPLAN: config, mode, hostContext, originalHostContext (换会话 resume 必填), runtime, permissions, answers, checks, checkTimeoutMs。\nchecks 每项为 {id,command,timeoutMs?};checkTimeoutMs 与每项 timeoutMs 为 1..3600000 整数,默认 900000 ms(15 分钟)。\nabandon_review 需要 mode:resume、permissions:["--allow-abandon-review"] 与 PLAN.reason;abandon_effect 需要 mode:resume、permissions:["--allow-abandon-effect"] 与 PLAN.reason(均为单行、最多 500 UTF-8 字节)。\n人工答案放 answers/;check 只运行 PLAN.checks,不读取静态执行证据。bootstrap T-001 骨架可用;T-002 规范任务(纯规范 scope、单代码根、非 --protected-config)读 answers/init-generate.json({status:"generated",documents:[{path,contentFile}]},覆盖全部 targets)与 answers/init-verify.json(commands 为驾驶员实跑的草稿命令 {id,command,timeoutMs?},可选 commandsNotRun;checks 只含 globs/file_references/constraint_preservation/rule_applicability;constraintChanges:[];application/retrospective 沿原 Learning);第 1 轮也可用 *-a1.json,第 2 轮只读 init-generate-a2.json 与 init-verify-a2.json,且须先 decision 读取首轮 findings,不能带 --allow-review-attempt 跨轮。commands 在宿主接受启动后、发送操作前由驾驶员实跑(须先带 --allow-bootstrap-write 等宿主授权;受保护模式在 specs 沙箱内),失败或改动了预检核对的文件即退出 2 且不发送操作(create 时改用 resume 重跑);结果只来自实跑,答案文件不能提供。\n'
|
|
525
|
+
+'develop.json.edits 每项是 scope 路径到下列之一:"内容文件"(写入;已有文件保留权限,新文件 0644)、{"file":"内容文件","mode":"0755"|"0644"}、{"mode":"0755"|"0644"}(只改已有文件权限)、{"delete":true}(删除已有文件)。改名 = 删旧路径 + 写新路径,两者都要在 scope 内;同时列在 requirements 里的路径不能删除。\n'
|
|
526
|
+
+'启动前拒绝:单个 scope 文件超过 1 MiB、审查材料(按审查包快照:scope、requirements 与树中全部 AGENTS.md 正文)合计超过 2 MiB 或超过 256 个文件、交付后与任务基线完全相同(edits 为空或内容和权限都没变)、开发检查点(含 handoff 与 AGENTS.md 回写,按宿主同一套构建代码计)装不进运行存档单条 1 MiB 记录减去为有界审查与完成记录推出的预留,或任务基线装不进一条记录。受保护模式(--protected-conversation-config)只收合法 UTF-8 文本,应答大于 --input-limit(默认 65536)时提示应加的值。\n'
|
|
527
|
+
+'runId 需 8–128 个字符(运行日志要求),create 前检查。resume 时按存档里的当前轮次发送 identity,第 2 轮的 decision/complete/qa 等无需手改。\n');
|
|
166
528
|
process.exit(0);
|
|
167
529
|
}
|
|
168
530
|
const loaded=loadPlanFile({name:'cm-ai-drive.mjs',known:OPERATIONS});
|
|
169
531
|
const {plan,operation,base}=loaded;
|
|
170
532
|
requireFields(plan,['config','mode','hostContext','permissions']);
|
|
533
|
+
try{planCheckTimeout(plan);}catch(error){stop(2,error.message);}
|
|
171
534
|
if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
|
|
172
535
|
if(!nonempty(plan.hostContext))stop(2,'hostContext 必须是当前真实会话 ID');
|
|
173
|
-
if(plan.mode==='resume'&&!nonempty(plan.originalHostContext))stop(2,'resume 需要 originalHostContext');
|
|
174
536
|
if(plan.mode==='create'&&plan.originalHostContext)stop(2,'originalHostContext 只在 resume 时有意义');
|
|
175
537
|
if(!Array.isArray(plan.permissions)||!plan.permissions.every(x=>typeof x==='string'))stop(2,'permissions 必须是宿主参数数组');
|
|
176
538
|
const permissions=[];
|
|
@@ -184,31 +546,54 @@ function load(){
|
|
|
184
546
|
const supersedeReason=permissions.includes('--supersede-reason');
|
|
185
547
|
if(supersedeFlag!==supersedeReason)
|
|
186
548
|
stop(2,'--supersede-reviewed-evidence 与 --supersede-reason 必须同时提供');
|
|
549
|
+
if(permissions.includes('--accept-superseded-code-drift')&&!supersedeFlag)
|
|
550
|
+
stop(2,'--accept-superseded-code-drift 需要 --supersede-reviewed-evidence 与 --supersede-reason');
|
|
187
551
|
if(supersedeFlag&&plan.mode!=='create')stop(2,'supersede 只允许 mode create');
|
|
552
|
+
if(permissions.includes('--rebind-spec-material')!==permissions.includes('--spec-rebind-reason')
|
|
553
|
+
||permissions.includes('--rebind-spec-material')&&plan.mode!=='resume')
|
|
554
|
+
stop(2,'--rebind-spec-material 只用于 mode resume,并须同时提供 --spec-rebind-reason 原因');
|
|
555
|
+
const abandonError=abandonReviewPlanError(operation,plan,permissions);
|
|
556
|
+
if(abandonError)stop(2,abandonError);
|
|
557
|
+
const abandonEffectError=abandonEffectPlanError(operation,plan,permissions);
|
|
558
|
+
if(abandonEffectError)stop(2,abandonEffectError);
|
|
188
559
|
const config=path.resolve(base,plan.config),answers=plan.answers?path.resolve(base,plan.answers):null;
|
|
189
560
|
if(!fs.existsSync(config))stop(2,`运行定义不存在: ${config}`);
|
|
190
561
|
let definition;
|
|
191
562
|
try{definition=readRunDefinition(config);}catch(error){stop(2,`运行定义无效或 codeProject/specsDir 无法解析: ${error.code??error.message}`);}
|
|
563
|
+
if(plan.mode==='create')try{assertCreatableRunId(definition.identity);}
|
|
564
|
+
catch(error){stop(2,`运行定义的 ${error.code.replace(/^invalid_config: /,'')};宿主未启动,请换一个更长的 runId`);}
|
|
192
565
|
const store=path.join(definition.specsDir,'.reviews','.execution',definition.identity.runId);
|
|
193
566
|
if(plan.mode==='resume'&&!fs.existsSync(path.join(store,'state.json')))stop(2,`恢复存档不存在: ${store}`);
|
|
567
|
+
let journal=null;
|
|
568
|
+
if(plan.mode==='resume')try{journal=readRunJournal(definition);}catch(error){journal={error};}
|
|
569
|
+
// The run definition always says attempt 1. Package-bound operations must name
|
|
570
|
+
// the attempt the run is on now, so send that; an unreadable journal keeps the
|
|
571
|
+
// original identity and the host decides, exactly as before.
|
|
572
|
+
const identity=journal?.history?{...definition.identity,attempt:journal.history.state.attempt}:definition.identity;
|
|
194
573
|
const workflowAt=permissions.indexOf('--workflow-config');let workflow=null;
|
|
195
574
|
if(workflowAt!==-1){
|
|
196
575
|
const file=path.resolve(base,permissions[workflowAt+1]);workflow=readJson(file,'workflow-config');
|
|
197
576
|
if(workflow===undefined)stop(2,`workflow-config 不存在: ${file}`);
|
|
198
577
|
permissions[workflowAt+1]=file;
|
|
199
578
|
}
|
|
579
|
+
const permissionFiles=[];
|
|
200
580
|
for(let i=0;i<permissions.length;i++)if(PAIR_FLAGS.has(permissions[i])
|
|
201
581
|
&&permissions[i]!=='--allow-review-attempt'&&permissions[i]!=='--browser-qa'
|
|
202
|
-
&&permissions[i]!=='--qa-config-revision-reason'&&permissions[i]!=='--allow-provider-development-attempt'
|
|
203
|
-
&&permissions[i]!=='--supersede-reason'){
|
|
582
|
+
&&permissions[i]!=='--qa-config-revision-reason'&&permissions[i]!=='--qa-environment-failure'&&permissions[i]!=='--allow-provider-development-attempt'
|
|
583
|
+
&&permissions[i]!=='--supersede-reason'&&permissions[i]!=='--spec-rebind-reason'&&permissions[i]!=='--input-limit'){
|
|
204
584
|
const file=path.resolve(base,permissions[i+1]);if(!fs.existsSync(file))stop(2,`${permissions[i]} 文件不存在: ${file}`);
|
|
205
|
-
permissions[i+1]=file;i++;
|
|
585
|
+
permissions[i+1]=file;permissionFiles.push(file);i++;
|
|
206
586
|
}
|
|
587
|
+
const bootstrap=inspectDriverBootstrap({advance:ADVANCE.has(operation),definition,permissions});
|
|
588
|
+
if(bootstrap.gap)stop(2,bootstrap.gap);
|
|
589
|
+
const rules=bootstrap.mode==='instructions';
|
|
207
590
|
const providerMode=permissions.includes('--protected-config');
|
|
208
591
|
const protectedMode=providerMode||permissions.includes('--protected-conversation-config');
|
|
209
592
|
const asks=[];
|
|
210
593
|
if(ADVANCE.has(operation)){
|
|
211
|
-
|
|
594
|
+
// A pure rules scope never reaches develop: host-bootstrap.mjs asks the session instead.
|
|
595
|
+
if(rules)asks.push('init_generate','init_verify');
|
|
596
|
+
else if(!providerMode)asks.push('develop');
|
|
212
597
|
if(!protectedMode)asks.push('check');
|
|
213
598
|
}
|
|
214
599
|
if(plan.verificationPrecheck===true&&(ADVANCE.has(operation)||operation==='complete'))asks.push('verification_precheck');
|
|
@@ -227,28 +612,62 @@ function load(){
|
|
|
227
612
|
if(['fix_advance','fix_run'].includes(operation))asks.push(...new Set(Object.values(FIX_ASKS).flat()));
|
|
228
613
|
if(operation==='fix_action'){
|
|
229
614
|
if(!FIX_ACTIONS.has(plan.fixOperation))stop(2,'fix_action 需要宿主支持的 fixOperation');
|
|
230
|
-
|
|
231
|
-
|
|
615
|
+
const abandonFlag=plan.fixOperation==='abandon_review'?'--allow-qa-fix-abandon-review':'--allow-qa-fix-abandon';
|
|
616
|
+
if(['abandon_step','abandon_review'].includes(plan.fixOperation)&&(!nonempty(plan.reason)
|
|
617
|
+
||!permissions.includes(abandonFlag)))stop(2,`${plan.fixOperation} 需要 reason 与 ${abandonFlag}`);
|
|
232
618
|
asks.push(...(FIX_ASKS[plan.fixOperation]??[]));
|
|
233
619
|
}
|
|
234
620
|
if(['qa_logic','qa_browser','verification_precheck'].some(kind=>asks.includes(kind)))
|
|
235
621
|
stop(2,`缺少真实执行 runner: ${asks.filter(kind=>['qa_logic','qa_browser','verification_precheck'].includes(kind)).join(', ')};不能从静态答案文件应答`);
|
|
236
622
|
if(asks.includes('check')){
|
|
237
623
|
if(!Array.isArray(plan.checks)||plan.checks.length===0)stop(2,'步骤会反问 check,但 PLAN.checks 缺少真实命令列表');
|
|
238
|
-
try{
|
|
624
|
+
try{
|
|
625
|
+
for(const item of plan.checks){
|
|
626
|
+
if(!object(item)||Object.keys(item).some(key=>!['id','command','timeoutMs'].includes(key)))throw Error('PLAN.checks 每项只允许 id、command、timeoutMs');
|
|
627
|
+
planCheckTimeout(plan,item);
|
|
628
|
+
}
|
|
629
|
+
createHostCheck({cwd:definition.codeProject,commands:plan.checks.map(({id,command})=>({id,command}))});
|
|
630
|
+
}
|
|
239
631
|
catch(error){stop(2,`PLAN.checks 格式错误: ${error.code??error.message}`);}
|
|
240
632
|
}
|
|
241
|
-
const
|
|
633
|
+
const reachable=(asks.includes('develop')||rules)&&!providerMode
|
|
634
|
+
?reachableDevelopAttempts({plan,operation,journal,permissions})
|
|
635
|
+
:{attempts:[],reviewFirst:false,packageDigest:null};
|
|
636
|
+
const bootstrapAnswers=rules
|
|
637
|
+
?readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable}):null;
|
|
638
|
+
const developAnswers=new Map(),deliveries=[];
|
|
639
|
+
if(asks.includes('develop'))for(const attempt of reachable.attempts){
|
|
640
|
+
const file=answerPath(answers??'',developFilename(answers??'',attempt));
|
|
641
|
+
if(!answers||!fs.existsSync(file)){
|
|
642
|
+
const reviewFile=`.reviews/${definition.feature.replace(/^\d+\./,'')}-${definition.identity.taskId}-r1.md`;
|
|
643
|
+
if(reachable.reviewAfterDevelop&&attempt===2)
|
|
644
|
+
stop(2,`缺少 ${file};本次 advance 带 --allow-review-attempt 1,宿主完成首轮审查后可能直接进入第 2 轮 develop。可选:1) 从 PLAN.permissions 移除 --allow-review-attempt 1,先 advance 到 awaiting_review;再用该运行返回的 packageDigest 执行 decision,读取 ${reviewFile} 的 findings;若要求修改,写 answers/develop-a2.json 后 advance。2) 若有意一次跑完,预先写 answers/develop-a2.json 后重试 advance。develop-a2.json 必须针对首轮 findings 修改;与第 1 轮被要求修改的代码逐字节相同时,第 2 轮停在 blocked/develop_unchanged_after_review,不送审,改好后再 advance。`);
|
|
645
|
+
if(reachable.reviewFirst)stop(2,`缺少 ${path.basename(file)};请先以 decision 和当前 packageDigest ${reachable.packageDigest} 单独运行审查,读取 .reviews/${definition.feature.replace(/^\d+\./,'')}-${definition.identity.taskId}-r${attempt-1}.md 中的 findings,写 answers/develop-a${attempt}.json 后再 advance`);
|
|
646
|
+
stop(2,`步骤 ${operation} 会反问 develop,但答案文件不存在: ${file}`);
|
|
647
|
+
}
|
|
648
|
+
const value=readJson(file,'develop');validateCmAiAnswer('develop',value,answers);
|
|
649
|
+
if(value.status==='succeeded')for(const target of Object.keys(value.edits))
|
|
650
|
+
if(!definition.scope.includes(target))stop(2,`${path.basename(file)}.edits 越过批准 scope: ${target}`);
|
|
651
|
+
developAnswers.set(attempt,value);deliveries.push({file,value,attempt});
|
|
652
|
+
}
|
|
653
|
+
if(deliveries.length)preflightDevelopDeliveries({deliveries,answersRoot:answers,codeProject:definition.codeProject,
|
|
654
|
+
scope:definition.scope,requirements:definition.requirements,
|
|
655
|
+
baseline:plan.mode==='create'?'disk':baselineScope(journal.baseline,definition.scope),
|
|
656
|
+
protectedMode,inputLimit:inputLimitFrom(permissions),checks:plannedCheckResults(protectedMode?null:plan.checks),
|
|
657
|
+
preview:developPreview({definition,journal:plan.mode==='create'?null:journal,
|
|
658
|
+
exact:!permissions.includes('--bootstrap-config')})});
|
|
659
|
+
const unique=[...new Set(asks.filter(kind=>FILES[kind]&&kind!=='develop'))];
|
|
242
660
|
const answer=preflightAnswers(unique,kind=>{
|
|
243
661
|
const file=answerPath(answers??'',FILES[kind]);
|
|
244
662
|
if(!answers||!fs.existsSync(file))stop(2,`步骤 ${operation} 会反问 ${kind},但答案文件不存在: ${file}`);
|
|
245
663
|
const value=readJson(file,kind);validateCmAiAnswer(kind,value,answers);return value;
|
|
246
664
|
});
|
|
247
|
-
if(answer.develop?.status==='succeeded')for(const target of Object.keys(answer.develop.edits))
|
|
248
|
-
if(!definition.scope.includes(target))stop(2,`develop.json.edits 越过批准 scope: ${target}`);
|
|
249
665
|
if(answer.documentation_sync)for(const target of Object.keys(answer.documentation_sync.edits))
|
|
250
666
|
if(!workflow.documentationPaths.includes(target))stop(2,`documentation-sync.json.edits 越过文档 scope: ${target}`);
|
|
251
|
-
return {...loaded,definition,permissions,config,answers,answer
|
|
667
|
+
return {...loaded,definition,identity,permissions,config,answers,answer,developAnswers,
|
|
668
|
+
bootstrapRules:bootstrapAnswers&&createBootstrapRulesResponder({definition,plan,bootstrap,answers:bootstrapAnswers,
|
|
669
|
+
// Same execution as the task checks: the host's specs sandbox in protected mode, else the driver's own.
|
|
670
|
+
specsRoot:protectedMode?definition.specsDir:null,watch:[config,...permissionFiles]})};
|
|
252
671
|
}
|
|
253
672
|
function applyEdits(map,root,allowed){
|
|
254
673
|
for(const target of Object.keys(map)){
|
|
@@ -278,11 +697,15 @@ export function qaFixAnswerFor(row,answer,answerRoot){
|
|
|
278
697
|
return value??null;
|
|
279
698
|
}
|
|
280
699
|
async function answerFor(row,answer){
|
|
281
|
-
|
|
700
|
+
if(['init_generate','init_verify'].includes(row.kind))return loaded.bootstrapRules?.[row.kind](row)??null;
|
|
701
|
+
const kind=row.kind,value=kind==='develop'
|
|
702
|
+
?loaded.developAnswers.get(row.payload.request?.identity?.attempt??row.payload.identity?.attempt)
|
|
703
|
+
:answer[kind];
|
|
282
704
|
if(kind==='check'){
|
|
283
705
|
const results=[];
|
|
284
706
|
for(const command of loaded.plan.checks){
|
|
285
|
-
const run=createHostCheck({cwd:loaded.definition.codeProject,commands:[command],
|
|
707
|
+
const run=createHostCheck({cwd:loaded.definition.codeProject,commands:[{id:command.id,command:command.command}],
|
|
708
|
+
timeoutMs:planCheckTimeout(loaded.plan,command),
|
|
286
709
|
onOutput:({stream,chunk})=>{process.stderr.write(`[drive check ${command.id} ${stream}] ${chunk.toString('utf8')}`);}});
|
|
287
710
|
const [item]=await run({identity:row.payload.identity},{signal:new AbortController().signal});
|
|
288
711
|
results.push(item);
|
|
@@ -291,13 +714,11 @@ async function answerFor(row,answer){
|
|
|
291
714
|
return results;
|
|
292
715
|
}
|
|
293
716
|
if(kind==='develop'){
|
|
717
|
+
if(!value)throw Error(`develop attempt ${row.payload.request?.identity?.attempt??row.payload.identity?.attempt} 未预检,拒绝复用旧答案`);
|
|
294
718
|
if(value.status!=='succeeded')return {status:'failed',code:value.code};
|
|
295
|
-
if(row.payload.editMode==='protected-text-v1'){
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
return {status:'succeeded',value:value.value,edits};
|
|
299
|
-
}
|
|
300
|
-
applyEdits(value.edits,loaded.definition.codeProject,row.payload.request.payload.scope);
|
|
719
|
+
if(row.payload.editMode==='protected-text-v1')return {status:'succeeded',value:value.value,
|
|
720
|
+
edits:protectedDevelopEdits(value.edits,loaded.answers,loaded.definition.codeProject,row.payload.expected)};
|
|
721
|
+
applyDevelopEdits(value.edits,loaded.answers,loaded.definition.codeProject,row.payload.request.payload.scope);
|
|
301
722
|
return {status:'succeeded',value:value.value};
|
|
302
723
|
}
|
|
303
724
|
if(kind==='documentation_sync'){
|
|
@@ -309,26 +730,38 @@ async function answerFor(row,answer){
|
|
|
309
730
|
if(kind.startsWith('fix_'))return qaFixAnswerFor(row,answer,loaded.answers);
|
|
310
731
|
return value??null;
|
|
311
732
|
}
|
|
312
|
-
function
|
|
733
|
+
export function buildCmAiDriveRequest(operation,plan,definition,identity=definition.identity){
|
|
734
|
+
return {version:1,identity,
|
|
735
|
+
...(['abandon_review','abandon_effect'].includes(operation)?{reason:plan.reason}:{}),
|
|
736
|
+
...(PACKAGE_OPERATIONS.has(operation)?{packageDigest:plan.packageDigest}:{}),
|
|
737
|
+
...(TEST_RUN_OPERATIONS.has(operation)?{testRunId:plan.testRunId}:{}),
|
|
738
|
+
...(['fix_status','fix_advance','fix_action','fix_run'].includes(operation)?{
|
|
739
|
+
packageDigest:plan.packageDigest,testRunId:plan.testRunId,
|
|
740
|
+
...(operation==='fix_action'?{fixOperation:plan.fixOperation,
|
|
741
|
+
...(['abandon_step','abandon_review'].includes(plan.fixOperation)?{reason:plan.reason}:{})}: {})}: {})};
|
|
742
|
+
}
|
|
743
|
+
export function buildCmAiDriveHostArgs(plan,permissions,config){
|
|
744
|
+
return ['serve','--config',config,'--mode',plan.mode,'--host-context',plan.hostContext,
|
|
745
|
+
'--allow-development',
|
|
746
|
+
...(plan.originalHostContext?['--original-host-context',plan.originalHostContext]:[]),
|
|
747
|
+
'--runtime',plan.runtime??'codex',...permissions.filter(flag=>flag!=='--allow-development')];
|
|
748
|
+
}
|
|
749
|
+
async function main(){
|
|
313
750
|
loaded=load();
|
|
314
751
|
const {plan,operation,definition,permissions,config,answer}=loaded;
|
|
315
752
|
if(PACKAGE_OPERATIONS.has(operation)&&!(typeof plan.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(plan.packageDigest)))
|
|
316
753
|
stop(2,`${operation} 需要 packageDigest(64 位十六进制)`);
|
|
317
754
|
if(TEST_RUN_OPERATIONS.has(operation)&&!(operation==='qa_result'?nonempty(plan.testRunId)
|
|
318
755
|
:plan.testRunId===null||nonempty(plan.testRunId)))stop(2,`${operation} 需要 testRunId(可为 null)`);
|
|
319
|
-
const request=
|
|
320
|
-
...(PACKAGE_OPERATIONS.has(operation)?{packageDigest:plan.packageDigest}:{}),
|
|
321
|
-
...(TEST_RUN_OPERATIONS.has(operation)?{testRunId:plan.testRunId}:{}),
|
|
322
|
-
...(['fix_status','fix_advance','fix_action','fix_run'].includes(operation)?{
|
|
323
|
-
packageDigest:plan.packageDigest,testRunId:plan.testRunId,
|
|
324
|
-
...(operation==='fix_action'?{fixOperation:plan.fixOperation,
|
|
325
|
-
...(plan.fixOperation==='abandon_step'?{reason:plan.reason}:{})}: {})}: {})};
|
|
756
|
+
const request=buildCmAiDriveRequest(operation,plan,definition,loaded.identity);
|
|
326
757
|
if(operation.startsWith('fix_')&&(!nonempty(plan.packageDigest)||!nonempty(plan.testRunId)))
|
|
327
758
|
stop(2,`${operation} 需要 packageDigest 和 testRunId`);
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
answers:answer,paths:{answers:loaded.answers},answerFor
|
|
759
|
+
// Rules init_verify commands really run once the host has accepted the launch
|
|
760
|
+
// (host_ready) and before the operation is sent: a failure never becomes an
|
|
761
|
+
// unknown develop effect, and the host's own launch validation came first.
|
|
762
|
+
driveHost({host:HOST,args:buildCmAiDriveHostArgs(plan,permissions,config),cwd:definition.codeProject,operation,request,
|
|
763
|
+
answers:answer,paths:{answers:loaded.answers},answerFor,
|
|
764
|
+
...(loaded.bootstrapRules?{beforeRequest:()=>loaded.bootstrapRules.prepare(plan.mode)}:{})});
|
|
333
765
|
}
|
|
334
|
-
if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))
|
|
766
|
+
if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))
|
|
767
|
+
main().catch(error=>stop(1,`驾驶员失败:${error.message}`));
|