@aibyzero/cm-workflow 0.16.3 → 0.16.4
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/CHANGELOG.md +9 -0
- package/README.md +44 -3
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/docs/next-steps.md +14 -24
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +18 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +2 -1
- package/runtime/js/cm-ai/host-session.mjs +8 -1
- package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
- package/runtime/js/cm-prd/summary.mjs +4 -2
- package/runtime/js/specs-status.mjs +6 -2
- package/scripts/cm-ai-admission.mjs +2 -0
- package/scripts/cm-ai-batch-drive.mjs +1 -1
- package/scripts/cm-ai-batch-drive.test.mjs +7 -0
- package/scripts/cm-ai-batch-host.mjs +13 -5
- package/scripts/cm-ai-batch-host.test.mjs +25 -0
- package/scripts/cm-ai-drive.mjs +2 -1
- package/scripts/cm-ai-drive.test.mjs +7 -0
- package/scripts/cm-ai-host.mjs +10 -5
- package/scripts/cm-ai-host.test.mjs +42 -0
- package/scripts/cm-check-drive.mjs +4 -3
- package/scripts/cm-check-drive.test.mjs +16 -0
- package/scripts/cm-check-entry.mjs +13 -2
- package/scripts/cm-check-host.mjs +2 -2
- package/scripts/cm-check-host.test.mjs +56 -0
- package/scripts/cm-check-runtime.sh +15 -6
- package/scripts/cm-claude-developer-worker.test.mjs +40 -1
- package/scripts/cm-claude-review-stream.test.mjs +43 -0
- package/scripts/cm-prd-completion.test.mjs +30 -2
- package/scripts/cm-prd-drive.mjs +13 -7
- package/scripts/cm-prd-drive.test.mjs +10 -0
- package/scripts/cm-prd-summary.test.mjs +31 -0
- package/scripts/cm-specs-status.test.mjs +19 -0
- package/scripts/test-shell-compat.sh +67 -0
- package/skills/cm-ai/references/js-host.md +5 -0
- package/skills/cm-check/SKILL.md +6 -1
- package/skills/cm-check/references/js-host.md +3 -3
- package/skills/cm-prd/references/js-change-recovery.md +30 -0
package/scripts/cm-ai-host.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import {REVIEWED_HANDOFF_HINT} from '../runtime/js/cm-ai/host-handoff.mjs';
|
|
|
8
8
|
import {readRunDefinition,openControlRun,createCodexExecution} from './cm-ai-run.mjs';
|
|
9
9
|
import {createConversationExecution as executionFor} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
|
|
10
10
|
import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
|
|
11
|
-
import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
|
|
11
|
+
import {serveCmAiHost,parseHostInputLimit} from '../runtime/js/cm-ai/host-session.mjs';
|
|
12
12
|
import {createQaFixOwnerHost} from '../runtime/js/cm-ai/host-qa-fix-owner.mjs';
|
|
13
13
|
import {createFixLearningPreparation} from '../runtime/js/cm-fix/learning.mjs';
|
|
14
14
|
import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
|
|
@@ -37,7 +37,11 @@ const fixLocalPermissions=new Map(['red-test','baseline','regression','learning-
|
|
|
37
37
|
'test-author','repair','cause-review','final-review']
|
|
38
38
|
.map(name=>[`--allow-qa-fix-${name}`,`--allow-${name}`]));
|
|
39
39
|
|
|
40
|
-
const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development [--original-host-context ID] [--runtime codex|claude] [--failover] [--review-config PATH] [--allow-review-attempt 1|2] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\
|
|
40
|
+
const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development [--original-host-context ID] [--runtime codex|claude] [--input-limit BYTES] [--failover] [--review-config PATH] [--allow-review-attempt 1|2] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\nInput limit is transport-only: integer 65536-4194304 bytes, default 65536; it may change on resume. Review config is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 60000), independent of protected mode and outside the authorized configuration digest.\ncm-ai-host.mjs preflight --config RUN_DEFINITION.json --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
|
|
41
|
+
|
|
42
|
+
export async function serveHostTransport(options,rawInputLimit,serve=serveCmAiHost){
|
|
43
|
+
return serve({...options,inputLimit:parseHostInputLimit(rawInputLimit)});
|
|
44
|
+
}
|
|
41
45
|
|
|
42
46
|
function reviewConfiguration(file){
|
|
43
47
|
const info=fs.lstatSync(file);
|
|
@@ -133,7 +137,7 @@ function canResumeLegacyProtected(definition,runtime){
|
|
|
133
137
|
export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
|
|
134
138
|
if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--original-host-context ID is resume-only: keep the creating session in durable configuration while --host-context remains the real live session. Equal IDs mean a same-session reopen. Parent conversation runs only; legacy protected runs, batch and QA-fix children are unchanged.\n');
|
|
135
139
|
if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Approved 0.bootstrap only: --bootstrap-config PATH {selection:null for scaffold, or original cm-init selection for rules} and --allow-bootstrap-write. Original scope must include fixed instruction targets; they are host-written inside the original task effect, checked/reviewed and reloaded. No Git/install/network grant. Optional codeProjects selects disjoint real roots below codeProject; prefix scope/requirements and use protected current-session checks with a declared codeProject per command.\n');
|
|
136
|
-
if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session mode (Codex or Claude; also batch): --protected-conversation-config PATH with {checkCommands,timeoutMs}; timeoutMs bounds both check commands and the reviewer process. A review transport timeout with no result can resume once per attempt with fresh review authorization; a result-bearing timeout still requires reconciliation. No extra model call. The current host returns scoped UTF-8 edits; native Codex sandbox applies them and runs the declared checks. Original author runtime, per-attempt Review and QA permissions remain required. Do not combine with --protected-config.
|
|
140
|
+
if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session mode (Codex or Claude; also batch): --protected-conversation-config PATH with {checkCommands,timeoutMs}; timeoutMs bounds both check commands and the reviewer process. A review transport timeout with no result can resume once per attempt with fresh review authorization; a result-bearing timeout still requires reconciliation. No extra model call. The current host returns scoped UTF-8 edits; native Codex sandbox applies them and runs the declared checks. Original author runtime, per-attempt Review and QA permissions remain required. Do not combine with --protected-config. The input limit defaults to 64 KiB and may be raised with --input-limit; unavailable/binary changes stop, never switch to direct writes.\n');
|
|
137
141
|
if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected single-task CLI mode: add --protected-config PATH --allow-provider-development-attempt 1|2 and --review-config PATH. Protected config is {model,checkCommands,timeoutMs}; roots and host identity come from the original run definition and launch. This explicitly permits one task attempt of real developer execution and its declared native-sandbox checks; --allow-development alone does not. Review separately requires --allow-review-attempt 1|2. Diagnostics are required but are not review authorization. Optional original --workflow-config PATH and --allow-qa connect protected QA commands and documentation within the same developer invocation before Review; host semantic/browser/inspection requests retain their original contracts, not arbitrary writes. Default current-session mode is unchanged. Protected parent mode selects coder/reviewer CLIs from the project declaration; Claude returns protected-text-v1 proposals for host validation and sandbox application; original QA-fix options require child configuration.protectSpecs=true and all original child action permissions. Protected fix writes use text proposals, not direct host edits. The original QA/documentation/finalizer gates remain required. No installation or Git authority.\n');
|
|
138
142
|
if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--browser-qa is required when the approved contract for this feature contains blocking browser cases or policy-enabled browser cases and QA is enabled, and must not be given otherwise. It is a declaration by the launching session, not a probe: the host cannot verify that this session can drive a browser. The gate applies to create and resume alike, so every launch must assert it again; the assertion is not persisted, because a stored assertion would only repeat the claim made by whichever session wrote it. unavailable refuses to start; either launch from a browser-capable session or remove browser cases from the approved contract.\n');
|
|
139
143
|
if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--revise-qa-config PREVIOUS_WORKFLOW.json --qa-config-revision-reason REASON: 仅 resume 且 --allow-qa;核对旧配置后追加 QA 修订,旧 QA 作废留史,下一轮仍受三轮上限约束。未知 QA 须先处理;不能修改开发配置或重开 N5。\n');
|
|
@@ -166,10 +170,11 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
166
170
|
const extra=new Map();
|
|
167
171
|
for(let index=8;index<argv.length;index++){
|
|
168
172
|
const name=argv[index];need(!extra.has(name),'invalid_arguments');
|
|
169
|
-
need(['--revise-qa-config','--qa-config-revision-reason','--supersede-reviewed-evidence','--supersede-reason','--original-host-context','--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments');
|
|
173
|
+
need(['--revise-qa-config','--qa-config-revision-reason','--supersede-reviewed-evidence','--supersede-reason','--original-host-context','--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--input-limit','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments');
|
|
170
174
|
if(['--supersede-reviewed-evidence','--allow-bootstrap-write','--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--failover','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
|
|
171
175
|
else{need(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments');extra.set(name,argv[++index]);}
|
|
172
176
|
}
|
|
177
|
+
parseHostInputLimit(extra.get('--input-limit'));
|
|
173
178
|
const revisionRequested=extra.has('--revise-qa-config')||extra.has('--qa-config-revision-reason');
|
|
174
179
|
need(!extra.has('--supersede-reviewed-evidence')&&!extra.has('--supersede-reason')
|
|
175
180
|
||(argv[4]==='create'&&extra.has('--supersede-reviewed-evidence')&&extra.has('--supersede-reason')),
|
|
@@ -277,7 +282,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
277
282
|
// process's own terminal so tool results are not mistaken for output frames.
|
|
278
283
|
const rawMode=input.isTTY&&typeof input.setRawMode==='function';if(rawMode)input.setRawMode(true);
|
|
279
284
|
const diagnosticHost=withHandoffDiagnostic(run.host,error);
|
|
280
|
-
try{await
|
|
285
|
+
try{await serveHostTransport({host:diagnosticHost,input,output,toolBridge:bridge,errorOutput:error},extra.get('--input-limit'));}
|
|
281
286
|
finally{if(rawMode)input.setRawMode(false);}
|
|
282
287
|
return 0;
|
|
283
288
|
}catch(cause){
|
|
@@ -8,6 +8,7 @@ import {spawn,spawnSync} from 'node:child_process';
|
|
|
8
8
|
import {fileURLToPath} from 'node:url';
|
|
9
9
|
import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
|
|
10
10
|
import {createConversationExecution} from './cm-ai-host.mjs';
|
|
11
|
+
import {readRunDefinition,openControlRun} from './cm-ai-run.mjs';
|
|
11
12
|
import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
|
|
12
13
|
|
|
13
14
|
// Keep runtime declarations and log mirrors independent of the invoking user's home.
|
|
@@ -19,6 +20,47 @@ after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
|
|
|
19
20
|
const cli=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
|
|
20
21
|
const identity={repositoryId:'host-fixture',runId:'host-fixture-run',taskId:'T-001',attempt:1};
|
|
21
22
|
const request=(operation,requestId=operation)=>({version:1,operation,requestId,identity});
|
|
23
|
+
test('single host input limit parsing and transport pass-through need no running host',async()=>{
|
|
24
|
+
const {serveHostTransport}=await import('./cm-ai-host.mjs');
|
|
25
|
+
assert.equal(typeof serveHostTransport,'function');
|
|
26
|
+
const seen=[];
|
|
27
|
+
for(const raw of [undefined,'65536','1048576','4194304']){
|
|
28
|
+
await serveHostTransport({host:{}},raw,async options=>{seen.push(options.inputLimit);});
|
|
29
|
+
}
|
|
30
|
+
assert.deepEqual(seen,[65536,65536,1048576,4194304]);
|
|
31
|
+
for(const raw of ['65535','4194305','1.5','NaN']){
|
|
32
|
+
await assert.rejects(serveHostTransport({host:{}},raw,async()=>{}),/invalid_arguments/);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
test('single host help documents input limit',()=>{
|
|
36
|
+
const help=spawnSync(process.execPath,[cli,'--help'],{encoding:'utf8'});
|
|
37
|
+
assert.equal(help.status,0);assert.match(help.stdout,/--input-limit BYTES/);
|
|
38
|
+
});
|
|
39
|
+
test('single host CLI rejects out-of-range and non-integer input limits before opening a run',()=>{
|
|
40
|
+
for(const raw of ['65535','4194305','1.5']){
|
|
41
|
+
const run=spawnSync(process.execPath,[cli,'serve','--config','unused','--mode','create',
|
|
42
|
+
'--host-context','fixture','--allow-development','--input-limit',raw],{encoding:'utf8'});
|
|
43
|
+
assert.equal(run.status,1);assert.match(run.stderr,/invalid_arguments/);
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
test('resume accepts a changed transport input limit without changing the durable fingerprint',async()=>{
|
|
47
|
+
const f=fixture(),bridge=createHostToolBridge();
|
|
48
|
+
try{
|
|
49
|
+
const definition=readRunDefinition(f.config);
|
|
50
|
+
const execution=createConversationExecution(definition,'native-host-fixture',bridge,null,null,null,false,'codex');
|
|
51
|
+
const first=await openControlRun(definition,'create',execution);first.close();
|
|
52
|
+
const state=path.join(f.specsDir,'.reviews','.execution',identity.runId,'state.json');
|
|
53
|
+
const before=JSON.parse(fs.readFileSync(state,'utf8')).fingerprints;
|
|
54
|
+
let limit;
|
|
55
|
+
const {serveHostTransport}=await import('./cm-ai-host.mjs');
|
|
56
|
+
await serveHostTransport({host:{}},'65536',async options=>{limit=options.inputLimit;});
|
|
57
|
+
assert.equal(limit,65536);
|
|
58
|
+
const resumed=await openControlRun(definition,'resume',execution);resumed.close();
|
|
59
|
+
await serveHostTransport({host:{}},'1048576',async options=>{limit=options.inputLimit;});
|
|
60
|
+
assert.equal(limit,1048576);
|
|
61
|
+
assert.deepEqual(JSON.parse(fs.readFileSync(state,'utf8')).fingerprints,before);
|
|
62
|
+
}finally{bridge.close();fs.rmSync(f.root,{recursive:true,force:true});}
|
|
63
|
+
});
|
|
22
64
|
function fixture(){
|
|
23
65
|
const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-native-host-')));
|
|
24
66
|
const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),feature='1.work',config=path.join(root,'run.json');
|
|
@@ -50,15 +50,16 @@ function semantic(value,root){
|
|
|
50
50
|
}
|
|
51
51
|
function main(){
|
|
52
52
|
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
53
|
-
process.stdout.write('用法: cm-check-drive.mjs --plan PLAN.json <start|status|cancel>\nPLAN: skillDir, project, optional config/quick, checks:[{command:[checker,...args]}], answers。start 的机械证据由实际命令产生;check-semantic.json 只存人工判断。宿主没有跨进程恢复。\n');return;
|
|
53
|
+
process.stdout.write('用法: cm-check-drive.mjs --plan PLAN.json <start|status|cancel>\nPLAN: skillDir, project, optional config/runtime/quick, checks:[{command:[checker,...args]}], answers。start 的机械证据由实际命令产生;check-semantic.json 只存人工判断。宿主没有跨进程恢复。\n');return;
|
|
54
54
|
}
|
|
55
55
|
const {plan,operation,base}=loadPlanFile({name:'cm-check-drive.mjs',known:KNOWN});
|
|
56
56
|
requireFields(plan,['skillDir','project']);
|
|
57
57
|
if(plan.mode==='resume')stop(2,'cm-check 宿主没有持久会话,不能 resume');
|
|
58
58
|
const skillDir=path.resolve(base,plan.skillDir),project=path.resolve(base,plan.project);
|
|
59
59
|
const config=plan.config?path.resolve(base,plan.config):undefined;
|
|
60
|
+
const runtime=Object.hasOwn(plan,'runtime')?plan.runtime:undefined;
|
|
60
61
|
let invocation;
|
|
61
|
-
try{invocation=createCmCheckInvocation({skillDir,project,...(config?{config}:{})});}
|
|
62
|
+
try{invocation=createCmCheckInvocation({skillDir,project,...(config?{config}:{}),...(runtime===undefined?{}:{runtime})});}
|
|
62
63
|
catch(error){stop(2,`宿主输入无效: ${error.code??error.message}`);}
|
|
63
64
|
if(config)try{loadConfig({projectRoot:project,configPath:config});}
|
|
64
65
|
catch(error){stop(2,`PLAN.config 无效: ${config}: ${error.message}`);}
|
|
@@ -76,7 +77,7 @@ function main(){
|
|
|
76
77
|
if(value===undefined)stop(2,`步骤 start 会反问 ${kind},但答案文件不存在: ${file}`);
|
|
77
78
|
semantic(value,invocation.workflowRoot);return value;
|
|
78
79
|
});
|
|
79
|
-
driveHost({host:HOST,args:['serve','--skill-dir',skillDir,'--project',project,...(config?['--config',config]:[]),...(plan.quick?['--quick']:[])],
|
|
80
|
+
driveHost({host:HOST,args:['serve','--skill-dir',skillDir,'--project',project,...(config?['--config',config]:[]),...(runtime===undefined?[]:['--runtime',String(runtime)]),...(plan.quick?['--quick']:[])],
|
|
80
81
|
cwd:project,operation,answers:answer,answerFor:row=>{
|
|
81
82
|
if(row.kind==='check_semantic')return {sourceDigest:row.payload.sourceDigest,...answer.check_semantic};
|
|
82
83
|
if(row.kind!=='check_runtime')return null;
|
|
@@ -60,3 +60,19 @@ test('quick mode needs real runner and returns mechanical-only',t=>{
|
|
|
60
60
|
const run=f.drive(f.plan({quick:true}));assert.equal(run.status,0,run.stderr);
|
|
61
61
|
assert.equal(JSON.parse(run.stdout).result.result.overall,'MECHANICAL_ONLY');
|
|
62
62
|
});
|
|
63
|
+
|
|
64
|
+
test('a plan runtime reaches the checker command and a stale command is still refused',t=>{
|
|
65
|
+
const f=fixture(t),checker=path.join(f.dir,'scripts/cm-check-runtime.sh');
|
|
66
|
+
const withRuntime=f.plan({runtime:'claude',
|
|
67
|
+
checks:[{id:'check_runtime',command:[checker,'--project',f.project,'--runtime','claude','--print-effective']}]});
|
|
68
|
+
const run=f.drive(withRuntime);assert.equal(run.status,0,run.stderr);
|
|
69
|
+
assert.equal(JSON.parse(run.stdout).result.result.overall,'PASSED');
|
|
70
|
+
assert.equal(fs.readFileSync(f.marker,'utf8'),'x','the checker must run exactly once');
|
|
71
|
+
const mismatched=f.drive(f.plan({runtime:'claude'}));
|
|
72
|
+
assert.notEqual(mismatched.status,0,'a plan runtime absent from the command must not be accepted');
|
|
73
|
+
assert.equal(fs.readFileSync(f.marker,'utf8'),'x','a refused plan must not run the checker again');
|
|
74
|
+
const rejected=f.drive(f.plan({runtime:'pi',
|
|
75
|
+
checks:[{id:'check_runtime',command:[checker,'--project',f.project,'--runtime','pi','--print-effective']}]}));
|
|
76
|
+
assert.notEqual(rejected.status,0,'an unsupported runtime must not reach the checker');
|
|
77
|
+
assert.equal(fs.readFileSync(f.marker,'utf8'),'x');
|
|
78
|
+
});
|
|
@@ -51,9 +51,14 @@ function ownedFile(root,relative,code) {
|
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
// The checker labels each role against the runtime actually running it; an unnamed
|
|
55
|
+
// runtime stays unknown rather than being assumed.
|
|
56
|
+
const CHECK_RUNTIMES=new Set(['codex','claude']);
|
|
57
|
+
|
|
54
58
|
export function createCmCheckInvocation(input) {
|
|
55
59
|
const allowed=['skillDir','project'];
|
|
56
60
|
if(input&&Object.hasOwn(input,'config'))allowed.push('config');
|
|
61
|
+
if(input&&Object.hasOwn(input,'runtime'))allowed.push('runtime');
|
|
57
62
|
if(!input||typeof input!=='object'||Array.isArray(input)
|
|
58
63
|
||Object.keys(input).length!==allowed.length||!allowed.every(key=>Object.hasOwn(input,key)))reject('invalid_input');
|
|
59
64
|
const skillDir=realDirectory(input.skillDir,'skill_path_invalid');
|
|
@@ -68,8 +73,14 @@ export function createCmCheckInvocation(input) {
|
|
|
68
73
|
config=realFile(input.config,'config_path_invalid');
|
|
69
74
|
args.push('--config',config);
|
|
70
75
|
}
|
|
76
|
+
let runtime=null;
|
|
77
|
+
if(Object.hasOwn(input,'runtime')){
|
|
78
|
+
if(!CHECK_RUNTIMES.has(input.runtime))reject('runtime_invalid');
|
|
79
|
+
runtime=input.runtime;
|
|
80
|
+
args.push('--runtime',runtime);
|
|
81
|
+
}
|
|
71
82
|
args.push('--print-effective');
|
|
72
|
-
return Object.freeze({workflow:'cm-check',workflowRoot,skillDir,checker,project,config,args:Object.freeze(args)});
|
|
83
|
+
return Object.freeze({workflow:'cm-check',workflowRoot,skillDir,checker,project,config,runtime,args:Object.freeze(args)});
|
|
73
84
|
}
|
|
74
85
|
|
|
75
86
|
export function runCmCheck(input) {
|
|
@@ -99,7 +110,7 @@ function parseCli(argv) {
|
|
|
99
110
|
printEffective=true;
|
|
100
111
|
continue;
|
|
101
112
|
}
|
|
102
|
-
if(!['--skill-dir','--project','--config'].includes(flag)||index+1>=argv.length)reject('invalid_arguments');
|
|
113
|
+
if(!['--skill-dir','--project','--config','--runtime'].includes(flag)||index+1>=argv.length)reject('invalid_arguments');
|
|
103
114
|
const key=flag==='--skill-dir'?'skillDir':flag.slice(2);
|
|
104
115
|
if(Object.hasOwn(input,key))reject('invalid_arguments');
|
|
105
116
|
input[key]=argv[index+1];
|
|
@@ -11,12 +11,12 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
11
11
|
let bridge;
|
|
12
12
|
try{
|
|
13
13
|
if(argv.length===1&&argv[0]==='--help'){
|
|
14
|
-
output.write('cm-check-host.mjs serve --skill-dir ABS_PATH --project ABS_PATH [--config ABS_PATH] [--quick]\n--quick stops after the mechanical checker and reports MECHANICAL_ONLY; it never claims PASSED and never skips a failure.\nJSONL start/status/cancel. Current host executes check_runtime once using the existing platform checker; only exitCode 0 permits check_semantic. Eight original groups + optional degradation; complete coverage and local evidence required. No provider, install, repair, task completion or persistent state. Unknown/disconnected operations never retry.\n');return 0;
|
|
14
|
+
output.write('cm-check-host.mjs serve --skill-dir ABS_PATH --project ABS_PATH [--config ABS_PATH] [--runtime codex|claude] [--quick]\n--runtime names the runtime actually running this check so each role is labelled against it; omitted it stays unknown and no dispatch claim is made.\n--quick stops after the mechanical checker and reports MECHANICAL_ONLY; it never claims PASSED and never skips a failure.\nJSONL start/status/cancel. Current host executes check_runtime once using the existing platform checker; only exitCode 0 permits check_semantic. Eight original groups + optional degradation; complete coverage and local evidence required. No provider, install, repair, task completion or persistent state. Unknown/disconnected operations never retry.\n');return 0;
|
|
15
15
|
}
|
|
16
16
|
need(argv[0]==='serve','invalid_arguments');const request={};
|
|
17
17
|
for(let i=1;i<argv.length;){
|
|
18
18
|
if(argv[i]==='--quick'){need(!Object.hasOwn(request,'quick'),'invalid_arguments');request.quick=true;i+=1;continue;}
|
|
19
|
-
need(['--skill-dir','--project','--config'].includes(argv[i])&&argv[i+1],'invalid_arguments');
|
|
19
|
+
need(['--skill-dir','--project','--config','--runtime'].includes(argv[i])&&argv[i+1],'invalid_arguments');
|
|
20
20
|
const key=argv[i]==='--skill-dir'?'skillDir':argv[i].slice(2);need(!Object.hasOwn(request,key),'invalid_arguments');request[key]=argv[i+1];i+=2;
|
|
21
21
|
}
|
|
22
22
|
need(request.skillDir&&request.project,'invalid_arguments');
|
|
@@ -211,3 +211,59 @@ test('quick mode still reports an actual mechanical failure',{timeout:5000},asyn
|
|
|
211
211
|
assert.equal(report.result.overall,'FAILED','quick mode must not swallow a failing checker');
|
|
212
212
|
assert.equal(report.result.semanticChecked,false);
|
|
213
213
|
});
|
|
214
|
+
|
|
215
|
+
test('an explicit runtime reaches the checker; omitting it never claims a dispatch verdict',{timeout:5000},async t=>{
|
|
216
|
+
const f=fixture(t),seen=[];
|
|
217
|
+
for(const runtime of ['codex','claude']){
|
|
218
|
+
const host=createCmCheckHost({...f.input,runtime,quick:true},{call:async(kind,payload)=>{
|
|
219
|
+
seen.push(payload.invocation.args);return mechanical(payload);
|
|
220
|
+
}});
|
|
221
|
+
const report=await host.handle({requestId:`r-${runtime}`,operation:'start'});
|
|
222
|
+
assert.equal(report.result.overall,'MECHANICAL_ONLY');
|
|
223
|
+
}
|
|
224
|
+
assert.deepEqual(seen,[
|
|
225
|
+
['--project',f.input.project,'--runtime','codex','--print-effective'],
|
|
226
|
+
['--project',f.input.project,'--runtime','claude','--print-effective']
|
|
227
|
+
],'the checker must be told which runtime is actually running it');
|
|
228
|
+
const plain=[];
|
|
229
|
+
const host=createCmCheckHost({...f.input,quick:true},{call:async(kind,payload)=>{
|
|
230
|
+
plain.push(payload.invocation.args);return mechanical(payload);
|
|
231
|
+
}});
|
|
232
|
+
await host.handle({requestId:'r-none',operation:'start'});
|
|
233
|
+
assert.deepEqual(plain,[['--project',f.input.project,'--print-effective']],'an unnamed runtime must not be substituted with a guess');
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
test('an unsupported runtime is rejected instead of silently defaulting',{timeout:5000},async t=>{
|
|
237
|
+
const f=fixture(t);
|
|
238
|
+
for(const runtime of ['pi','CODEX','unknown','',null]){
|
|
239
|
+
assert.throws(()=>createCmCheckHost({...f.input,runtime},{call:async()=>{throw Error('must not run');}}),
|
|
240
|
+
error=>error.code==='runtime_invalid',`runtime ${JSON.stringify(runtime)} must not reach the checker`);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test('the JSONL CLI accepts --runtime once and rejects a malformed one',{timeout:5000},async t=>{
|
|
245
|
+
const f=fixture(t),cli=path.join(f.dir,'scripts/cm-check-host.mjs');
|
|
246
|
+
const base=['serve','--skill-dir',f.input.skillDir,'--project',f.input.project];
|
|
247
|
+
for(const extra of [['--runtime'],['--runtime','claude','--runtime','codex']]){
|
|
248
|
+
const bad=spawnSync(process.execPath,[cli,...base,...extra],{encoding:'utf8',input:''});
|
|
249
|
+
assert.equal(bad.status,1,`${extra.join(' ')} must not start a session`);
|
|
250
|
+
assert.match(bad.stderr,/invalid_arguments/);
|
|
251
|
+
}
|
|
252
|
+
const help=spawnSync(process.execPath,[cli,'--help'],{encoding:'utf8'});
|
|
253
|
+
assert.match(help.stdout,/--runtime codex\|claude/,'the documented usage must name the option');
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
test('the standalone mechanical entry CLI takes the runtime flag and validates it',{timeout:5000},async t=>{
|
|
257
|
+
const f=fixture(t),cli=path.join(f.dir,'scripts/cm-check-entry.mjs');
|
|
258
|
+
const base=['--skill-dir',f.input.skillDir,'--project',f.input.project];
|
|
259
|
+
const ok=spawnSync(process.execPath,[cli,...base,'--runtime','claude','--print-effective'],{encoding:'utf8'});
|
|
260
|
+
assert.equal(ok.status,0,ok.stderr);
|
|
261
|
+
assert.match(ok.stdout,/original checker output/,'the real checker must still be the one that runs');
|
|
262
|
+
for(const extra of [['--runtime','pi'],['--runtime','unknown']]){
|
|
263
|
+
const bad=spawnSync(process.execPath,[cli,...base,...extra,'--print-effective'],{encoding:'utf8'});
|
|
264
|
+
assert.equal(bad.status,2,`${extra.join(' ')} must not run the checker`);
|
|
265
|
+
assert.match(bad.stderr,/runtime_invalid/);
|
|
266
|
+
}
|
|
267
|
+
const dup=spawnSync(process.execPath,[cli,...base,'--runtime','codex','--runtime','claude','--print-effective'],{encoding:'utf8'});
|
|
268
|
+
assert.equal(dup.status,2);assert.match(dup.stderr,/invalid_arguments/);
|
|
269
|
+
});
|
|
@@ -184,29 +184,38 @@ PROJECT_PATH="$PWD"
|
|
|
184
184
|
CONFIG_PATH=""
|
|
185
185
|
REQUESTED_MODE=""
|
|
186
186
|
PRINT_EFFECTIVE=0
|
|
187
|
+
CHECK_RUNTIME=""
|
|
187
188
|
while [ "$#" -gt 0 ]; do
|
|
188
189
|
case "$1" in
|
|
189
190
|
--project)
|
|
190
|
-
[ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
|
|
191
|
+
[ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
|
|
191
192
|
PROJECT_PATH="$2"
|
|
192
193
|
shift 2
|
|
193
194
|
;;
|
|
194
195
|
--config)
|
|
195
|
-
[ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
|
|
196
|
+
[ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
|
|
196
197
|
CONFIG_PATH="$2"
|
|
197
198
|
shift 2
|
|
198
199
|
;;
|
|
199
200
|
--routing-fixtures|--log-fixtures)
|
|
200
|
-
[ -z "$REQUESTED_MODE" ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
|
|
201
|
+
[ -z "$REQUESTED_MODE" ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
|
|
201
202
|
REQUESTED_MODE="$1"
|
|
202
203
|
shift
|
|
203
204
|
;;
|
|
205
|
+
--runtime)
|
|
206
|
+
[ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
|
|
207
|
+
case "$2" in
|
|
208
|
+
codex|claude) CHECK_RUNTIME="$2" ;;
|
|
209
|
+
*) echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2 ;;
|
|
210
|
+
esac
|
|
211
|
+
shift 2
|
|
212
|
+
;;
|
|
204
213
|
--print-effective)
|
|
205
214
|
PRINT_EFFECTIVE=1
|
|
206
215
|
shift
|
|
207
216
|
;;
|
|
208
217
|
*)
|
|
209
|
-
echo "Usage: $0 [--project PATH] [--config PATH] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2
|
|
218
|
+
echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2
|
|
210
219
|
exit 2
|
|
211
220
|
;;
|
|
212
221
|
esac
|
|
@@ -395,14 +404,14 @@ if [ -n "$NODE_BIN" ]; then
|
|
|
395
404
|
for rt in $missing; do
|
|
396
405
|
warn "runtimes.available 声明 ${declared},但本机 ${rt} CLI 不可解析(可解析≠配额可用)"
|
|
397
406
|
done
|
|
398
|
-
current_runtime="${CM_RUNTIME:-
|
|
407
|
+
current_runtime="${CHECK_RUNTIME:-${CM_RUNTIME:-unknown}}"
|
|
399
408
|
for role in coder reviewer; do
|
|
400
409
|
if [ -n "$CONFIG_PATH" ]; then
|
|
401
410
|
role_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --config "$CONFIG_PATH" --role "$role" --runtime "$current_runtime" --print-role 2>/dev/null || true)
|
|
402
411
|
else
|
|
403
412
|
role_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --role "$role" --runtime "$current_runtime" --print-role 2>/dev/null || true)
|
|
404
413
|
fi
|
|
405
|
-
role_line=$(printf '%s' "$role_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{let j={};try{j=JSON.parse(d);}catch{}const tag=j.route_state==="declared-adapter"?"(已声明未派发)":"";process.stdout.write(`${j.role||"?"}: adapter=${j.adapter||"?"} route_state=${
|
|
414
|
+
role_line=$(printf '%s' "$role_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{let j={};try{j=JSON.parse(d);}catch{}const unknown=process.argv[1]==="unknown";const state=unknown?"未判定":(j.route_state||"?");const tag=unknown?"(当前运行时未指定,用 --runtime 或 CM_RUNTIME 指定后才能判断)":(j.route_state==="declared-adapter"?"(已声明未派发)":"");process.stdout.write(`${j.role||"?"}: adapter=${j.adapter||"?"} route_state=${state}${tag}`);})' "$current_runtime" 2>/dev/null || true)
|
|
406
415
|
[ -n "$role_line" ] && echo "runtime declaration [${declared}] ${role_line}"
|
|
407
416
|
done
|
|
408
417
|
fi
|
|
@@ -57,6 +57,45 @@ function fakeWorker(cwd,{value=proposal,mode='normal',timeoutMs=3000,noticeEvent
|
|
|
57
57
|
const rateLimit=(overrides={})=>({type:'rate_limit_event',session_id:'synthetic-claude-developer',
|
|
58
58
|
rate_limit_info:{status:'allowed',rateLimitType:'five_hour',resetsAt:123,active:true,reason:null,
|
|
59
59
|
nested:{raw:'private'},list:['private']},...overrides});
|
|
60
|
+
const devIntent=(sessionId='synthetic-claude-developer')=>JSON.parse(
|
|
61
|
+
`{"type":"system","subtype":"dev_intent","kind":"ios_app","trigger":"project_scan","uuid":"fixture-uuid","session_id":"${sessionId}"}`,
|
|
62
|
+
);
|
|
63
|
+
test('developer accepts dev_intent on either side of init with a sanitized notice',async t=>{
|
|
64
|
+
const root=fixture(t),control={signal:new AbortController().signal};
|
|
65
|
+
const baseline=await fakeWorker(root)({prompt:prompt()},control);
|
|
66
|
+
for(const noticeAt of [0,1,2]){
|
|
67
|
+
const notices=[],result=await fakeWorker(root,{noticeAt,noticeEvents:[devIntent()],onNotice:n=>notices.push(n)})
|
|
68
|
+
({prompt:prompt()},control);
|
|
69
|
+
assert.deepEqual(result,baseline);
|
|
70
|
+
assert.deepEqual(notices,[{kind:'claude_system_notice',subtype:'dev_intent'}]);
|
|
71
|
+
}
|
|
72
|
+
for(const onNotice of [undefined,()=>{throw Error('notice consumer');}]){
|
|
73
|
+
const result=await fakeWorker(root,{noticeAt:0,noticeEvents:[devIntent()],onNotice})({prompt:prompt()},control);
|
|
74
|
+
assert.deepEqual(result,baseline);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
test('developer dev_intent binds init session and shares a 32-notice budget',async t=>{
|
|
78
|
+
const root=fixture(t),control={signal:new AbortController().signal};
|
|
79
|
+
for(const [noticeEvents,noticeAt,code] of [
|
|
80
|
+
[[devIntent('other')],0,'session_mismatch'],
|
|
81
|
+
[[devIntent('other')],1,'session_mismatch'],
|
|
82
|
+
[[devIntent('')],0,'invalid_session'],
|
|
83
|
+
[[devIntent(' '.repeat(3))],0,'invalid_session'],
|
|
84
|
+
[[devIntent('x'.repeat(129))],0,'invalid_session'],
|
|
85
|
+
[[{...devIntent(),subtype:'api_retry'}],0,'missing_init'],
|
|
86
|
+
[[{...devIntent(),subtype:'future_notice'}],1,'unexpected_event'],
|
|
87
|
+
[Array.from({length:33},()=>devIntent()),0,'unexpected_event'],
|
|
88
|
+
]){
|
|
89
|
+
const result=await fakeWorker(root,{noticeEvents,noticeAt})({prompt:prompt()},control);
|
|
90
|
+
assert.deepEqual(result,{status:'unknown',code});
|
|
91
|
+
}
|
|
92
|
+
const notices=[],baseline=await fakeWorker(root)({prompt:prompt()},control);
|
|
93
|
+
const result=await fakeWorker(root,{noticeAt:1,
|
|
94
|
+
noticeEvents:[devIntent(),...Array.from({length:30},()=>devIntent()),rateLimit()],
|
|
95
|
+
onNotice:n=>notices.push(n)})({prompt:prompt()},control);
|
|
96
|
+
assert.deepEqual(result,baseline);
|
|
97
|
+
assert.equal(notices.length,32);
|
|
98
|
+
});
|
|
60
99
|
test('developer forwards scalar notices while preserving proposals and read-tool state',async t=>{
|
|
61
100
|
const root=fixture(t),events=[],control={signal:new AbortController().signal,onEvent:e=>events.push(e)};
|
|
62
101
|
const baseline=await fakeWorker(root)({prompt:prompt()},control);
|
|
@@ -110,7 +149,7 @@ test('developer rejects mismatched, excessive, unknown and terminal rate limit e
|
|
|
110
149
|
const root=fixture(t);
|
|
111
150
|
for(const [noticeEvents,noticeAt,code,count] of [
|
|
112
151
|
[[rateLimit({session_id:'other'})],1,'session_mismatch',0],
|
|
113
|
-
[Array.from({length:
|
|
152
|
+
[Array.from({length:33},()=>rateLimit()),1,'unexpected_event',32],
|
|
114
153
|
[[rateLimit({type:'foo_event'})],1,'unexpected_event',0],
|
|
115
154
|
[[rateLimit()],0,'missing_init',0],
|
|
116
155
|
[[rateLimit()],3,'invalid_event',0],
|
|
@@ -170,12 +170,55 @@ test('rate limit session, count, whitelist and terminal boundaries fail closed',
|
|
|
170
170
|
});
|
|
171
171
|
|
|
172
172
|
const systemNotice = (subtype='api_retry',extra={}) => ({type:'system',subtype,session_id:'fresh-review',...extra});
|
|
173
|
+
const devIntent = (sessionId='fresh-review') => JSON.parse(
|
|
174
|
+
`{"type":"system","subtype":"dev_intent","kind":"ios_app","trigger":"project_scan","uuid":"fixture-uuid","session_id":"${sessionId}"}`,
|
|
175
|
+
);
|
|
173
176
|
function observe(messages,callback) {
|
|
174
177
|
const events=[],notices=[];
|
|
175
178
|
const stream=createClaudeReviewStream(e=>events.push(e),callback ?? (n=>notices.push(n)));
|
|
176
179
|
messages.forEach(m=>stream.accept(m));
|
|
177
180
|
return {result:stream.finish(),events,notices};
|
|
178
181
|
}
|
|
182
|
+
test('dev_intent before or after init preserves review result and emits only its subtype',()=>{
|
|
183
|
+
const [init,assistant,result]=transcript(),baseline=observe(transcript());
|
|
184
|
+
for(const messages of [
|
|
185
|
+
[devIntent(),init,assistant,result],
|
|
186
|
+
[init,devIntent(),assistant,result],
|
|
187
|
+
[init,assistant,devIntent(),result],
|
|
188
|
+
]){
|
|
189
|
+
const actual=observe(messages);
|
|
190
|
+
assert.deepEqual(actual.result,baseline.result);
|
|
191
|
+
assert.deepEqual(actual.events,baseline.events);
|
|
192
|
+
assert.deepEqual(actual.notices,[{kind:'claude_system_notice',subtype:'dev_intent'}]);
|
|
193
|
+
}
|
|
194
|
+
for(const callback of [undefined,()=>{throw Error('notice consumer');}]){
|
|
195
|
+
const stream=createClaudeReviewStream(()=>{},callback);
|
|
196
|
+
[devIntent(),init,assistant,result].forEach(message=>stream.accept(message));
|
|
197
|
+
assert.deepEqual(stream.finish(),baseline.result);
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
test('dev_intent binds session across init and shares the 32-notice budget',()=>{
|
|
201
|
+
const [init,assistant,result]=transcript();
|
|
202
|
+
for(const messages of [
|
|
203
|
+
[devIntent('other'),init],
|
|
204
|
+
[init,devIntent('other')],
|
|
205
|
+
])assert.throws(()=>decode(messages),{code:'session_mismatch'});
|
|
206
|
+
for(const sessionId of ['', ' '.repeat(3), 'x'.repeat(257)]){
|
|
207
|
+
const stream=createClaudeReviewStream(()=>{});
|
|
208
|
+
assert.throws(()=>stream.accept(devIntent(sessionId)),{code:'invalid_session'});
|
|
209
|
+
}
|
|
210
|
+
assert.throws(()=>decode([systemNotice('api_retry'),init]),{code:'missing_init'});
|
|
211
|
+
assert.throws(()=>decode([init,systemNotice('future_notice')]),{code:'unexpected_event'});
|
|
212
|
+
const notices=[],stream=createClaudeReviewStream(()=>{},notice=>notices.push(notice));
|
|
213
|
+
[devIntent(),...Array.from({length:30},()=>devIntent()),init,rateLimit(),assistant,result]
|
|
214
|
+
.forEach(message=>stream.accept(message));
|
|
215
|
+
assert.equal(stream.finish().status,'succeeded');
|
|
216
|
+
assert.equal(notices.length,32);
|
|
217
|
+
const overflow=createClaudeReviewStream(()=>{});
|
|
218
|
+
[devIntent(),init,...Array.from({length:31},()=>devIntent())]
|
|
219
|
+
.forEach(message=>overflow.accept(message));
|
|
220
|
+
assert.throws(()=>overflow.accept(devIntent()),{code:'unexpected_event'});
|
|
221
|
+
});
|
|
179
222
|
test('88-heartbeat dogfood event counts preserve structured findings and exact observation',()=>{
|
|
180
223
|
const [init,text,result]=transcript();
|
|
181
224
|
const value={verdict:'changes_requested',packageDigest:'a'.repeat(64),examinedPaths:['code.mjs'],
|
|
@@ -3,11 +3,11 @@ import assert from 'node:assert/strict';
|
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import os from 'node:os';
|
|
6
|
-
import {spawn} from 'node:child_process';
|
|
6
|
+
import {spawn,spawnSync} from 'node:child_process';
|
|
7
7
|
import {once} from 'node:events';
|
|
8
8
|
import {createInterface} from 'node:readline';
|
|
9
9
|
import {fileURLToPath} from 'node:url';
|
|
10
|
-
import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange} from '../runtime/js/cm-prd/change.mjs';
|
|
10
|
+
import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange,assertPrdReviewsSettled} from '../runtime/js/cm-prd/change.mjs';
|
|
11
11
|
import {loadConfig} from './cm-workflow-config.mjs';
|
|
12
12
|
import {recordPrdReview} from './cm-prd-review-gate.mjs';
|
|
13
13
|
|
|
@@ -83,6 +83,34 @@ test('actual change CLI resumes unsaved phase across processes and stops at huma
|
|
|
83
83
|
c=await client(t,dir,()=>assert.fail('completed recovery must not call host'),{session:runId});
|
|
84
84
|
assert.equal((await c.request('status')).result.stage,'awaiting_review');await c.close();
|
|
85
85
|
});
|
|
86
|
+
test('approved change retains revision history for the next real cm-prd change',t=>{
|
|
87
|
+
const dir=fixture(t),reviews=path.join(dir,'.reviews');fs.mkdirSync(reviews);
|
|
88
|
+
const evidence=path.join(reviews,'prd-guide-split-r1.md'),receipt=path.join(reviews,'prd-guide-split-disposition.json');
|
|
89
|
+
fs.writeFileSync(evidence,'---\nat: 2026-09-08T00:00:00Z\nreviewer: codex-subagent\nindependent: true\nscope:\n - 1.guide/tasks.md\n---\nSynthetic original review');
|
|
90
|
+
recordPrdReview({stage:'split',feature:'guide',evidence,receipt,disposition:'no_findings',finding_count:0,unresolved_count:0,
|
|
91
|
+
artifact:docs().map(doc=>path.join(dir,'1.guide',doc.path))});
|
|
92
|
+
const selected=['1.guide'],config=loadConfig({projectRoot:dir});
|
|
93
|
+
const before=inspectPrdChangeSnapshot(dir);
|
|
94
|
+
const proposal=inspectPrdChangeProposal(before,{status:'draft',summary:'Add example',removed:[],features:[
|
|
95
|
+
{directory:'1.guide',documents:revised(),testCasesReason:'no_observable_behavior'}]},selected,config);
|
|
96
|
+
const proposalDigest=proposal.proposalDigest;
|
|
97
|
+
const saved=applyPrdChange({specs:dir,before,proposal,selected});
|
|
98
|
+
assert.equal(saved.status,'awaiting_review');
|
|
99
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).revisionDigest,proposalDigest);
|
|
100
|
+
const approval=spawnSync(process.execPath,[path.join(root,'scripts/cm-ai-admission.mjs'),'--specs-dir',dir,
|
|
101
|
+
'--code-project',dir,'--approve','--approval-response','开始'],{encoding:'utf8'});
|
|
102
|
+
assert.equal(approval.status,0,approval.stdout+approval.stderr);
|
|
103
|
+
assert.doesNotThrow(()=>assertPrdReviewsSettled(dir,['1.guide'],{requireSplit:true}));
|
|
104
|
+
const nextDocs=revised().map(doc=>({path:doc.path,content:doc.content.replace('| 2026-09-08 | v2 | change |',
|
|
105
|
+
'| 2026-09-08 | v2 | change |\n| 2026-09-08 | v3 | another change |')+
|
|
106
|
+
(doc.path==='tasks.md'?'\n- [ ] T-004: [NEW] More examples\n':'\nMore detail\n')}));
|
|
107
|
+
const nextBefore=inspectPrdChangeSnapshot(dir);
|
|
108
|
+
const nextProposal=inspectPrdChangeProposal(nextBefore,{status:'draft',summary:'Another guide change',removed:[],features:[
|
|
109
|
+
{directory:'1.guide',documents:nextDocs,testCasesReason:'no_observable_behavior'}]},selected,config);
|
|
110
|
+
const secondSaved=applyPrdChange({specs:dir,before:nextBefore,proposal:nextProposal,selected});
|
|
111
|
+
assert.equal(secondSaved.status,'awaiting_review');
|
|
112
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).revisionDigest,nextProposal.proposalDigest);
|
|
113
|
+
});
|
|
86
114
|
test('unknown host generation resumes only its exact original receipt, no repeat call', {timeout:25000},async t=>{
|
|
87
115
|
const dir=fixture(t);let original;
|
|
88
116
|
let c=await client(t,dir,message=>{
|
package/scripts/cm-prd-drive.mjs
CHANGED
|
@@ -274,17 +274,23 @@ function validate(kind,value,ctx){
|
|
|
274
274
|
}
|
|
275
275
|
}
|
|
276
276
|
let loaded;
|
|
277
|
+
export async function runPrdContextChecks(cwd,commands){
|
|
278
|
+
const results=[];
|
|
279
|
+
for(const command of commands){
|
|
280
|
+
const run=createHostCheck({cwd,commands:[command],onOutput:({stream,chunk})=>{
|
|
281
|
+
process.stderr.write(`[drive check ${command.id} ${stream}] ${chunk}`);
|
|
282
|
+
}});
|
|
283
|
+
const [item]=await run({identity:{repositoryId:'prd',runId:'prd-check',taskId:'prd-check',attempt:1}},
|
|
284
|
+
{signal:new AbortController().signal});
|
|
285
|
+
results.push(item);if(item.outcome!=='passed')break;
|
|
286
|
+
}
|
|
287
|
+
return results;
|
|
288
|
+
}
|
|
277
289
|
async function answerFor(row,answers){
|
|
278
290
|
const v=answers[row.kind];
|
|
279
291
|
if(row.kind==='prd_materials')return null;
|
|
280
292
|
if(row.kind==='prd_self_check'){
|
|
281
|
-
const results=
|
|
282
|
-
for(const command of loaded.plan.contextChecks){
|
|
283
|
-
const run=createHostCheck({cwd:loaded.admission.project,commands:[command],onOutput:({stream,chunk})=>process.stderr.write(`[drive check ${command.id} ${stream}] ${chunk}`)});
|
|
284
|
-
const [item]=await run({identity:{repositoryId:'prd',runId:'prd-check',taskId:'prd-check',attempt:1}},
|
|
285
|
-
{signal:new AbortController().signal});
|
|
286
|
-
results.push(item);if(item.outcome!=='passed')break;
|
|
287
|
-
}
|
|
293
|
+
const results=await runPrdContextChecks(loaded.admission.project,loaded.plan.contextChecks);
|
|
288
294
|
const draft=row.payload.draft;const evidence=results.map(r=>`${r.id}: ${r.evidence}`);
|
|
289
295
|
return {draftDigest:draft.draftDigest,features:draft.features.map(f=>({directory:f.directory,
|
|
290
296
|
checks:draft.mechanicalSelfCheck.pending.map(id=>({id,status:results.every(r=>r.outcome==='passed')?
|
|
@@ -6,6 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import {spawn,spawnSync} from 'node:child_process';
|
|
7
7
|
import {createInterface} from 'node:readline';
|
|
8
8
|
import {fileURLToPath} from 'node:url';
|
|
9
|
+
import {runPrdContextChecks} from './cm-prd-drive.mjs';
|
|
9
10
|
|
|
10
11
|
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
11
12
|
const driver=path.join(root,'scripts/cm-prd-drive.mjs');
|
|
@@ -33,6 +34,15 @@ const draft={status:'draft',summary:'Synthetic documentation draft',features:[{n
|
|
|
33
34
|
documents:[{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Document setup.'},
|
|
34
35
|
{path:'design.md',content:'## 方案摘要\nSynthetic design'},
|
|
35
36
|
{path:'tasks.md',content:'- [ ] T-001: Update guide'}]}]};
|
|
37
|
+
test('contextChecks with stdout and stderr record a passed command',async t=>{
|
|
38
|
+
const f=fixture(t);
|
|
39
|
+
const checks=await runPrdContextChecks(f.project,[{id:'output',command:[process.execPath,'-e',
|
|
40
|
+
"console.log('x');console.error('y')"]}]);
|
|
41
|
+
assert.notEqual(checks[0].evidence,'host check: output_capture_failed');
|
|
42
|
+
assert.equal(checks[0].outcome,'passed');
|
|
43
|
+
assert.equal(checks[0].exitCode,0);
|
|
44
|
+
assert.match(checks[0].evidence,/exited 0/);
|
|
45
|
+
});
|
|
36
46
|
function draftReady(t){
|
|
37
47
|
const f=fixture(t);f.write('analyze.json',analyzed);f.write('generate.json',draft);
|
|
38
48
|
const start=f.drive('start');assert.equal(start.status,0,start.stderr);
|
|
@@ -10,6 +10,9 @@ import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
|
|
|
10
10
|
import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
|
|
11
11
|
import {recordPrdHostDisposition,createPrdDispositionOwner} from '../runtime/js/cm-prd/review-disposition.mjs';
|
|
12
12
|
import {inspectPrdSummaryEvidence,createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
|
|
13
|
+
import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange} from '../runtime/js/cm-prd/change.mjs';
|
|
14
|
+
import {approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
|
|
15
|
+
import {loadConfig} from './cm-workflow-config.mjs';
|
|
13
16
|
const sha=content=>createHash('sha256').update(content).digest('hex');
|
|
14
17
|
function fixture(t,{pendingCorrection=false}={}){
|
|
15
18
|
const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-summary-marks-')));
|
|
@@ -79,6 +82,34 @@ function summaryOwner(){
|
|
|
79
82
|
signals:{greenfieldAdr:false,architectureOrDataFlow:false,newRuntimeDependencyOrToolchain:false,
|
|
80
83
|
publicContractDataOrSecurity:false,fiveOrMoreFunctions:false},evidence:['Synthetic documentation fixture']}))})});
|
|
81
84
|
}
|
|
85
|
+
test('change digest survives later summary publication, recovery, approval, and another change',async t=>{
|
|
86
|
+
const {specs}=fixture(t),directory='3.notes',selected=[directory];
|
|
87
|
+
fs.mkdirSync(path.join(specs,directory));
|
|
88
|
+
const original=[
|
|
89
|
+
{path:'requirements.md',content:'## 需求版本\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-09-08 | v1 | original |\n## 功能需求\n1. [F-003] Notes\n- [ ] [AC-003] Read notes\n'},
|
|
90
|
+
{path:'design.md',content:'## 设计版本\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-09-08 | v1 | original |\n## 方案摘要\nNotes\n'},
|
|
91
|
+
{path:'tasks.md',content:'## 任务版本\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-09-08 | v1 | original |\n- [ ] T-003: Notes\n'}];
|
|
92
|
+
for(const doc of original)fs.writeFileSync(path.join(specs,directory,doc.path),doc.content);
|
|
93
|
+
const revise=(docs,version)=>docs.map(doc=>({path:doc.path,content:doc.content+
|
|
94
|
+
`\n| 2026-09-08 | v${version} | change |\n`+(doc.path==='tasks.md'?`- [ ] T-00${version+2}: [NEW] Extend notes\n`:'More notes\n')}));
|
|
95
|
+
const config=loadConfig({projectRoot:specs});
|
|
96
|
+
const before=inspectPrdChangeSnapshot(specs),proposal=inspectPrdChangeProposal(before,{status:'draft',summary:'Extend notes',removed:[],
|
|
97
|
+
features:[{directory,documents:revise(original,2),testCasesReason:'no_observable_behavior'}]},selected,config);
|
|
98
|
+
assert.equal(applyPrdChange({specs,before,proposal,selected}).status,'awaiting_review');
|
|
99
|
+
const summary=await summaryOwner()(specs,{currentFeatures:['2.appendix']});
|
|
100
|
+
assert.equal(summary.readyForAwaitingReview,true,JSON.stringify(summary.blockers));
|
|
101
|
+
assert.equal(publishPrdAwaitingReview({specs,summary,writeEnabled:true}).status,'awaiting_review');
|
|
102
|
+
const published=fs.readFileSync(path.join(specs,'.cm-specs-status'));
|
|
103
|
+
assert.equal(JSON.parse(published).revisionDigest,proposal.proposalDigest);
|
|
104
|
+
assert.equal(publishPrdAwaitingReview({specs,summary,writeEnabled:true,recover:true}).status,'awaiting_review');
|
|
105
|
+
assert.deepEqual(fs.readFileSync(path.join(specs,'.cm-specs-status')),published);
|
|
106
|
+
const approval=approveCmAiSpecs({specsDir:specs,codeProject:specs,approvalResponse:'开始'});
|
|
107
|
+
assert.equal(approval.projectResults[0].state,'ready',JSON.stringify(approval));
|
|
108
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'))).revisionDigest,proposal.proposalDigest);
|
|
109
|
+
const nextBefore=inspectPrdChangeSnapshot(specs),nextProposal=inspectPrdChangeProposal(nextBefore,{status:'draft',summary:'Extend notes again',removed:[],
|
|
110
|
+
features:[{directory,documents:revise(revise(original,2),3),testCasesReason:'no_observable_behavior'}]},selected,config);
|
|
111
|
+
assert.equal(applyPrdChange({specs,before:nextBefore,proposal:nextProposal,selected}).status,'awaiting_review');
|
|
112
|
+
});
|
|
82
113
|
function legacy(specs){
|
|
83
114
|
const prefix=path.join(specs,'.reviews/prd-guide-split');
|
|
84
115
|
for(const suffix of ['-disposition.json','-dispatch.json'])fs.unlinkSync(prefix+suffix);
|