@aibyzero/cm-workflow 0.16.4 → 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 +50 -0
- package/README.md +12 -1
- package/VERSION +1 -1
- package/docs/installation.md +21 -1
- package/docs/js-workflow-control.md +245 -33
- 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 +12 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -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 +12 -4
- 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-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 +3 -1
- 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 +10 -3
- package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
- package/scripts/cm-ai-admission.mjs +18 -11
- package/scripts/cm-ai-admission.test.mjs +65 -1
- package/scripts/cm-ai-batch-drive.mjs +92 -20
- package/scripts/cm-ai-batch-drive.test.mjs +164 -3
- package/scripts/cm-ai-batch-host.mjs +27 -11
- package/scripts/cm-ai-batch-host.test.mjs +2 -1
- 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 +479 -47
- package/scripts/cm-ai-drive.test.mjs +240 -10
- package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
- package/scripts/cm-ai-host.mjs +84 -25
- package/scripts/cm-ai-host.test.mjs +232 -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.test.mjs +1 -1
- package/scripts/cm-check-host.test.mjs +1 -1
- package/scripts/cm-check-runtime.sh +1 -1
- package/scripts/cm-claude-developer-worker.test.mjs +3 -1
- package/scripts/cm-claude-probe.test.mjs +9 -1
- package/scripts/cm-claude-review-stream.test.mjs +25 -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 +75 -0
- package/scripts/cm-prd-draft.test.mjs +14 -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 +9 -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 +12 -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-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 +261 -42
- package/skills/cm-fix/references/js-host.md +22 -1
- package/skills/cm-prd/references/js-change-recovery.md +1 -1
- package/skills/cm-prd/references/js-host.md +6 -0
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
// Single-task driver support for the approved bootstrap rules task (host-bootstrap.mjs).
|
|
2
|
+
// init_generate returns the current session's documents; they come from a
|
|
3
|
+
// per-attempt answer file, validated before the host starts.
|
|
4
|
+
// init_verify has two parts. globs/file_references/constraint_preservation/
|
|
5
|
+
// rule_applicability and Learning are the session's own report (the host marks
|
|
6
|
+
// it host verification, not Review), so they come from a per-attempt answer file.
|
|
7
|
+
// The commands group is execution evidence: only commands this driver really
|
|
8
|
+
// runs produce it; an answer file can list commands but never their results.
|
|
9
|
+
// They run after the host accepted the launch (host_ready: every launch input,
|
|
10
|
+
// admission, task selection and the run store) and before any operation is sent
|
|
11
|
+
// (prepare): a failure is refused before the develop effect exists, because any
|
|
12
|
+
// init_verify failure inside the host leaves it unknown with no in-run recovery
|
|
13
|
+
// (host-bootstrap.mjs run()). Static refusals reuse the host's own readers and
|
|
14
|
+
// admission functions, and every file the preflight bound is re-read afterwards.
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
18
|
+
import {createHash} from 'node:crypto';
|
|
19
|
+
import {createHostCheck} from './host-check.mjs';
|
|
20
|
+
import {inspectCmAiAdmission,inspectCmAiBootstrapTask,matchesCmAiTaskSelection} from './cm-ai-admission.mjs';
|
|
21
|
+
import {readBootstrapConfiguration,readConversationProtection} from '../../../scripts/cm-ai-host.mjs';
|
|
22
|
+
import {mergeBootstrapAgents} from './host-bootstrap.mjs';
|
|
23
|
+
import {createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective} from './cm-ai-context-refresh.mjs';
|
|
24
|
+
import {cmInitRuleTargets,validateCmInitSelection} from '../cm-init/draft-generation.mjs';
|
|
25
|
+
import {inspectCmInitDraft,readCmInitSource} from '../cm-init/draft-inspection.mjs';
|
|
26
|
+
import {stop,readJson,planCheckTimeout} from './drive-core.mjs';
|
|
27
|
+
import {need} from './effect-contract.mjs';
|
|
28
|
+
|
|
29
|
+
const CATEGORIES=['commands','globs','file_references','constraint_preservation','rule_applicability'];
|
|
30
|
+
const REPORTED=CATEGORIES.slice(1);
|
|
31
|
+
// cm-ai-host.mjs uses createHostToolBridge() defaults: one host_result is at most 64 KiB.
|
|
32
|
+
const RESPONSE_LIMIT=64*1024;
|
|
33
|
+
const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
34
|
+
const nonempty=value=>typeof value==='string'&&value.trim().length>0;
|
|
35
|
+
const oneLine=(value,limit)=>nonempty(value)&&Buffer.byteLength(value,'utf8')<=limit&&!/[\r\n\0]/.test(value);
|
|
36
|
+
const refuse=(ok,line)=>{if(!ok)stop(2,line);};
|
|
37
|
+
const envelope=result=>Buffer.byteLength(JSON.stringify({type:'host_result',sessionId:'0'.repeat(36),
|
|
38
|
+
callId:'0'.repeat(36),requestDigest:'0'.repeat(64),result}),'utf8');
|
|
39
|
+
const learningSection=source=>/^## 项目教训[ \t]*\r?$/gmu.test(source);
|
|
40
|
+
const sha=bytes=>bytes===null?null:createHash('sha256').update(bytes).digest('hex');
|
|
41
|
+
|
|
42
|
+
export function attemptAnswerName(root,name,attempt){
|
|
43
|
+
if(attempt!==1)return `${name}-a${attempt}.json`;
|
|
44
|
+
const legacy=fs.existsSync(path.join(root,`${name}.json`)),named=fs.existsSync(path.join(root,`${name}-a1.json`));
|
|
45
|
+
if(legacy&&named)stop(2,`${name}.json 与 ${name}-a1.json 不能同时存在`);
|
|
46
|
+
return named?`${name}-a1.json`:`${name}.json`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Returns {mode,gap}; gap is a refusal for a bootstrap case this driver does not support.
|
|
50
|
+
export function inspectDriverBootstrap({advance,definition,permissions}){
|
|
51
|
+
if(!advance||!permissions.includes('--bootstrap-config'))return {mode:null,gap:null};
|
|
52
|
+
let task;
|
|
53
|
+
try{task=inspectCmAiBootstrapTask({specsDir:definition.specsDir,codeProject:definition.codeProject,
|
|
54
|
+
taskId:definition.identity.taskId},true);}catch(error){
|
|
55
|
+
return {mode:null,gap:`bootstrap 任务预检失败: ${error.code??'bootstrap_task_required'};宿主未启动`};
|
|
56
|
+
}
|
|
57
|
+
if(task.mode!=='instructions')return {mode:task.mode,gap:null};
|
|
58
|
+
const gap=line=>({mode:'instructions',gap:`${line};可由当前 AI 会话用 cm-ai-host.mjs serve 应答 init_generate/init_verify`});
|
|
59
|
+
if(permissions.includes('--protected-config'))return gap('规范任务不支持 --protected-config(provider 开发)驾驶');
|
|
60
|
+
if(Object.hasOwn(definition,'codeProjects'))return gap('多代码根(codeProjects)规范任务驾驶员尚不支持');
|
|
61
|
+
let selection;
|
|
62
|
+
// The host's own reader: a regular, non-symlink file of at most 64 KiB with only selection.
|
|
63
|
+
try{selection=validateCmInitSelection(readBootstrapConfiguration(permissions[permissions.indexOf('--bootstrap-config')+1]).selection);}
|
|
64
|
+
catch(error){return {mode:'instructions',gap:`bootstrap-config 无效或缺少有效的 cm-init selection: ${error.code??error.message};宿主未启动`};}
|
|
65
|
+
const instructionPaths=cmInitRuleTargets(selection);
|
|
66
|
+
const missing=instructionPaths.filter(file=>!definition.scope.includes(file));
|
|
67
|
+
if(missing.length)return {mode:'instructions',gap:`规范任务 scope 缺少固定目标 ${missing.join(', ')};宿主会以 bootstrap_scope_required 拒绝启动`};
|
|
68
|
+
const business=definition.scope.filter(file=>!instructionPaths.includes(file));
|
|
69
|
+
if(business.length)return gap(`规范任务 scope 含业务文件 ${business.join(', ')}:驾驶员只支持纯规范 scope,业务文件请拆成独立任务`);
|
|
70
|
+
return {mode:'instructions',gap:null,selection,targets:cmInitRuleTargets(selection,definition.codeProject)};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function contentOf(root,local,label){
|
|
74
|
+
refuse(nonempty(local)&&!path.isAbsolute(local)&&!local.split(/[\\/]/).includes('..'),`答案格式错误:${label} 路径无效`);
|
|
75
|
+
const file=path.join(root,local);
|
|
76
|
+
refuse(fs.existsSync(file)&&fs.lstatSync(file).isFile()&&!fs.lstatSync(file).isSymbolicLink()
|
|
77
|
+
&&fs.realpathSync(file).startsWith(fs.realpathSync(root)+path.sep),`答案格式错误:${label} 缺少安全的内容文件 ${file}`);
|
|
78
|
+
try{return new TextDecoder('utf-8',{fatal:true}).decode(fs.readFileSync(file));}
|
|
79
|
+
catch{return stop(2,`答案格式错误:${label} 不是 UTF-8 文本 ${file}`);}
|
|
80
|
+
}
|
|
81
|
+
function inspected(project,documents,selection,label){
|
|
82
|
+
let inspection;
|
|
83
|
+
try{inspection=inspectCmInitDraft({project,documents,selection});}
|
|
84
|
+
catch(error){stop(2,`${label} 无效: ${error.code??error.message}`);}
|
|
85
|
+
refuse(inspection.status==='structurally_checked',
|
|
86
|
+
`${label} 结构检查未通过: ${inspection.issues.map(issue=>`${issue.path}:${issue.code}`).join(', ')}`);
|
|
87
|
+
}
|
|
88
|
+
// Same decoding as host-bootstrap.mjs run(); throws on an unsafe path.
|
|
89
|
+
const agentsBefore=project=>readCmInitSource(project,'AGENTS.md')?.toString('utf8')??'';
|
|
90
|
+
function readTarget(project,file){
|
|
91
|
+
try{return readCmInitSource(project,file);}
|
|
92
|
+
catch(error){return stop(2,`无法安全读取当前 ${file}: ${error.code??error.message}`);}
|
|
93
|
+
}
|
|
94
|
+
// Host order: generateCmInitDraft inspects the raw documents, then AGENTS.md is
|
|
95
|
+
// merged with the current file and inspected again (host-bootstrap.mjs run()).
|
|
96
|
+
function readGenerate(root,name,{definition,bootstrap,learning}){
|
|
97
|
+
const value=readJson(path.join(root,name),name);
|
|
98
|
+
refuse(object(value)&&Object.keys(value).sort().join()==='documents,status',`答案格式错误:${name} 只允许 status 与 documents`);
|
|
99
|
+
refuse(value.status==='generated',`答案格式错误:${name}.status 只能是 generated;无法生成时不要启动驾驶员,先报告缺口(宿主把 blocked 记为 unknown 开发步骤)`);
|
|
100
|
+
const {targets}=bootstrap;
|
|
101
|
+
refuse(Array.isArray(value.documents)&&value.documents.length===targets.length
|
|
102
|
+
&&new Set(value.documents.map(item=>item?.path)).size===targets.length
|
|
103
|
+
&&value.documents.every(item=>object(item)&&Object.keys(item).sort().join()==='contentFile,path'&&targets.includes(item.path)),
|
|
104
|
+
`答案格式错误:${name}.documents 须逐项覆盖 targets(每项只有 path/contentFile): ${targets.join(', ')}`);
|
|
105
|
+
const documents=targets.map(file=>({path:file,content:contentOf(root,
|
|
106
|
+
value.documents.find(item=>item.path===file).contentFile,`${name} ${file}`)}));
|
|
107
|
+
inspected(definition.codeProject,documents,bootstrap.selection,name);
|
|
108
|
+
refuse(envelope({status:'generated',documents})<=RESPONSE_LIMIT,
|
|
109
|
+
`${name} 的正文合计超过宿主单次回复 64 KiB 上限;精简规范正文,不要截断`);
|
|
110
|
+
// Same expectations as host-bootstrap.mjs run(): files this run already wrote are
|
|
111
|
+
// bound to the journal's recorded evidence (revision or same-attempt retry);
|
|
112
|
+
// without it only an AGENTS.md carrying a Learning section may pre-exist.
|
|
113
|
+
const project=definition.codeProject,prior=learning?.bootstrap??null,writeback=learning?.writeback??null;
|
|
114
|
+
for(const file of targets){
|
|
115
|
+
const bytes=readTarget(project,file);
|
|
116
|
+
if(prior===null)refuse(bytes===null||file==='AGENTS.md'&&learningSection(bytes.toString('utf8')),
|
|
117
|
+
`规范目标已存在: ${file};本运行尚未写入规范,只允许带「## 项目教训」段的 AGENTS.md,宿主不覆盖已有规则(bootstrap_instruction_conflict)`);
|
|
118
|
+
else{
|
|
119
|
+
const expected=file==='AGENTS.md'&&writeback?.outcome==='written'?writeback.agentsFile.sha256
|
|
120
|
+
:prior.files.find(item=>item.path===file)?.afterSha256??null;
|
|
121
|
+
refuse(sha(bytes)===expected,`规范目标 ${file} 与本运行已记录的写入不一致(期望 ${expected??'不存在'},当前 ${sha(bytes)??'不存在'});`
|
|
122
|
+
+'宿主会以 bootstrap_instruction_conflict 停在 unknown,先还原该文件');
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const existing=readTarget(project,'AGENTS.md')?.toString('utf8')??'';
|
|
126
|
+
let merged;
|
|
127
|
+
try{merged=mergeBootstrapAgents(existing,documents.find(item=>item.path==='AGENTS.md').content);}
|
|
128
|
+
catch{stop(2,`${name} 的 AGENTS.md 必须逐字保留当前 AGENTS.md 中「## 项目教训」段以外的全部内容(宿主只把该段按原字节合入);否则宿主以 bootstrap_instruction_conflict 停在 unknown`);}
|
|
129
|
+
inspected(project,documents.map(item=>item.path==='AGENTS.md'?{path:item.path,content:merged}:item),
|
|
130
|
+
bootstrap.selection,`${name}(合入当前 AGENTS.md 后)`);
|
|
131
|
+
return documents;
|
|
132
|
+
}
|
|
133
|
+
function readVerify(root,name,{definition,plan,attempt}){
|
|
134
|
+
const value=readJson(path.join(root,name),name);
|
|
135
|
+
refuse(object(value),`答案格式错误:${name}`);
|
|
136
|
+
refuse(!(object(value.checks)&&Object.hasOwn(value.checks,'commands')),
|
|
137
|
+
`答案格式错误:${name}.checks 不能包含 commands;命令核验只由驾驶员实跑 ${name}.commands 得出,答案文件不能提供执行结果`);
|
|
138
|
+
const keys=['commands','checks','constraintChanges','application','retrospective'];
|
|
139
|
+
refuse(Object.keys(value).every(key=>[...keys,'commandsNotRun'].includes(key))&&keys.every(key=>Object.hasOwn(value,key)),
|
|
140
|
+
`答案格式错误:${name} 需要 ${keys.join('、')}(可选 commandsNotRun)`);
|
|
141
|
+
refuse(Array.isArray(value.commands)&&value.commands.length>0&&value.commands.length<=32,
|
|
142
|
+
`答案格式错误:${name}.commands 须列出 1..32 条草稿里可安全实跑的命令 {id,command,timeoutMs?};驾驶员不接受没有实跑的命令核验`);
|
|
143
|
+
try{
|
|
144
|
+
for(const item of value.commands){
|
|
145
|
+
if(!object(item)||Object.keys(item).some(key=>!['id','command','timeoutMs'].includes(key)))throw Error('每项只允许 id、command、timeoutMs');
|
|
146
|
+
planCheckTimeout(plan,item);
|
|
147
|
+
}
|
|
148
|
+
createHostCheck({cwd:definition.codeProject,commands:value.commands.map(({id,command})=>({id,command}))});
|
|
149
|
+
}catch(error){stop(2,`答案格式错误:${name}.commands ${error.code??error.message}`);}
|
|
150
|
+
refuse(value.commandsNotRun===undefined||value.commandsNotRun===null||oneLine(value.commandsNotRun,2048),
|
|
151
|
+
`答案格式错误:${name}.commandsNotRun 须为 null 或单行说明(最多 2048 UTF-8 字节)`);
|
|
152
|
+
refuse(object(value.checks)&&Object.keys(value.checks).sort().join()===[...REPORTED].sort().join(),
|
|
153
|
+
`答案格式错误:${name}.checks 须恰好包含 ${REPORTED.join('、')}`);
|
|
154
|
+
for(const category of REPORTED){
|
|
155
|
+
const check=value.checks[category];
|
|
156
|
+
refuse(object(check)&&Object.keys(check).sort().join()==='evidence,status'&&nonempty(check.evidence)
|
|
157
|
+
&&Buffer.byteLength(check.evidence,'utf8')<=4096,`答案格式错误:${name}.checks.${category} 须为 {status,evidence},evidence 非空且最多 4096 UTF-8 字节`);
|
|
158
|
+
refuse(['verified','not_applicable'].includes(check.status),
|
|
159
|
+
`${name}.checks.${category} 为 ${check.status}:宿主只接受 verified/not_applicable,未核验项会让开发步骤停在 unknown;先修正草稿或补齐证据`);
|
|
160
|
+
}
|
|
161
|
+
refuse(Array.isArray(value.constraintChanges)&&value.constraintChanges.length===0,
|
|
162
|
+
`${name}.constraintChanges 必须为空:规范任务不支持改写既有约束的确认,宿主会以 bootstrap_constraint_confirmation_required 停在 unknown`);
|
|
163
|
+
// The host binds feature/identity/learningDigest itself; the answer carries only the original fields.
|
|
164
|
+
const binding={feature:definition.feature,identity:{...definition.identity,attempt},learningDigest:'0'.repeat(64)};
|
|
165
|
+
const fields=(item,keys)=>object(item)&&Object.keys(item).sort().join()===keys;
|
|
166
|
+
try{need(fields(value.application,'note,status'));createCmAiTaskLearningApplication({...binding,...value.application});}
|
|
167
|
+
catch{stop(2,`答案格式错误:${name}.application 须为原 Learning 的 {status,note}`);}
|
|
168
|
+
try{need(fields(value.retrospective,'candidates,reason,status'));createCmAiTaskLearningRetrospective({...binding,...value.retrospective});}
|
|
169
|
+
catch{stop(2,`答案格式错误:${name}.retrospective 须为原 Learning 的 {status,candidates,reason}`);}
|
|
170
|
+
return value;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Only the attempt that starts from today's disk and journal is accepted. An
|
|
174
|
+
// advance that could review and then revise in one go is refused: the revision
|
|
175
|
+
// must answer findings that do not exist yet, and its commands would run before
|
|
176
|
+
// attempt 1 even writes.
|
|
177
|
+
// Early refusals with the host's own functions. The host checks the write grant
|
|
178
|
+
// only when the develop effect starts, and the task entry inside it
|
|
179
|
+
// (host-bootstrap.mjs run()), so both are required here; everything else the host
|
|
180
|
+
// checks at launch runs before host_ready, before any command.
|
|
181
|
+
function authorizeRulesLaunch({definition,plan,permissions}){
|
|
182
|
+
const refusal=';驾驶员不运行 init-verify 命令、不启动宿主';
|
|
183
|
+
refuse(permissions.includes('--allow-bootstrap-write'),
|
|
184
|
+
`规范任务需要 --allow-bootstrap-write:宿主写规范前要求这一授权(bootstrap_write_authorization_required)${refusal}`);
|
|
185
|
+
const protection=permissions.indexOf('--protected-conversation-config');
|
|
186
|
+
if(protection!==-1)try{readConversationProtection(permissions[protection+1]);}
|
|
187
|
+
catch(error){stop(2,`--protected-conversation-config 无效: ${error.code??error.message}(宿主以同一读取器拒绝启动)${refusal}`);}
|
|
188
|
+
const where={specsDir:definition.specsDir,codeProject:definition.codeProject};
|
|
189
|
+
if(plan.mode==='create'){
|
|
190
|
+
// openControlRun: a new run needs a ready admission that selects this task.
|
|
191
|
+
const admission=inspectCmAiAdmission(where);
|
|
192
|
+
refuse(admission.state==='ready'&&matchesCmAiTaskSelection(admission,definition.feature,definition.identity.taskId,
|
|
193
|
+
definition.taskSelection??null),`${definition.identity.taskId} 现在不能新建运行:admission ${admission.state},`
|
|
194
|
+
+`nextTask ${admission.nextTask?.id??'无'}(宿主以 task_selection_mismatch 等拒绝)${refusal}`);
|
|
195
|
+
}
|
|
196
|
+
// host-bootstrap.mjs run(): the rules effect only enters the admitted next task.
|
|
197
|
+
let entry;
|
|
198
|
+
try{entry=inspectCmAiBootstrapTask({...where,taskId:definition.identity.taskId}).admission.nextTask;}
|
|
199
|
+
catch(error){return stop(2,`bootstrap 任务预检失败: ${error.code??error.message}${refusal}`);}
|
|
200
|
+
refuse(entry?.feature===definition.feature&&entry.id===definition.identity.taskId,
|
|
201
|
+
`${definition.identity.taskId} 不是当前可进入的 bootstrap 任务(nextTask ${entry?.id??'无'},宿主以 bootstrap_task_required 拒绝)${refusal}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable}){
|
|
205
|
+
const result=new Map(),slug=`.reviews/${definition.feature.replace(/^\d+\./,'')}-${definition.identity.taskId}`;
|
|
206
|
+
const pair=attempt=>`answers/init-generate-a${attempt}.json 与 answers/init-verify-a${attempt}.json`;
|
|
207
|
+
if(reachable.reviewAfterDevelop)
|
|
208
|
+
stop(2,`规范任务的 advance 不能带 --allow-review-attempt 1 直接进入第 2 轮:修订答案须在读取首轮审查 findings 之后编写。请从 PLAN.permissions 移除 --allow-review-attempt 1,先 advance 到 awaiting_review;再用返回的 packageDigest 执行 decision,读取 ${slug}-r1.md 的 findings;若要求修改,写 ${pair(2)} 后 advance。`);
|
|
209
|
+
if(reachable.reviewFirst)
|
|
210
|
+
stop(2,`规范修订答案须在读取首轮审查 findings 之后编写:请先以 decision 和当前 packageDigest ${reachable.packageDigest} 单独运行审查,读取 ${slug}-r1.md 的 findings,写 ${pair(2)} 后再 advance(不要带 --allow-review-attempt 1 advance)`);
|
|
211
|
+
if(reachable.attempts.length)authorizeRulesLaunch({definition,plan,permissions});
|
|
212
|
+
for(const attempt of reachable.attempts){
|
|
213
|
+
const names=['init-generate','init-verify'].map(name=>attemptAnswerName(answers??'',name,attempt));
|
|
214
|
+
for(const name of names){
|
|
215
|
+
const file=path.join(answers??'',name);
|
|
216
|
+
if(answers&&fs.existsSync(file))continue;
|
|
217
|
+
if(attempt>1)stop(2,`步骤 ${operation} 会进入第 ${attempt} 轮规范修订,但答案文件不存在: ${file};读取 ${slug}-r${attempt-1}.md 的 findings 后写 ${pair(attempt)}(不会复用第 1 轮答案)`);
|
|
218
|
+
stop(2,`步骤 ${operation} 会反问 ${name.startsWith('init-generate')?'init_generate':'init_verify'},但答案文件不存在: ${file}`);
|
|
219
|
+
}
|
|
220
|
+
result.set(attempt,{generate:readGenerate(answers,names[0],{definition,bootstrap,learning:reachable.learning}),
|
|
221
|
+
verify:readVerify(answers,names[1],{definition,plan,attempt}),verifyName:names[1]});
|
|
222
|
+
}
|
|
223
|
+
return result;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const documentMap=documents=>new Map(documents.map(item=>[item.path,item.content]));
|
|
227
|
+
// Everything the preflight validated or the host re-reads at launch: the fixed
|
|
228
|
+
// targets, the run definition and permission files, and the approved bootstrap specs.
|
|
229
|
+
function boundFiles({definition,bootstrap,watch}){
|
|
230
|
+
const state=new Map(),mark=error=>`unreadable:${error.code??'error'}`;
|
|
231
|
+
for(const file of bootstrap.targets){
|
|
232
|
+
try{state.set(file,sha(readCmInitSource(definition.codeProject,file)));}catch(error){state.set(file,mark(error));}
|
|
233
|
+
}
|
|
234
|
+
const specs=['requirements.md','design.md','tasks.md'].map(name=>path.join(definition.specsDir,definition.feature,name));
|
|
235
|
+
for(const file of [...watch,...specs,path.join(definition.specsDir,'.cm-specs-status')]){
|
|
236
|
+
try{state.set(file,sha(fs.readFileSync(file)));}catch(error){state.set(file,error.code==='ENOENT'?null:mark(error));}
|
|
237
|
+
}
|
|
238
|
+
return state;
|
|
239
|
+
}
|
|
240
|
+
export function createBootstrapRulesResponder({definition,plan,bootstrap,answers,specsRoot=null,watch=[]}){
|
|
241
|
+
let generated=null;const executed=new Map();
|
|
242
|
+
// Bound at preflight time: a change before the host opened or during the commands both count.
|
|
243
|
+
const before=boundFiles({definition,bootstrap,watch});
|
|
244
|
+
const recovery=mode=>mode==='create'
|
|
245
|
+
?'宿主已按 create 建好运行(ready,未执行开发步骤);修正后把 PLAN.mode 改为 resume 重试'
|
|
246
|
+
:'运行存档不变;修正后原样重试';
|
|
247
|
+
return {
|
|
248
|
+
// Returns null when every listed command passed and left the bound files
|
|
249
|
+
// unchanged, otherwise the refusal line.
|
|
250
|
+
async prepare(mode='resume'){
|
|
251
|
+
for(const [attempt,entry] of answers){
|
|
252
|
+
const results=[],at=new Date().toISOString().replace(/\.\d{3}Z$/,'Z');
|
|
253
|
+
for(const command of entry.verify.commands){
|
|
254
|
+
const run=createHostCheck({cwd:definition.codeProject,commands:[{id:command.id,command:command.command}],
|
|
255
|
+
timeoutMs:planCheckTimeout(plan,command),...(specsRoot===null?{}:{specsRoot}),
|
|
256
|
+
onOutput:({stream,chunk})=>{process.stderr.write(`[drive init_verify ${command.id} ${stream}] ${chunk.toString('utf8')}`);}});
|
|
257
|
+
const [item]=await run({identity:{...definition.identity,attempt}},{signal:new AbortController().signal});
|
|
258
|
+
results.push(item);
|
|
259
|
+
if(item.outcome!=='passed')break;
|
|
260
|
+
}
|
|
261
|
+
const passed=results.length===entry.verify.commands.length&&results.every(item=>item.outcome==='passed');
|
|
262
|
+
const lines=results.map(item=>`${item.id}: ${item.outcome}(${item.evidence})`);
|
|
263
|
+
if(results.length<entry.verify.commands.length)
|
|
264
|
+
lines.push(`未运行(前一条未通过): ${entry.verify.commands.slice(results.length).map(item=>item.id).join(', ')}`);
|
|
265
|
+
executed.set(attempt,{passed,lines,at,total:entry.verify.commands.length,ran:results.length});
|
|
266
|
+
if(!passed)return `${entry.verifyName} 的命令在发送操作前实跑未通过:${lines.join(';')}。未发送操作,${recovery(mode)}(修正项目或草稿及答案)`;
|
|
267
|
+
}
|
|
268
|
+
const after=boundFiles({definition,bootstrap,watch});
|
|
269
|
+
const changed=[...before.keys()].filter(file=>before.get(file)!==after.get(file));
|
|
270
|
+
if(changed.length)return `预检已核对的文件在发送操作前被改动: ${changed.join(', ')};未发送操作(否则宿主会以 bootstrap_instruction_conflict 等停在 unknown),`
|
|
271
|
+
+`${recovery(mode)}。init-verify 命令须只读核验,还原这些文件后重试`;
|
|
272
|
+
return null;
|
|
273
|
+
},
|
|
274
|
+
init_generate(row){
|
|
275
|
+
const payload=row.payload,attempt=payload?.bootstrap?.identity?.attempt,entry=answers.get(attempt);
|
|
276
|
+
if(!entry)throw Error(`init_generate 第 ${attempt} 轮未预检,拒绝复用其他轮答案`);
|
|
277
|
+
if(payload.project!==definition.codeProject)throw Error('init_generate 项目根与运行定义不一致');
|
|
278
|
+
if(!isDeepStrictEqual(payload.selection,bootstrap.selection))throw Error('init_generate selection 与 bootstrap-config 不一致');
|
|
279
|
+
if(!isDeepStrictEqual([...payload.targets].sort(),[...bootstrap.targets].sort()))
|
|
280
|
+
throw Error(`init_generate targets 与预检不一致: ${payload.targets.join(', ')}`);
|
|
281
|
+
generated={attempt,documents:entry.generate};
|
|
282
|
+
return {status:'generated',documents:entry.generate.map(({path:file,content})=>({path:file,content}))};
|
|
283
|
+
},
|
|
284
|
+
async init_verify(row){
|
|
285
|
+
const payload=row.payload;
|
|
286
|
+
if(generated===null)throw Error('本驾驶员尚未应答对应的 init_generate,拒绝核验未知草稿');
|
|
287
|
+
const {attempt,documents}=generated;generated=null;
|
|
288
|
+
const identity=payload.learningInput?.identity;
|
|
289
|
+
if(identity?.attempt!==attempt)throw Error('init_verify 轮次与刚应答的 init_generate 不一致');
|
|
290
|
+
if(payload.project!==definition.codeProject)throw Error('init_verify 项目根与运行定义不一致');
|
|
291
|
+
if(!isDeepStrictEqual(payload.categories,CATEGORIES))throw Error('init_verify 核验分组与合同不一致');
|
|
292
|
+
// The host verifies the final documents: current AGENTS.md lessons are merged in.
|
|
293
|
+
const expected=documents.map(item=>item.path==='AGENTS.md'
|
|
294
|
+
?{path:item.path,content:mergeBootstrapAgents(agentsBefore(definition.codeProject),item.content)}:item);
|
|
295
|
+
if(!Array.isArray(payload.documents)||!isDeepStrictEqual(documentMap(payload.documents),documentMap(expected)))
|
|
296
|
+
throw Error('宿主核验的草稿与 init-generate 答案(含合入的项目教训段)不一致');
|
|
297
|
+
const answer=answers.get(attempt).verify,run=executed.get(attempt);
|
|
298
|
+
if(!run)throw Error('init_verify 的命令尚未由本驾驶员实跑,拒绝应答');
|
|
299
|
+
const evidence=`驾驶员在发送本操作前实跑 ${run.ran}/${run.total} 条草稿命令(${run.at}): ${run.lines.join(';')}`
|
|
300
|
+
+(nonempty(answer.commandsNotRun)?`。未实跑(会话核对说明,不是执行证据): ${answer.commandsNotRun}`:'');
|
|
301
|
+
return {checks:{...answer.checks,commands:{status:run.passed?'verified':'failed',evidence}},
|
|
302
|
+
constraintChanges:[],application:answer.application,retrospective:answer.retrospective};
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
}
|
|
@@ -6,6 +6,12 @@ import readline from 'node:readline';
|
|
|
6
6
|
|
|
7
7
|
export const stderr=line=>process.stderr.write(`[drive] ${line}\n`);
|
|
8
8
|
export const stop=(code,line)=>{stderr(line);process.exit(code);};
|
|
9
|
+
export function planCheckTimeout(plan,item=null){
|
|
10
|
+
const valid=value=>Number.isInteger(value)&&value>=1&&value<=3600000;
|
|
11
|
+
if(Object.hasOwn(plan,'checkTimeoutMs')&&!valid(plan.checkTimeoutMs))throw Error('PLAN.checkTimeoutMs 需要 1..3600000 的整数');
|
|
12
|
+
if(item!==null&&Object.hasOwn(item,'timeoutMs')&&!valid(item.timeoutMs))throw Error('PLAN.checks timeoutMs 需要 1..3600000 的整数');
|
|
13
|
+
return item?.timeoutMs??plan.checkTimeoutMs??900000;
|
|
14
|
+
}
|
|
9
15
|
|
|
10
16
|
export function readJson(file,label){
|
|
11
17
|
try{return JSON.parse(fs.readFileSync(file,'utf8'));}
|
|
@@ -34,14 +40,33 @@ export function preflightAnswers(kinds,load){
|
|
|
34
40
|
return answers;
|
|
35
41
|
}
|
|
36
42
|
|
|
37
|
-
export
|
|
43
|
+
export const hostResponseFailed=row=>Boolean(row.error||row.result?.state==='unknown'
|
|
44
|
+
||row.result?.pendingAction==='reconcile');
|
|
45
|
+
// A static answer cannot be corrected and resent, so a rejected reply would
|
|
46
|
+
// leave the host waiting forever on the same call. Say why and end the session.
|
|
47
|
+
const rejectedReplyHint=code=>code==='host_response_too_large'
|
|
48
|
+
?'应答超过宿主输入上限:在 PLAN.permissions 加 "--input-limit","<字节数>"(65536–4194304,默认 65536)'
|
|
49
|
+
:'应答与宿主这次反问不匹配(会话、调用或请求摘要不对)';
|
|
50
|
+
|
|
51
|
+
// beforeRequest runs after host_ready, i.e. after the host itself accepted every
|
|
52
|
+
// launch input, admission and the run store, and before the operation is sent.
|
|
53
|
+
// A returned refusal closes the session without any operation and exits 2.
|
|
54
|
+
export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null}){
|
|
38
55
|
const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe']});
|
|
39
56
|
child.stderr.on('data',chunk=>process.stderr.write(chunk));
|
|
40
|
-
|
|
41
|
-
|
|
57
|
+
// After a rejected reply the session is ended; later rows get no answer.
|
|
58
|
+
const send=value=>{if(!child.stdin.writableEnded)child.stdin.write(JSON.stringify(value)+'\n');};
|
|
59
|
+
let done=false,refused=false,rejected=null;
|
|
42
60
|
readline.createInterface({input:child.stdout}).on('line',async line=>{
|
|
43
61
|
let row;try{row=JSON.parse(line);}catch{process.stdout.write(line+'\n');return;}
|
|
44
|
-
if(row.type==='host_ready'){
|
|
62
|
+
if(row.type==='host_ready'){
|
|
63
|
+
if(beforeRequest){
|
|
64
|
+
let refusal;
|
|
65
|
+
try{refusal=await beforeRequest();}catch(error){refusal=`发送操作前的准备失败:${error.message}`;}
|
|
66
|
+
if(refusal){refused=true;stderr(refusal);process.exitCode=2;send({type:'host_close',sessionId:row.sessionId});child.stdin.end();return;}
|
|
67
|
+
}
|
|
68
|
+
send({requestId:'drive',operation,...request});return;
|
|
69
|
+
}
|
|
45
70
|
if(row.type==='host_request'){
|
|
46
71
|
let result;
|
|
47
72
|
try{result=await answerFor(row,answers,paths);}catch(error){stderr(`应答 ${row.kind} 失败:${error.message}`);result=null;}
|
|
@@ -53,16 +78,23 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
|
|
|
53
78
|
send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
|
|
54
79
|
return;
|
|
55
80
|
}
|
|
56
|
-
if(row.type==='host_response')
|
|
81
|
+
if(row.type==='host_response'){
|
|
82
|
+
if(row.accepted===false&&rejected===null){
|
|
83
|
+
rejected=typeof row.code==='string'?row.code:'host_response_rejected';
|
|
84
|
+
stderr(`宿主拒收了应答:${rejected};${rejectedReplyHint(rejected)}。驾驶员不再等待,已结束会话;宿主会把这一步记为 unknown`);
|
|
85
|
+
child.stdin.end();
|
|
86
|
+
}
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
57
89
|
if(row.requestId==='drive'){
|
|
58
90
|
done=true;
|
|
59
91
|
process.stdout.write(JSON.stringify(row,null,2)+'\n');
|
|
60
92
|
if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
|
|
61
93
|
if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
|
|
62
|
-
process.exitCode=row
|
|
94
|
+
process.exitCode=hostResponseFailed(row)||rejected!==null?1:0;
|
|
63
95
|
child.stdin.end();
|
|
64
96
|
}
|
|
65
97
|
});
|
|
66
98
|
child.on('error',error=>{stderr(`宿主启动失败:${error.message}`);process.exitCode=1;});
|
|
67
|
-
child.on('exit',code=>{if(!done){stderr(`宿主在给出结果前退出了,exit ${code}`);process.exitCode=1;}});
|
|
99
|
+
child.on('exit',code=>{if(!done&&!refused){stderr(`宿主在给出结果前退出了,exit ${code}`);process.exitCode=1;}});
|
|
68
100
|
}
|