@aibyzero/cm-workflow 0.16.6 → 0.16.8
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 +29 -0
- package/README.md +32 -1
- package/VERSION +1 -1
- package/assets/readme/workflow-recovery-detailed.png +0 -0
- package/assets/readme/workflow-stages-detailed.png +0 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +84 -9
- package/docs/user-guide.md +104 -0
- package/package.json +1 -1
- package/runtime/js/cm-ai/cm-ai-admission.mjs +37 -11
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +56 -17
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +172 -33
- package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
- package/runtime/js/cm-ai/drive-bootstrap.mjs +2 -2
- package/runtime/js/cm-ai/drive-core.mjs +17 -4
- package/runtime/js/cm-ai/durable-runner-state.mjs +29 -0
- package/runtime/js/cm-ai/execution-store.mjs +4 -2
- package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -3
- package/runtime/js/cm-ai/host-documentation.mjs +2 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +89 -19
- package/runtime/js/cm-ai/host-session.mjs +46 -6
- package/runtime/js/cm-ai/host-tool-bridge.mjs +15 -3
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
- package/runtime/js/cm-ai/log-rows.mjs +36 -0
- package/runtime/js/cm-ai/operator-guidance.mjs +3 -0
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
- package/runtime/js/cm-ai/task-runner.mjs +6 -1
- package/runtime/js/cm-fix/cause-package.mjs +37 -8
- package/runtime/js/cm-fix/diagnosis.mjs +43 -0
- package/runtime/js/cm-fix/execution.mjs +189 -148
- package/runtime/js/cm-fix/finish.mjs +2 -19
- package/runtime/js/cm-fix/investigation.mjs +25 -9
- package/runtime/js/cm-fix/log-events.mjs +29 -0
- package/runtime/js/cm-fix/metrics.mjs +3 -2
- package/runtime/js/cm-fix/progress.mjs +3 -1
- package/runtime/js/cm-prd/analysis.mjs +5 -2
- package/runtime/js/cm-prd/review-host.mjs +2 -1
- package/runtime/js/cm-test/recovery.mjs +4 -4
- package/runtime/js/notify-run.mjs +26 -0
- package/runtime/js/notify.mjs +388 -0
- package/runtime/model-efficiency.md +17 -0
- package/scripts/cm-ai-admission.mjs +14 -3
- package/scripts/cm-ai-batch-drive.mjs +2 -2
- package/scripts/cm-ai-batch-host.mjs +7 -2
- package/scripts/cm-ai-batch-run.mjs +11 -2
- package/scripts/cm-ai-batch-run.test.mjs +9 -1
- package/scripts/cm-ai-drive.mjs +18 -4
- package/scripts/cm-ai-drive.test.mjs +30 -0
- package/scripts/cm-ai-feature-selection.test.mjs +178 -0
- package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
- package/scripts/cm-ai-host.mjs +20 -8
- package/scripts/cm-ai-host.test.mjs +88 -0
- package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
- package/scripts/cm-ai-protected-scope.test.mjs +194 -0
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +77 -4
- package/scripts/cm-ai-run.mjs +36 -5
- package/scripts/cm-fix-abandon.test.mjs +89 -3
- package/scripts/cm-fix-cause-package.test.mjs +33 -0
- package/scripts/cm-fix-drive.mjs +9 -1
- package/scripts/cm-fix-host.mjs +1 -1
- package/scripts/cm-fix-large-log.test.mjs +113 -0
- package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
- package/scripts/cm-host-qa-executor.test.mjs +429 -3
- package/scripts/cm-log-event.mjs +53 -6
- package/scripts/cm-notify.test.mjs +468 -0
- package/scripts/cm-patrol.mjs +83 -0
- package/scripts/cm-patrol.test.mjs +161 -0
- package/scripts/cm-prd-host.mjs +13 -2
- package/scripts/cm-prd-host.test.mjs +4 -0
- package/scripts/cm-prd-review-host.test.mjs +17 -0
- package/scripts/cm-prd-session-recovery.test.mjs +44 -2
- package/scripts/cm-prd-task-grouping.test.mjs +206 -0
- package/scripts/cm-review-scope-recovery.test.mjs +5 -3
- package/scripts/cm-test-branch-impact.test.mjs +11 -0
- package/scripts/cm-token-report.mjs +497 -0
- package/scripts/cm-token-report.test.mjs +346 -0
- package/skills/cm-ai/SKILL.md +7 -3
- package/skills/cm-ai/references/N1-init.md +1 -1
- package/skills/cm-ai/references/N6-qa-eval.md +2 -2
- package/skills/cm-ai/references/js-host-modes.md +90 -0
- package/skills/cm-ai/references/js-host-qa-recovery.md +110 -0
- package/skills/cm-ai/references/js-host-recovery.md +199 -0
- package/skills/cm-ai/references/js-host.md +69 -330
- package/skills/cm-fix/SKILL.md +2 -0
- package/skills/cm-fix/references/js-host.md +16 -9
- package/skills/cm-prd/SKILL.md +7 -4
- package/skills/cm-prd/references/spec-self-check.md +3 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 只读巡检:找出「登记过、进程却已不在」的 CM 宿主,合并成一条卡住提醒。
|
|
3
|
+
// 宿主活着但没人推进由宿主自己的空转计时负责(runtime/js/cm-ai/host-session.mjs);
|
|
4
|
+
// 这里只抓宿主已死(被杀、崩溃、机器重启)而没来得及收尾的情况。
|
|
5
|
+
// 只读 <home>/hosts 下的登记文件和进程是否存在(process.kill(pid,0)),不读日志、
|
|
6
|
+
// 不读项目文件、不写任何流程状态。会写的只有两样:提醒模块自己的去重/限流状态
|
|
7
|
+
// (notify-state.json、notify.log,和其他提醒一样),以及删除已报告的登记文件。
|
|
8
|
+
// 用法:node cm-patrol.mjs 巡检并提醒
|
|
9
|
+
// node cm-patrol.mjs --report 只把结果以 JSON 打到标准输出,不提醒、不删文件
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import {fileURLToPath} from 'node:url';
|
|
13
|
+
import {HOST_REGISTRY_MAX_AGE_MS,hostRegistryDir,notify,readNotifyConfig} from '../runtime/js/notify.mjs';
|
|
14
|
+
|
|
15
|
+
const NAME=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.json$/;
|
|
16
|
+
// nextAction is capped at 200 chars by the notice; list what fits, count the rest.
|
|
17
|
+
const LIST_BUDGET=150;
|
|
18
|
+
const text=value=>typeof value==='string'&&value?value:null;
|
|
19
|
+
|
|
20
|
+
// A pid the current user cannot signal (EPERM) still exists; only ESRCH is gone.
|
|
21
|
+
export function processAlive(pid){
|
|
22
|
+
if(pid===process.pid)return true;
|
|
23
|
+
try{process.kill(pid,0);return true;}catch(error){return error.code!=='ESRCH';}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function readEntry(file){
|
|
27
|
+
try{
|
|
28
|
+
const value=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
29
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||value.version!==1)return null;
|
|
30
|
+
if(!Number.isSafeInteger(value.pid)||value.pid<=0)return null;
|
|
31
|
+
const at=Date.parse(value.at);if(!Number.isFinite(at))return null;
|
|
32
|
+
return {file,pid:value.pid,at,sessionKey:text(value.sessionKey),workflow:text(value.workflow)??'cm',project:text(value.project),
|
|
33
|
+
runId:text(value.runId),task:text(value.task),stage:text(value.stage),operation:text(value.operation)};
|
|
34
|
+
}catch{return null;}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// {live, dead, stale, invalid}: dead = registered within 48 hours, process gone.
|
|
38
|
+
export function inspectHosts({env=process.env,now=Date.now()}={}){
|
|
39
|
+
const result={live:[],dead:[],stale:[],invalid:0};
|
|
40
|
+
let names;
|
|
41
|
+
try{names=fs.readdirSync(hostRegistryDir(env)).filter(name=>NAME.test(name));}catch{return result;}
|
|
42
|
+
for(const name of names){
|
|
43
|
+
const entry=readEntry(path.join(hostRegistryDir(env),name));
|
|
44
|
+
if(!entry){result.invalid++;continue;}
|
|
45
|
+
if(now-entry.at>HOST_REGISTRY_MAX_AGE_MS||entry.at>now)result.stale.push(entry);
|
|
46
|
+
else if(processAlive(entry.pid))result.live.push(entry);
|
|
47
|
+
else result.dead.push(entry);
|
|
48
|
+
}
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const stamp=at=>new Date(at).toISOString().slice(11,16)+'Z';
|
|
53
|
+
const line=entry=>[entry.workflow,entry.runId,entry.task,entry.stage??entry.operation,`最后动静 ${stamp(entry.at)}`].filter(Boolean).join(' ');
|
|
54
|
+
|
|
55
|
+
// One notice for every dead host found in this pass. The key names the set, so
|
|
56
|
+
// the same set is not resent within the notice window; reported entries are
|
|
57
|
+
// removed so the next pass only sees new ones.
|
|
58
|
+
export function patrol({env=process.env,now=Date.now(),report=false}={}){
|
|
59
|
+
const hosts=inspectHosts({env,now});
|
|
60
|
+
const summary={at:new Date(now).toISOString(),live:hosts.live.length,dead:hosts.dead.length,stale:hosts.stale.length,invalid:hosts.invalid,
|
|
61
|
+
deadHosts:hosts.dead.map(entry=>({workflow:entry.workflow,pid:entry.pid,runId:entry.runId,task:entry.task,stage:entry.stage,at:new Date(entry.at).toISOString()}))};
|
|
62
|
+
if(report)return {...summary,notice:'report_only'};
|
|
63
|
+
if(!readNotifyConfig(env))return {...summary,notice:'off'};
|
|
64
|
+
if(hosts.dead.length===0)return {...summary,notice:'none'};
|
|
65
|
+
const dead=[...hosts.dead].sort((a,b)=>a.at-b.at);
|
|
66
|
+
const workflows=new Set(dead.map(entry=>entry.workflow)),projects=new Set(dead.map(entry=>entry.project).filter(Boolean));
|
|
67
|
+
const listed=[];let used=0;
|
|
68
|
+
for(const entry of dead){const item=line(entry);if(used+item.length>LIST_BUDGET)break;listed.push(item);used+=item.length+1;}
|
|
69
|
+
if(listed.length<dead.length)listed.push(`另有 ${dead.length-listed.length} 个`);
|
|
70
|
+
const sent=notify({key:`dead|${dead.map(entry=>entry.sessionKey??entry.file).sort().join(',')}`,event:'dead',
|
|
71
|
+
workflow:workflows.size===1?[...workflows][0]:'cm',project:projects.size===1?[...projects][0]:null,
|
|
72
|
+
runId:dead.length===1?dead[0].runId:null,task:dead.length===1?dead[0].task:null,
|
|
73
|
+
stage:`${dead.length} 个宿主进程已不在`,code:'host_process_gone',
|
|
74
|
+
nextAction:`${listed.join(';')}。请回到会话用 status 核对运行状态,需要时按恢复说明接手`},{env,now});
|
|
75
|
+
if(sent.sent||sent.reason==='duplicate')for(const entry of dead){try{fs.unlinkSync(entry.file);}catch{}}
|
|
76
|
+
return {...summary,notice:sent.sent?'sent':sent.reason};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url)){
|
|
80
|
+
const report=process.argv.includes('--report');
|
|
81
|
+
const result=patrol({report});
|
|
82
|
+
if(report)process.stdout.write(JSON.stringify(result,null,2)+'\n');
|
|
83
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {spawn,spawnSync} from 'node:child_process';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {patrol,inspectHosts,processAlive} from './cm-patrol.mjs';
|
|
9
|
+
import {hostRegistryDir,buildNotifyMessage,removeHostRegistry} from '../runtime/js/notify.mjs';
|
|
10
|
+
|
|
11
|
+
const HOST_SESSION=new URL('../runtime/js/cm-ai/host-session.mjs',import.meta.url).href;
|
|
12
|
+
const PATROL=fileURLToPath(new URL('./cm-patrol.mjs',import.meta.url));
|
|
13
|
+
const NOW=Date.parse('2026-10-09T08:00:00.000Z');
|
|
14
|
+
const KEYS=['11111111-1111-4111-8111-111111111111','22222222-2222-4222-8222-222222222222','33333333-3333-4333-8333-333333333333',
|
|
15
|
+
'44444444-4444-4444-8444-444444444444'];
|
|
16
|
+
|
|
17
|
+
// A temp CM_WORKFLOW_HOME whose notify.json points at a fake command that
|
|
18
|
+
// appends its message to sent.jsonl.
|
|
19
|
+
function home(t,{withConfig=true}={}){
|
|
20
|
+
const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-patrol-')));
|
|
21
|
+
t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
|
22
|
+
const sent=path.join(dir,'sent.jsonl'),script=path.join(dir,'fake-notify.mjs');
|
|
23
|
+
fs.writeFileSync(script,`import fs from 'node:fs';let input='';process.stdin.on('data',c=>input+=c);
|
|
24
|
+
process.stdin.on('end',()=>{fs.appendFileSync(${JSON.stringify(sent)},JSON.stringify({title:process.env.CM_NOTIFY_TITLE,
|
|
25
|
+
body:process.env.CM_NOTIFY_BODY,stdin:JSON.parse(input)})+'\\n');});`);
|
|
26
|
+
if(withConfig)fs.writeFileSync(path.join(dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script]}));
|
|
27
|
+
const env={...process.env,CM_WORKFLOW_HOME:dir};
|
|
28
|
+
const rows=()=>fs.existsSync(sent)?fs.readFileSync(sent,'utf8').trim().split('\n').map(line=>JSON.parse(line)):[];
|
|
29
|
+
const until=async(check,ms=8000)=>{const end=Date.now()+ms;while(!check()&&Date.now()<end)await new Promise(r=>setTimeout(r,25));return check();};
|
|
30
|
+
const registry=()=>fs.existsSync(hostRegistryDir(env))?fs.readdirSync(hostRegistryDir(env)).filter(name=>name.endsWith('.json')).sort():[];
|
|
31
|
+
const write=(key,entry)=>{fs.mkdirSync(hostRegistryDir(env),{recursive:true});fs.writeFileSync(path.join(hostRegistryDir(env),`${key}.json`),
|
|
32
|
+
typeof entry==='string'?entry:JSON.stringify({version:1,sessionKey:key,workflow:'cm-ai',project:'/srv/work/demo-app',startedAt:new Date(NOW-3600000).toISOString(),
|
|
33
|
+
at:new Date(NOW-600000).toISOString(),runId:'run-1',task:'T-003',stage:'awaiting_review',operation:'advance',...entry}));};
|
|
34
|
+
return {dir,env,rows,until,registry,write};
|
|
35
|
+
}
|
|
36
|
+
// A pid that certainly existed and is gone now.
|
|
37
|
+
function gonePid(){const child=spawnSync(process.execPath,['-e','']);assert.equal(child.status,0);return child.pid;}
|
|
38
|
+
|
|
39
|
+
test('processAlive: own pid and a finished child',()=>{
|
|
40
|
+
assert.equal(processAlive(process.pid),true);
|
|
41
|
+
assert.equal(processAlive(gonePid()),false);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('host session registers itself when notices are configured: written at start, updated per reply, removed at end',async t=>{
|
|
45
|
+
const h=home(t);
|
|
46
|
+
const script=path.join(h.dir,'cm-prd-host.mjs');
|
|
47
|
+
fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
|
|
48
|
+
const host={handle:async request=>{if(request.slowMs)await new Promise(resolve=>setTimeout(resolve,request.slowMs));
|
|
49
|
+
return request.operation==='status'?{stage:'poll'}:{stage:request.stage,runId:'prd-9'};}};
|
|
50
|
+
await serveCmAiHost({host,input:process.stdin,output:process.stdout});`);
|
|
51
|
+
const env={...h.env};delete env.NODE_TEST_CONTEXT;
|
|
52
|
+
const child=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
|
|
53
|
+
t.after(()=>{try{child.kill();}catch{}});
|
|
54
|
+
const exited=new Promise(resolve=>child.on('close',resolve));
|
|
55
|
+
let out='';child.stdout.on('data',chunk=>{out+=chunk;});
|
|
56
|
+
assert(await h.until(()=>h.registry().length===1),'registered at start');
|
|
57
|
+
const read=()=>JSON.parse(fs.readFileSync(path.join(hostRegistryDir(env),h.registry()[0]),'utf8'));
|
|
58
|
+
const first=read();
|
|
59
|
+
assert.equal(first.pid,child.pid);assert.equal(first.workflow,'cm-prd');assert.equal(first.project,process.cwd());
|
|
60
|
+
assert.equal(first.runId,null);assert.equal(first.operation,null);
|
|
61
|
+
child.stdin.write(JSON.stringify({requestId:'r1',operation:'advance',stage:'requirements_analysis'})+'\n');
|
|
62
|
+
assert(await h.until(()=>out.includes('"requestId":"r1"')&&read().operation==='advance'));
|
|
63
|
+
const after=read();assert.equal(after.runId,'prd-9');assert.equal(after.stage,'requirements_analysis');assert.equal(after.sessionKey,first.sessionKey);
|
|
64
|
+
child.stdin.write(JSON.stringify({requestId:'s1',operation:'status'})+'\n');
|
|
65
|
+
assert(await h.until(()=>out.includes('"requestId":"s1"')));
|
|
66
|
+
await new Promise(resolve=>setTimeout(resolve,100));
|
|
67
|
+
assert.equal(read().stage,'requirements_analysis','a status poll does not overwrite the registry');
|
|
68
|
+
child.stdin.end();assert.equal(await exited,0);
|
|
69
|
+
assert.deepEqual(h.registry(),[],'removed at session end');
|
|
70
|
+
// EOF while an operation is still running: its reply must not re-register after the removal.
|
|
71
|
+
const busy=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
|
|
72
|
+
t.after(()=>{try{busy.kill();}catch{}});
|
|
73
|
+
const busyExit=new Promise(resolve=>busy.on('close',resolve));let busyOut='';busy.stdout.on('data',chunk=>{busyOut+=chunk;});
|
|
74
|
+
assert(await h.until(()=>h.registry().length===1));
|
|
75
|
+
busy.stdin.write(JSON.stringify({requestId:'r1',operation:'advance',stage:'slow',slowMs:600})+'\n');
|
|
76
|
+
await new Promise(resolve=>setTimeout(resolve,100));busy.stdin.end();
|
|
77
|
+
assert.equal(await busyExit,0);assert.match(busyOut,/"requestId":"r1"/,'the in-flight reply is still delivered');
|
|
78
|
+
assert.deepEqual(h.registry(),[],'removed after the in-flight reply');
|
|
79
|
+
// A session that ends immediately leaves nothing behind either.
|
|
80
|
+
const quick=spawnSync(process.execPath,[script],{env,input:''});assert.equal(quick.status,0,quick.stderr);
|
|
81
|
+
assert.deepEqual(h.registry(),[]);
|
|
82
|
+
// Without notify.json nothing is written.
|
|
83
|
+
const off=home(t,{withConfig:false});const offEnv={...off.env};delete offEnv.NODE_TEST_CONTEXT;
|
|
84
|
+
const silent=spawnSync(process.execPath,[script],{env:offEnv,input:JSON.stringify({requestId:'r1',operation:'advance',stage:'x'})+'\n'});
|
|
85
|
+
assert.equal(silent.status,0,silent.stderr);assert.equal(fs.existsSync(hostRegistryDir(offEnv)),false);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test('patrol: dead hosts are merged into one notice and their entries removed; live, stale and invalid entries are left alone',async t=>{
|
|
89
|
+
const h=home(t),gone=gonePid();
|
|
90
|
+
h.write(KEYS[0],{pid:process.pid});
|
|
91
|
+
h.write(KEYS[1],{pid:gone,workflow:'cm-ai',task:'T-003',at:new Date(NOW-900000).toISOString()});
|
|
92
|
+
h.write(KEYS[2],{pid:gone,workflow:'cm-fix',runId:'fix-2',task:null,stage:'repair_required',at:new Date(NOW-300000).toISOString()});
|
|
93
|
+
h.write(KEYS[3],{pid:gone,at:new Date(NOW-49*3600000).toISOString()});
|
|
94
|
+
h.write('55555555-5555-4555-8555-555555555555','{not json');
|
|
95
|
+
const seen=inspectHosts({env:h.env,now:NOW});
|
|
96
|
+
assert.deepEqual([seen.live.length,seen.dead.length,seen.stale.length,seen.invalid],[1,2,1,1]);
|
|
97
|
+
const first=patrol({env:h.env,now:NOW});
|
|
98
|
+
assert.equal(first.notice,'sent');assert.equal(first.dead,2);
|
|
99
|
+
assert(await h.until(()=>h.rows().length===1));
|
|
100
|
+
const [row]=h.rows();
|
|
101
|
+
assert.equal(row.title,'CM cm 宿主已退出未收尾 · demo-app');
|
|
102
|
+
assert.equal(row.stdin.code,'host_process_gone');assert.equal(row.stdin.stage,'2 个宿主进程已不在');
|
|
103
|
+
assert.match(row.body,/cm-ai run-1 T-003 awaiting_review 最后动静 07:45Z;cm-fix fix-2 repair_required 最后动静 07:55Z/);
|
|
104
|
+
assert.doesNotMatch(row.body+JSON.stringify(row.stdin),/srv|demo-app\//,'no paths in body or payload');
|
|
105
|
+
assert.deepEqual(h.registry(),[`${KEYS[0]}.json`,`${KEYS[3]}.json`,'55555555-5555-4555-8555-555555555555.json']);
|
|
106
|
+
const again=patrol({env:h.env,now:NOW+60000});
|
|
107
|
+
assert.equal(again.notice,'none');assert.equal(again.dead,0);
|
|
108
|
+
await new Promise(resolve=>setTimeout(resolve,300));assert.equal(h.rows().length,1);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('patrol: a single dead host names its run and workflow; rate-limited or off keeps the entry for a later pass',async t=>{
|
|
112
|
+
const h=home(t),gone=gonePid();
|
|
113
|
+
h.write(KEYS[1],{pid:gone,workflow:'cm-prd',runId:'prd-7',task:null,stage:'awaiting_user'});
|
|
114
|
+
const state={version:1,keys:{},sends:Array.from({length:4},()=>NOW-1000)};
|
|
115
|
+
fs.writeFileSync(path.join(h.dir,'notify-state.json'),JSON.stringify(state));
|
|
116
|
+
assert.equal(patrol({env:h.env,now:NOW}).notice,'rate_minute');
|
|
117
|
+
assert.deepEqual(h.registry(),[`${KEYS[1]}.json`],'kept for the next pass');
|
|
118
|
+
assert.equal(patrol({env:h.env,now:NOW+61000}).notice,'sent');
|
|
119
|
+
assert(await h.until(()=>h.rows().length===1));
|
|
120
|
+
assert.equal(h.rows()[0].title,'CM cm-prd 宿主已退出未收尾 · demo-app');
|
|
121
|
+
assert.equal(h.rows()[0].stdin.runId,'prd-7');assert.equal(h.rows()[0].stdin.stage,'1 个宿主进程已不在');
|
|
122
|
+
assert.deepEqual(h.registry(),[]);
|
|
123
|
+
const off=home(t,{withConfig:false});off.write(KEYS[1],{pid:gone});
|
|
124
|
+
assert.equal(patrol({env:off.env,now:NOW}).notice,'off');assert.deepEqual(off.registry(),[`${KEYS[1]}.json`]);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('--report prints the summary and neither notifies nor removes anything',t=>{
|
|
128
|
+
const h=home(t),gone=gonePid();
|
|
129
|
+
h.write(KEYS[1],{pid:gone});
|
|
130
|
+
const run=spawnSync(process.execPath,[PATROL,'--report'],{encoding:'utf8',env:{...h.env,NODE_TEST_CONTEXT:undefined}});
|
|
131
|
+
assert.equal(run.status,0,run.stderr);
|
|
132
|
+
const summary=JSON.parse(run.stdout);
|
|
133
|
+
assert.equal(summary.notice,'report_only');assert.equal(summary.dead,1);assert.equal(summary.deadHosts[0].pid,gone);
|
|
134
|
+
assert.deepEqual(h.registry(),[`${KEYS[1]}.json`]);assert.equal(h.rows().length,0);
|
|
135
|
+
const plain=spawnSync(process.execPath,[PATROL],{encoding:'utf8',env:{...h.env,NODE_TEST_CONTEXT:undefined}});
|
|
136
|
+
assert.equal(plain.status,0,plain.stderr);assert.equal(plain.stdout,'');
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test('Windows paths are redacted like POSIX ones, also when glued to CJK text',()=>{
|
|
140
|
+
const {body}=buildNotifyMessage({workflow:'cm-ai',nextAction:'见 C:\\Users\\me\\proj\\a.txt 和 \\\\server\\share\\b 以及 /tmp/c'},{now:NOW});
|
|
141
|
+
assert.match(body,/下一步:见 <路径> 和 <路径> 以及 <路径>/);
|
|
142
|
+
const glued=buildNotifyMessage({workflow:'cm-ai',nextAction:'请检查C:\\Users\\me\\a.txt,再看\\\\srv\\s;或/tmp/c。相对 a/b 和 v1.2/x 保留'},{now:NOW}).body;
|
|
143
|
+
assert.match(glued,/下一步:请检查<路径>,再看<路径>;或<路径>。相对 a\/b 和 v1.2\/x 保留/);
|
|
144
|
+
assert.doesNotMatch(glued,/Users|srv|tmp/);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
// Under node --test without an explicit CM_WORKFLOW_HOME nothing in the user's
|
|
148
|
+
// real directory is touched, not even an unlink of a registry entry.
|
|
149
|
+
test('registry removal honours the test guard',t=>{
|
|
150
|
+
const fakeHome=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-patrol-home-')));
|
|
151
|
+
t.after(()=>fs.rmSync(fakeHome,{recursive:true,force:true}));
|
|
152
|
+
const dir=path.join(fakeHome,'.cm-workflow','hosts');fs.mkdirSync(dir,{recursive:true});
|
|
153
|
+
const file=path.join(dir,`${KEYS[0]}.json`);fs.writeFileSync(file,'{}');
|
|
154
|
+
// os.homedir() reads HOME from the live process environment, so point it at the fake home for this test only.
|
|
155
|
+
const realHome=process.env.HOME;process.env.HOME=fakeHome;t.after(()=>{process.env.HOME=realHome;});
|
|
156
|
+
assert.equal(os.homedir(),fakeHome);
|
|
157
|
+
const env={...process.env,NODE_TEST_CONTEXT:'1'};delete env.CM_WORKFLOW_HOME;
|
|
158
|
+
removeHostRegistry(KEYS[0],{env});assert.equal(fs.existsSync(file),true,'home left alone under node --test');
|
|
159
|
+
removeHostRegistry(KEYS[0],{env:{...env,CM_WORKFLOW_HOME:path.join(fakeHome,'.cm-workflow')}});
|
|
160
|
+
assert.equal(fs.existsSync(file),false,'explicit home is honoured');
|
|
161
|
+
});
|
package/scripts/cm-prd-host.mjs
CHANGED
|
@@ -85,7 +85,17 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
85
85
|
need(receipt.run_id===runId&&receipt.project_log===path.join(admission.specs,'运行日志.jsonl'),'prd_log_failed');
|
|
86
86
|
};
|
|
87
87
|
bridge=createHostToolBridge({responseLimit:1024*1024});
|
|
88
|
-
|
|
88
|
+
let replaying=false,replayCallIndex=0;
|
|
89
|
+
const call=(kind,payload,signal)=>{
|
|
90
|
+
const original=replaying?session.state.active?.calls[replayCallIndex++]:null;
|
|
91
|
+
if(original?.kind==='prd_generate'&&kind==='prd_generate'){
|
|
92
|
+
need(original.requestDigest===digest({kind:original.kind,payload:original.payload}),'prd_recovery_binding');
|
|
93
|
+
// Only the registered instructions survive a prompt update. All other
|
|
94
|
+
// reconstructed fields still pass session.call's strict digest check.
|
|
95
|
+
payload={...payload,instructions:original.payload.instructions};
|
|
96
|
+
}
|
|
97
|
+
return session.call(kind,payload,signal,(body,sig)=>bridge.call(kind,body,sig));
|
|
98
|
+
};
|
|
89
99
|
const restoreAnalysis=restored=>admission.mode==='new'?createCmPrdAnalysis({input:entry,runtime,record,restored,allowInputDrift:true,
|
|
90
100
|
checkContext:(payload,signal)=>call('prd_self_check',payload,signal),
|
|
91
101
|
generate:(payload,signal)=>call('prd_generate',payload,signal),
|
|
@@ -100,7 +110,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
100
110
|
const makeCorrect=()=>createPrdCorrectionOwner({correct:(payload,signal)=>call('prd_correct',{
|
|
101
111
|
...payload,project:admission.project,specs:admission.specs,
|
|
102
112
|
reference:path.join(admission.workflowRoot,'skills/cm-prd/SKILL.md')},signal)});
|
|
103
|
-
let correct=makeCorrect()
|
|
113
|
+
let correct=makeCorrect();
|
|
104
114
|
const dispose=createPrdDispositionOwner({validateCurrent:input=>{if(input.stage==='split')analysis.validateCurrent(input);},canRecoverRecorded:()=>replaying&&session.state.active.calls.some(call=>call.kind==='prd_self_check'&&Object.hasOwn(call,'result')),
|
|
105
115
|
checkContext:(payload,signal)=>call('prd_self_check',{
|
|
106
116
|
...payload,project:admission.project,specs:admission.specs,
|
|
@@ -276,6 +286,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
276
286
|
}
|
|
277
287
|
if(request.resolution!==null)session.resolve(request.resolution);
|
|
278
288
|
const active=session.replay();
|
|
289
|
+
replayCallIndex=0;
|
|
279
290
|
need(active.calls.every(call=>Object.hasOwn(call,'result')),'prd_host_result_unknown');
|
|
280
291
|
restore(active.before);operation=active.request;replaying=true;
|
|
281
292
|
// Claim-first review recovery publishes the recorded ORIGINAL result through
|
|
@@ -52,6 +52,8 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
52
52
|
}
|
|
53
53
|
if(message.kind==='prd_review'){
|
|
54
54
|
assert.equal(mode,'self-check');assert.equal(message.payload.authorContextId,'author-context');
|
|
55
|
+
assert.match(message.payload.instructions,/assess submitted task boundaries/);
|
|
56
|
+
assert.match(message.payload.instructions,/Do not.*repartition already generated tasks/);
|
|
55
57
|
send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,
|
|
56
58
|
result:{reviewer:'codex-subagent',contextId:'reviewer-context',independent:true,at:'2026-09-08T00:00:00.000Z',
|
|
57
59
|
result:{verdict:'changes_requested',packageDigest:message.payload.package.packageDigest,
|
|
@@ -66,6 +68,8 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
66
68
|
}
|
|
67
69
|
if(message.kind==='prd_generate'){
|
|
68
70
|
assert.ok(['draft','self-check'].includes(mode));assert.equal(message.payload.role.role,'planner');
|
|
71
|
+
if(message.payload.revision===null)assert.match(message.payload.instructions,/FIRST task planning only/);
|
|
72
|
+
else assert.doesNotMatch(message.payload.instructions,/FIRST task planning only/);
|
|
69
73
|
send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,
|
|
70
74
|
result:{status:'draft',summary:'Synthetic documentation draft',features:[{name:'guide',testCasesReason:'no_observable_behavior',
|
|
71
75
|
documents:['requirements.md','design.md','tasks.md'].map(file=>({path:file,
|
|
@@ -28,3 +28,20 @@ for(const mode of ['success','denied','disconnect','cancel','mode-switch'])test(
|
|
|
28
28
|
const file=path.join(specs,'.reviews/prd-guide-split-r1.md');assert.equal(fs.existsSync(file),mode==='success');
|
|
29
29
|
if(['disconnect','mode-switch'].includes(mode)){assert.equal((await run()).status,'review_existing');assert.equal(calls,1);}
|
|
30
30
|
});
|
|
31
|
+
|
|
32
|
+
test('design review transport remains unchanged and does not receive split grouping guidance',async t=>{
|
|
33
|
+
const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-review-design-')));
|
|
34
|
+
t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));
|
|
35
|
+
const draft={draftDigest:'a'.repeat(64),features:[{directory:'1.guide',name:'guide',documents:[
|
|
36
|
+
{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide'},
|
|
37
|
+
{path:'design.md',content:'## 方案摘要\nGuide'}]}]};
|
|
38
|
+
const prepare=()=>preparePrdReview({specs,draft,stage:'design',feature:'1.guide'});let calls=0;
|
|
39
|
+
const result=await runPrdHostReview({specs,prepared:prepare(),authorContextId:'author',writeEnabled:true,mode:'independent',
|
|
40
|
+
revalidate:prepare,signal:new AbortController().signal,review:async payload=>{
|
|
41
|
+
calls++;assert.doesNotMatch(payload.instructions,/assess submitted task boundaries/);
|
|
42
|
+
assert.equal(payload.package.instructions,'Apply original Step 9.5 only when its risk triggers were established. Read relevant project rules and changed-module context plus steelman-review. No second attempt.');
|
|
43
|
+
return {reviewer:'codex-subagent',contextId:'reviewer',independent:true,at:'2026-10-06T00:00:00.000Z',
|
|
44
|
+
result:{verdict:'approved',packageDigest:payload.package.packageDigest,examinedPaths:payload.examinedPaths,findings:[],summary:'Synthetic design review'}};
|
|
45
|
+
}});
|
|
46
|
+
assert.equal(result.status,'review_recorded');assert.equal(calls,1);
|
|
47
|
+
});
|
|
@@ -9,6 +9,7 @@ import {createInterface} from 'node:readline';
|
|
|
9
9
|
import {fileURLToPath} from 'node:url';
|
|
10
10
|
import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
|
|
11
11
|
import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
|
|
12
|
+
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
12
13
|
const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
|
|
13
14
|
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
14
15
|
const sessionId='prd-recovery-fixture';
|
|
@@ -37,15 +38,16 @@ async function client(t,f){
|
|
|
37
38
|
...(f.entry.change?['--change',f.entry.change]:[])],
|
|
38
39
|
{env:{...process.env,CM_WORKFLOW_LOG_HOME:path.join(f.dir,'mirror')},stdio:['pipe','pipe','pipe']});
|
|
39
40
|
let stderr='',seq=0;child.stderr.on('data',chunk=>stderr+=chunk);
|
|
40
|
-
const closed=once(child,'close'),lines=createInterface({input:child.stdout}),queue=[],waiters=[];
|
|
41
|
+
const closed=once(child,'close'),lines=createInterface({input:child.stdout}),queue=[],waiters=[],requests=[];
|
|
41
42
|
lines.on('line',line=>{const value=JSON.parse(line),index=waiters.findIndex(w=>w.match(value));
|
|
43
|
+
if(value.type==='host_request')requests.push(value);
|
|
42
44
|
if(index===-1)queue.push(value);else waiters.splice(index,1)[0].resolve(value);});
|
|
43
45
|
const wait=match=>{const index=queue.findIndex(match);return index===-1?
|
|
44
46
|
new Promise(resolve=>waiters.push({match,resolve})):Promise.resolve(queue.splice(index,1)[0]);};
|
|
45
47
|
const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
|
|
46
48
|
t.after(async()=>{if(child.exitCode===null&&child.signalCode===null)child.kill();await closed;lines.close();});
|
|
47
49
|
const ready=await wait(m=>m.type==='host_ready');
|
|
48
|
-
return {wait,send,request:(operation,fields={})=>{const requestId=`request-${++seq}`;
|
|
50
|
+
return {wait,send,requests,request:(operation,fields={})=>{const requestId=`request-${++seq}`;
|
|
49
51
|
const reply=wait(m=>m.requestId===requestId);send({requestId,operation,...fields});return reply;},
|
|
50
52
|
close:async()=>{send({type:'host_close',sessionId:ready.sessionId});assert.equal((await closed)[0],0,stderr);},
|
|
51
53
|
result:(call,result)=>send({type:'host_result',sessionId:ready.sessionId,callId:call.callId,requestDigest:call.requestDigest,result})};
|
|
@@ -166,3 +168,43 @@ test('help documents abandon shape and terminal cancellation',()=>{
|
|
|
166
168
|
assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/abandon:true/);assert.match(result.stdout,/result absent/);
|
|
167
169
|
assert.match(result.stdout,/cancel is terminal/);assert.match(result.stdout,/prd_review/);
|
|
168
170
|
});
|
|
171
|
+
|
|
172
|
+
// Capture the actual generator request, then seed a durable interrupted call.
|
|
173
|
+
// Replaying a stored synthetic result verifies the transport boundary, not model judgement.
|
|
174
|
+
for(const mode of ['legacy-prompt','current-prompt','other-field-drift','corrupt-prompt-record'])
|
|
175
|
+
test(`first planner prompt update preserves original durable call: ${mode}`,{timeout:20000},async t=>{
|
|
176
|
+
const f=await fixture(t),before=f.state().checkpoint;let payload;
|
|
177
|
+
const analysis=createCmPrdAnalysis({input:f.entry,runtime:'codex',restored:before.analysis,record:()=>{},
|
|
178
|
+
analyze:async()=>assert.fail('analysis redispatched'),generate:async request=>{
|
|
179
|
+
payload=request;return {status:'question',question:'Synthetic original question'};
|
|
180
|
+
}});
|
|
181
|
+
await analysis.plan('Original tasks');assert.match(payload.instructions,/FIRST task planning only/);
|
|
182
|
+
if(mode==='legacy-prompt')payload.instructions=payload.instructions.split(' For FIRST task planning only:')[0];
|
|
183
|
+
if(mode==='other-field-drift')payload.messages.at(-1).text='Different original user answer';
|
|
184
|
+
const session=f.open();try{
|
|
185
|
+
session.begin({requestId:'original-plan',operation:'advance',text:'Original tasks'},before);
|
|
186
|
+
await assert.rejects(session.call('prd_generate',payload,new AbortController().signal,async()=>{throw Error('synthetic disconnect');}),/synthetic disconnect/);
|
|
187
|
+
}finally{session.close();}
|
|
188
|
+
if(mode==='corrupt-prompt-record'){
|
|
189
|
+
const state=f.state();state.active.calls[0].payload.instructions+=' Corrupt recorded instructions.';
|
|
190
|
+
fs.writeFileSync(path.join(f.dir,'.reviews/prd-sessions',sessionId,'state.json'),JSON.stringify(state),{mode:0o600});
|
|
191
|
+
}
|
|
192
|
+
const original=f.state().active.calls[0],c=await client(t,f);
|
|
193
|
+
blocked(await c.request('resume',{resolution:null}),'prd_host_result_unknown');
|
|
194
|
+
const response=await c.request('resume',{resolution:{callId:original.callId,requestDigest:original.requestDigest,
|
|
195
|
+
result:{status:'draft',summary:'Original recorded planner result',features:[{name:'next',testCasesReason:'no_observable_behavior',
|
|
196
|
+
documents:[{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Read next guide'},
|
|
197
|
+
{path:'design.md',content:'## 方案摘要\nGuide'},{path:'tasks.md',content:'- [ ] T-001: Original task'}]}]},
|
|
198
|
+
evidence:'Original call result retrieved, not another provider invocation'}});
|
|
199
|
+
if(mode==='other-field-drift')blocked(response,'prd_replay_inputs_changed');
|
|
200
|
+
else if(mode==='corrupt-prompt-record')blocked(response,'prd_recovery_binding');
|
|
201
|
+
else{
|
|
202
|
+
assert.equal(response.error,undefined);assert.equal(response.result.stage,'draft_ready');
|
|
203
|
+
assert.equal(f.state().active,null);assert.equal(response.result.draft.features[0].directory,'2.next');
|
|
204
|
+
assert.equal(response.result.draft.features[0].documents.find(d=>d.path==='tasks.md').content,'- [ ] T-001: Original task');
|
|
205
|
+
}
|
|
206
|
+
assert.equal(c.requests.length,0,'resume must consume only the original call');
|
|
207
|
+
if(f.state().active)assert.deepEqual(f.state().active.calls[0].payload,original.payload);
|
|
208
|
+
assert.equal(original.requestDigest===digest({kind:original.kind,payload:original.payload}),mode!=='corrupt-prompt-record');
|
|
209
|
+
assert(!fs.existsSync(path.join(f.dir,'2.next')));await c.close();
|
|
210
|
+
});
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Synthetic control-flow fixtures, not proof of a model's semantic judgement
|
|
2
|
+
// or production token/time savings. No classifier or provider is invoked.
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import assert from 'node:assert/strict';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import {fileURLToPath} from 'node:url';
|
|
9
|
+
import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
|
|
10
|
+
import {checkPrdDraftMechanics} from '../runtime/js/cm-prd/self-check.mjs';
|
|
11
|
+
import {savePrdDesign,savePrdDraft} from '../runtime/js/cm-prd/draft-save.mjs';
|
|
12
|
+
import {runPrdHostReview} from '../runtime/js/cm-prd/review-host.mjs';
|
|
13
|
+
import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
|
|
14
|
+
import {claimPrdReview,recordPrdReview} from './cm-prd-review-gate.mjs';
|
|
15
|
+
import {buildManifest} from './cm-spec-manifest.mjs';
|
|
16
|
+
import {inspectCmAiAdmission} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
|
|
17
|
+
import {loadConfig,resolveRole,runtimePreset} from './cm-workflow-config.mjs';
|
|
18
|
+
|
|
19
|
+
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
20
|
+
const sourceCases={schemaVersion:'1.0',feature:'list',cases:['Render list','Confirm deletion','Style feedback'].map((title,i)=>({
|
|
21
|
+
id:`TC-00${i+1}`,origin:'user',kind:'logic',blocking:true,acIds:[`AC-00${i+1}`],taskIds:['T-001'],
|
|
22
|
+
title,preconditions:['Local fixture'],steps:[title],expected:[`${title} works`],cleanup:['Restore fixture']}))};
|
|
23
|
+
const documents=()=>[
|
|
24
|
+
{path:'requirements.md',content:'## 功能需求\n1. [F-001] Reversible list feedback\n'+sourceCases.cases.map(c=>`- [ ] [${c.acIds[0]}] ${c.expected[0]}`).join('\n')},
|
|
25
|
+
{path:'design.md',content:'## 方案摘要\nLocal list component, one reversible objective.\n## 接口契约\nListView remains unchanged.'}];
|
|
26
|
+
const draft=(tasks='- [ ] T-001: List feedback ~15min',mapping=['T-001','T-001','T-001'])=>({
|
|
27
|
+
status:'draft',summary:'Synthetic task boundaries',features:[{name:'list',testCasesReason:null,
|
|
28
|
+
documents:[...documents(),{path:'tasks.md',content:tasks},{path:'test-cases.json',content:JSON.stringify({
|
|
29
|
+
...sourceCases,cases:sourceCases.cases.map((c,i)=>({...c,taskIds:[mapping[i]]}))})}]}]});
|
|
30
|
+
function checked(payload,failed=null){
|
|
31
|
+
return {draftDigest:payload.draft.draftDigest,features:payload.draft.features.map(f=>({directory:f.directory,
|
|
32
|
+
checks:payload.draft.mechanicalSelfCheck.pending.map(id=>({id,status:id===failed?'failed':'passed',
|
|
33
|
+
evidence:[id===failed?'Synthetic boundary finding: authentication and local list changes have independent rollback.':'Synthetic context reference']}))}))};
|
|
34
|
+
}
|
|
35
|
+
function fixture(t,text='Local list feedback, one verifiable reversible objective.'){
|
|
36
|
+
const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-task-grouping-')));
|
|
37
|
+
t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));fs.mkdirSync(path.join(dir,'docs'));
|
|
38
|
+
fs.writeFileSync(path.join(dir,'docs/input.md'),text);
|
|
39
|
+
const cases=path.join(dir,'user-cases.md');fs.writeFileSync(cases,JSON.stringify(sourceCases));
|
|
40
|
+
const config=path.join(dir,'.cm-workflow.json');fs.writeFileSync(config,JSON.stringify({
|
|
41
|
+
version:1,...runtimePreset('claude-codes'),policies:{generate_cases:false}}));
|
|
42
|
+
const configBytes=fs.readFileSync(config),caseBytes=fs.readFileSync(cases);
|
|
43
|
+
const input={skillDir:path.join(root,'skills/cm-prd'),project:dir,specs:dir,cases};
|
|
44
|
+
const calls=[];
|
|
45
|
+
const make=({generate,checkContext=async payload=>checked(payload),restored=null}={})=>createCmPrdAnalysis({
|
|
46
|
+
input,runtime:'codex',restored,record:async()=>{},
|
|
47
|
+
analyze:async payload=>{calls.push('analyze');assert.deepEqual(payload.sources.userCases.content,caseBytes.toString());
|
|
48
|
+
return {status:'analyzed',summary:text,sourcePaths:['docs/input.md',cases],openQuestions:[]};},
|
|
49
|
+
generate:async payload=>{calls.push('generate');assert.deepEqual(payload.role,resolveRole(loadConfig({projectRoot:dir}),'planner','codex'));
|
|
50
|
+
assert.equal(payload.userCases.content,caseBytes.toString());assert.equal(payload.generateCases,false);return generate(payload);},
|
|
51
|
+
checkContext:async payload=>{calls.push('self-check');return checkContext(payload);}});
|
|
52
|
+
const unchanged=()=>{assert.deepEqual(fs.readFileSync(config),configBytes);assert.deepEqual(fs.readFileSync(cases),caseBytes);};
|
|
53
|
+
return {dir,input,calls,make,unchanged};
|
|
54
|
+
}
|
|
55
|
+
async function review(f,host,inspect){
|
|
56
|
+
savePrdDraft({specs:f.dir,writeEnabled:true,getDraft:()=>host.currentDraftForSave()});
|
|
57
|
+
const prepare=()=>host.prepareReview('split','1.list');
|
|
58
|
+
const original=prepare();
|
|
59
|
+
const result=await runPrdHostReview({specs:f.dir,prepared:original,authorContextId:'author',writeEnabled:true,mode:'independent',
|
|
60
|
+
revalidate:prepare,signal:new AbortController().signal,review:async payload=>{
|
|
61
|
+
f.calls.push('review');inspect?.(payload);
|
|
62
|
+
return {reviewer:'codex-subagent',contextId:'fresh-reviewer',independent:true,at:'2026-10-06T00:00:00.000Z',
|
|
63
|
+
result:{verdict:'approved',packageDigest:payload.package.packageDigest,examinedPaths:payload.examinedPaths,findings:[],summary:'Synthetic scope review'}};
|
|
64
|
+
}});
|
|
65
|
+
assert.equal(result.status,'review_recorded');
|
|
66
|
+
// The durable gate, rather than the supplied synthetic verdict, controls repeats.
|
|
67
|
+
assert.equal((await runPrdHostReview({specs:f.dir,prepared:prepare(),authorContextId:'author',writeEnabled:true,mode:'independent',
|
|
68
|
+
revalidate:prepare,signal:new AbortController().signal,review:async()=>assert.fail('second review')})).status,'review_existing');
|
|
69
|
+
assert.equal(prepare().packageDigest,original.packageDigest);return original;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
test('first full plan reaches planner and one split review; grouped task retains every user case and AC',async t=>{
|
|
73
|
+
const f=fixture(t);const host=f.make({generate:async payload=>{
|
|
74
|
+
assert.equal(payload.phase,'full_draft');assert.equal(payload.revision,null);
|
|
75
|
+
assert.match(payload.instructions,/FIRST task planning only/);
|
|
76
|
+
assert.match(payload.instructions,/independently verifiable and reversible objective/);return draft();
|
|
77
|
+
}});
|
|
78
|
+
await host.advance('Analyze');assert.equal((await host.plan('First plan')).stage,'draft_ready');
|
|
79
|
+
const planned=host.status().draft;
|
|
80
|
+
assert.deepEqual(planned.mechanicalSelfCheck.features,[{directory:'1.list',tasks:1,acceptanceCriteria:3}]);
|
|
81
|
+
const cases=JSON.parse(planned.features[0].documents.find(d=>d.path==='test-cases.json').content);
|
|
82
|
+
assert.deepEqual(cases,sourceCases);assert.equal(planned.mechanicalSelfCheck.completeSelfCheck,false);
|
|
83
|
+
await host.verify();
|
|
84
|
+
await review(f,host,payload=>{
|
|
85
|
+
assert.match(payload.instructions,/assess submitted task boundaries/);
|
|
86
|
+
assert.match(payload.instructions,/high or unknown risk/);
|
|
87
|
+
assert.match(payload.instructions,/every AC, original test and verification prerequisite retained/);
|
|
88
|
+
assert.equal(payload.authorContextId,'author');assert.equal(payload.mode,'independent');
|
|
89
|
+
assert.deepEqual(payload.package.artifacts.map(a=>a.path).sort(),planned.features[0].documents.map(d=>'1.list/'+d.path).sort());
|
|
90
|
+
});
|
|
91
|
+
assert.deepEqual(f.calls,['analyze','generate','self-check','review']);f.unchanged();
|
|
92
|
+
assert.equal(host.status().completionAuthorized,false);
|
|
93
|
+
assert(!fs.existsSync(path.join(f.dir,'.cm-specs-status')));
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('first tasks after accepted design receive the same rules without another design/classifier call',async t=>{
|
|
97
|
+
const f=fixture(t);let generations=0;
|
|
98
|
+
const host=f.make({generate:async payload=>{
|
|
99
|
+
if(++generations===1){assert.equal(payload.phase,'design');assert.doesNotMatch(payload.instructions,/FIRST task planning only/);
|
|
100
|
+
return {status:'design',summary:'Local design',features:[{name:'list',documents:documents()}]};}
|
|
101
|
+
assert.equal(payload.phase,'tasks_after_design');assert.match(payload.instructions,/FIRST task planning only/);
|
|
102
|
+
assert.deepEqual(payload.acceptedDesign.features[0].documents,documents());return draft();
|
|
103
|
+
}});
|
|
104
|
+
await host.advance('Analyze');await host.plan('Design',{designOnly:true});
|
|
105
|
+
const ready=host.status().designDraft;
|
|
106
|
+
host.selectDesignReviews({draftDigest:ready.draftDigest,risks:[{feature:'1.list',signals:{greenfieldAdr:false,
|
|
107
|
+
architectureOrDataFlow:false,newRuntimeDependencyOrToolchain:false,publicContractDataOrSecurity:false,fiveOrMoreFunctions:false},
|
|
108
|
+
evidence:['Local component; no design-risk trigger']} ]});
|
|
109
|
+
savePrdDesign({specs:f.dir,writeEnabled:true,getDraft:()=>host.currentDesignForSave()});
|
|
110
|
+
await host.plan('First tasks');await host.verify();await review(f,host);
|
|
111
|
+
assert.deepEqual(f.calls,['analyze','generate','generate','self-check','review']);f.unchanged();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test('high/unknown-risk boundary rules reach the planner; existing semantic finding blocks review readiness',async t=>{
|
|
115
|
+
const f=fixture(t,'Local list and authentication; another module risk is unknown.');
|
|
116
|
+
const host=f.make({generate:async payload=>{
|
|
117
|
+
assert.match(payload.instructions,/Keep high-risk work, unknown-risk work/);
|
|
118
|
+
assert.match(payload.instructions,/not keyword risk classification or another model call/);
|
|
119
|
+
assert.match(payload.analysis.summary,/authentication.*unknown/);return draft();
|
|
120
|
+
},checkContext:async payload=>checked(payload,'task_boundary_and_existing_asset_overlap')});
|
|
121
|
+
await host.advance('Analyze');await host.plan('Plan with actual boundaries');
|
|
122
|
+
assert.equal(host.status().draft.mechanicalSelfCheck.status,'mechanical_subset_passed');
|
|
123
|
+
assert.equal((await host.verify()).stage,'self_check_failed');
|
|
124
|
+
assert.throws(()=>host.prepareReview('split','1.list'),/prd_review_not_ready/);
|
|
125
|
+
assert.deepEqual(f.calls,['analyze','generate','self-check']);f.unchanged();
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('explicit user split reaches planner unchanged; same-component independent tasks and cases remain intact',async t=>{
|
|
129
|
+
const request='Keep rendering and deletion confirmation as independent tasks for different owners.';
|
|
130
|
+
const f=fixture(t,request),tasks='- [ ] T-001: Render and style list\n- [ ] T-002: Confirm deletion';
|
|
131
|
+
const host=f.make({generate:async payload=>{
|
|
132
|
+
assert(payload.userAnswers.some(m=>m.text===request));assert(payload.messages.some(m=>m.text===request));
|
|
133
|
+
assert.match(payload.instructions,/explicit user requests for independent tasks/);return draft(tasks,['T-001','T-002','T-001']);
|
|
134
|
+
}});
|
|
135
|
+
await host.advance(request);await host.plan(request);await host.verify();
|
|
136
|
+
const planned=host.status().draft;assert.equal(planned.mechanicalSelfCheck.features[0].tasks,2);
|
|
137
|
+
assert.equal(planned.features[0].documents.find(d=>d.path==='tasks.md').content,tasks);
|
|
138
|
+
const cases=JSON.parse(planned.features[0].documents.find(d=>d.path==='test-cases.json').content);
|
|
139
|
+
cases.cases.forEach((c,i)=>{const {taskIds,...semantics}=c,{taskIds:old,...original}=sourceCases.cases[i];assert.deepEqual(semantics,original);});
|
|
140
|
+
await review(f,host,payload=>assert.match(payload.instructions,/explicit user independence/));f.unchanged();
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test('contract-first DAG remains separate; cycles, task cap and lost AC coverage still fail mechanically',async t=>{
|
|
144
|
+
const f=fixture(t),tasks='- [ ] T-001: Freeze interface and throwing placeholder\n- [ ] T-002: Implement interface\n- [ ] T-003: Call interface\n- T-002 依赖 T-001\n- T-003 依赖 T-001';
|
|
145
|
+
const host=f.make({generate:async payload=>{
|
|
146
|
+
assert.match(payload.instructions,/preserve legitimate contract-first tasks and real dependencies/);
|
|
147
|
+
return draft(tasks,['T-001','T-002','T-003']);
|
|
148
|
+
}});
|
|
149
|
+
await host.advance('Analyze');await host.plan('Contract before implementation');
|
|
150
|
+
const planned=host.status().draft;assert.equal(planned.mechanicalSelfCheck.features[0].tasks,3);
|
|
151
|
+
assert.equal(planned.features[0].documents.find(d=>d.path==='tasks.md').content,tasks);
|
|
152
|
+
const changed=structuredClone(planned),task=changed.features[0].documents.find(d=>d.path==='tasks.md');
|
|
153
|
+
task.content+='\n- T-001 依赖 T-002';assert(checkPrdDraftMechanics(changed).findings.some(f=>f.code==='dependencies_invalid'));
|
|
154
|
+
task.content=Array.from({length:16},(_,i)=>`- [ ] T-${String(i+1).padStart(3,'0')}: Independent`).join('\n');
|
|
155
|
+
assert(checkPrdDraftMechanics(changed).findings.some(f=>f.code==='task_limit_exceeded'));
|
|
156
|
+
task.content=tasks;const cases=JSON.parse(changed.features[0].documents.find(d=>d.path==='test-cases.json').content);
|
|
157
|
+
cases.cases.pop();changed.features[0].documents.find(d=>d.path==='test-cases.json').content=JSON.stringify(cases);
|
|
158
|
+
assert(checkPrdDraftMechanics(changed).findings.some(f=>f.code==='acceptance_test_coverage_missing'));f.unchanged();
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('existing failed draft and restored revision receive no first-plan regrouping; IDs and bytes survive',async t=>{
|
|
162
|
+
const f=fixture(t);let generations=0;
|
|
163
|
+
const host=f.make({generate:async()=>{generations++;return draft('- [ ] T-001: Existing first\n- [ ] T-002: Existing second',['T-001','T-002','T-001']);},
|
|
164
|
+
checkContext:async payload=>checked(payload,'acceptance_verifiability')});
|
|
165
|
+
await host.advance('Analyze');await host.plan('Original plan');await host.verify();
|
|
166
|
+
const checkpoint=host.checkpoint(),bytes=JSON.stringify(checkpoint);
|
|
167
|
+
const restored=f.make({restored:checkpoint,generate:async payload=>{
|
|
168
|
+
assert.doesNotMatch(payload.instructions,/FIRST task planning only/);assert.equal(payload.revision.round,2);
|
|
169
|
+
assert.equal(JSON.stringify(payload.revision.draft),JSON.stringify(checkpoint.draft));return draft('- [ ] T-001: Existing first\n- [ ] T-002: Existing second',['T-001','T-002','T-001']);
|
|
170
|
+
}});
|
|
171
|
+
assert.equal(JSON.stringify(restored.checkpoint()),bytes);
|
|
172
|
+
await restored.plan('Correct only the finding');
|
|
173
|
+
assert.equal(restored.status().draft.draftDigest,checkpoint.draft.draftDigest);
|
|
174
|
+
assert.equal(JSON.stringify(checkpoint),bytes);assert.equal(generations,1);f.unchanged();
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
test('approved task boundary drift remains blocked and does not rewrite approval or repartition tasks',async t=>{
|
|
178
|
+
const f=fixture(t),feature=path.join(f.dir,'1.list');fs.mkdirSync(feature);
|
|
179
|
+
for(const d of draft().features[0].documents)fs.writeFileSync(path.join(feature,d.path),d.content);
|
|
180
|
+
const file=path.join(f.dir,'.cm-specs-status');fs.writeFileSync(file,JSON.stringify({status:'approved',features:['1.list'],specFiles:buildManifest(f.dir)}));
|
|
181
|
+
const approval=fs.readFileSync(file),options={specsDir:f.dir,codeProject:f.dir};
|
|
182
|
+
assert.equal(inspectCmAiAdmission(options).state,'ready');
|
|
183
|
+
const task=path.join(feature,'tasks.md');fs.appendFileSync(task,'\n- [ ] T-002: Expanded objective');
|
|
184
|
+
const changed=fs.readFileSync(task),blocked=inspectCmAiAdmission(options);
|
|
185
|
+
assert.equal(blocked.state,'blocked');assert.equal(blocked.reason,'spec_drift');
|
|
186
|
+
assert.deepEqual(fs.readFileSync(file),approval);assert.deepEqual(fs.readFileSync(task),changed);f.unchanged();
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test('old split package instructions/digest survive claimed, r1 and completed gates with zero reviewer calls',async t=>{
|
|
190
|
+
for(const state of ['claimed','r1','completed']){
|
|
191
|
+
const f=fixture(t),raw=draft(),inspected={draftDigest:'a'.repeat(64),features:[{...raw.features[0],directory:'1.list'}]};
|
|
192
|
+
const prepare=()=>preparePrdReview({specs:f.dir,draft:inspected,stage:'split',feature:'1.list'}),ready=prepare();
|
|
193
|
+
assert.equal(ready.reviewPackage.instructions,'Apply original Step 10.6 to the functional requirements, complete task list and selected design sections. Respect prior design review and do not repeat it. No second attempt.');
|
|
194
|
+
fs.mkdirSync(path.join(f.dir,'.reviews'));claimPrdReview({...ready.paths,package_sha256:ready.packageDigest});
|
|
195
|
+
if(state!=='claimed'){
|
|
196
|
+
fs.mkdirSync(path.join(f.dir,'1.list'));for(const doc of raw.features[0].documents)fs.writeFileSync(path.join(f.dir,'1.list',doc.path),doc.content);
|
|
197
|
+
fs.writeFileSync(ready.paths.evidence,'---\nat: 2026-10-06T00:00:00Z\nreviewer: codex-subagent\nindependent: true\nscope:\n - 1.list/tasks.md\n---\nOriginal review');
|
|
198
|
+
if(state==='completed')recordPrdReview({...ready.paths,disposition:'no_findings',finding_count:0,unresolved_count:0,
|
|
199
|
+
artifact:raw.features[0].documents.map(doc=>path.join(f.dir,'1.list',doc.path))});
|
|
200
|
+
}
|
|
201
|
+
assert.equal(prepare().packageDigest,ready.packageDigest);const before=JSON.stringify(prepare());
|
|
202
|
+
const result=await runPrdHostReview({specs:f.dir,prepared:prepare(),authorContextId:'author',writeEnabled:true,mode:'independent',
|
|
203
|
+
revalidate:prepare,signal:new AbortController().signal,review:async()=>assert.fail('old attempt redispatched')});
|
|
204
|
+
assert.equal(result.status,'review_existing');assert.equal(JSON.stringify(prepare()),before);f.unchanged();
|
|
205
|
+
}
|
|
206
|
+
});
|