@aibyzero/cm-workflow 0.15.4 → 0.16.0

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.
@@ -0,0 +1,98 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import {readVerificationPrecheck} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
5
+
6
+ const item=(requirement,satisfied,evidence)=>({requirement,satisfied,evidence});
7
+ const rejects=value=>assert.throws(()=>readVerificationPrecheck(value),
8
+ error=>error.code==='verification_precheck_invalid'||error.code==='invalid_input',
9
+ `expected rejection for ${JSON.stringify(value)}`);
10
+
11
+ test('every requirement satisfied lets the delivery through to the real review', () => {
12
+ const verdict=readVerificationPrecheck({items:[
13
+ item('记录实现前基线',true,'npm test tests 42 / pass 42 / fail 0'),
14
+ item('观察 RED 并记录失败用例名',true,'4 个用例因占位体抛错失败'),
15
+ ]});
16
+ assert.equal(verdict.satisfied,true);
17
+ assert.deepEqual(verdict.unsatisfied,[]);
18
+ });
19
+
20
+ test('one unsatisfied requirement blocks and is named back', () => {
21
+ const verdict=readVerificationPrecheck({items:[
22
+ item('记录实现前基线',true,'tests 42 / pass 42 / fail 0'),
23
+ item('既有用例数不减少',false,'交付里只有实现后计数,没有实现前基线'),
24
+ item('新增用例只写在指定文件',true,'git status 只列出该文件'),
25
+ ]});
26
+ assert.equal(verdict.satisfied,false);
27
+ assert.deepEqual(verdict.unsatisfied,['既有用例数不减少']);
28
+ });
29
+
30
+ test('a requirement claimed satisfied without citing evidence is rejected', () => {
31
+ // The whole point of the gate is the evidence location, not the verdict.
32
+ rejects({items:[item('记录实现前基线',true,'')]});
33
+ rejects({items:[item('记录实现前基线',true,' ')]});
34
+ });
35
+
36
+ test('an empty or oversized answer set is rejected', () => {
37
+ rejects({items:[]});
38
+ rejects({items:Array.from({length:65},(_,index)=>item(`要求 ${index}`,true,'证据'))});
39
+ assert.equal(readVerificationPrecheck({items:Array.from({length:64},
40
+ (_,index)=>item(`要求 ${index}`,true,'证据'))}).satisfied,true);
41
+ });
42
+
43
+ test('extra, missing or mistyped fields are rejected', () => {
44
+ rejects({items:[{requirement:'x',satisfied:true}]});
45
+ rejects({items:[{...item('x',true,'y'),note:'多给一个字段'}]});
46
+ rejects({items:[item('x','true','y')]});
47
+ rejects({items:[item('x',1,'y')]});
48
+ rejects({items:'not an array'});
49
+ rejects({});
50
+ rejects({items:[item('x',true,'y')],extra:1});
51
+ });
52
+
53
+ test('control characters and oversized text are rejected', () => {
54
+ rejects({items:[item(`要求${String.fromCharCode(0)}注入`,true,'证据')]});
55
+ rejects({items:[item('要求',true,'a'.repeat(2001))]});
56
+ assert.equal(readVerificationPrecheck({items:[item('要求',true,'a'.repeat(2000))]}).satisfied,true);
57
+ });
58
+
59
+ test('the verdict is frozen so a caller cannot flip it after validation', () => {
60
+ const verdict=readVerificationPrecheck({items:[item('要求',false,'没对上')]});
61
+ assert.throws(()=>{verdict.satisfied=true;},TypeError);
62
+ assert.equal(verdict.satisfied,false);
63
+ });
64
+
65
+ // The gate is only useful if a blocked delivery can be redone. A gate that
66
+ // leaves the task unrecoverable would cost more than the rework it prevents.
67
+ test('a blocked delivery is reported as resumable, not as an unknown state', async () => {
68
+ const {default:fs}=await import('node:fs');
69
+ const {developmentRetryable}=await import('../runtime/js/cm-ai/cm-ai-conversation-entry.mjs');
70
+ assert.equal(developmentRetryable({state:'blocked',code:'verification_precheck_failed'}),true);
71
+ assert.equal(developmentRetryable({state:'unknown',code:'verification_precheck_failed'}),false);
72
+ // resume is the action that predicate maps to.
73
+ const source=fs.readFileSync(new URL('../runtime/js/cm-ai/cm-ai-conversation-entry.mjs',import.meta.url),'utf8');
74
+ assert.match(source,/retryDeveloper\(status\)\|\|retryReview\(status\)\?'resume'/);
75
+ });
76
+
77
+ test('the failure code survives redaction instead of collapsing to execution_error', async () => {
78
+ const {failureCode}=await import('../runtime/js/cm-ai/effect-contract.mjs');
79
+ assert.equal(failureCode(Object.assign(new Error('x'),{code:'verification_precheck_failed'})),
80
+ 'verification_precheck_failed');
81
+ });
82
+
83
+ // The serial entry and the parallel batch driver must agree on what is
84
+ // retryable. They used to keep separate code lists; a gate code added to one
85
+ // and not the other would stall every parallel member that hits it.
86
+ test('the batch driver decides retryability from the shared predicate', async () => {
87
+ const {default:fs}=await import('node:fs');
88
+ const {developmentRetryable}=await import('../runtime/js/cm-ai/cm-ai-conversation-entry.mjs');
89
+ const source=fs.readFileSync(new URL('./cm-ai-batch-run.mjs',import.meta.url),'utf8');
90
+ assert.match(source,/import \{developmentRetryable\}/);
91
+ assert.match(source,/\|\|developmentRetryable\(status\)\)await call\('start'\)/);
92
+ assert.equal(/status\.code==='developer_result_invalid'/.test(source),false,
93
+ 'batch driver still carries its own copy of the retryable code list');
94
+ for(const code of ['developer_result_invalid','verification_precheck_failed'])
95
+ assert.equal(developmentRetryable({state:'blocked',code}),true,code);
96
+ assert.equal(developmentRetryable({state:'blocked',code:'package_mismatch'}),false);
97
+ assert.equal(developmentRetryable({state:'unknown',code:'verification_precheck_failed'}),false);
98
+ });
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ // Reports whether the update announcement hook is wired, and — only when the user
3
+ // says yes — adds that one SessionStart hook to their Claude settings.
4
+ //
5
+ // Scope is deliberately narrow. The installer otherwise never touches settings.json,
6
+ // which belongs to the user: it may carry their own statusline and hooks. This adds
7
+ // the announcement hook alone and never the background updater, because announcing a
8
+ // new version is not the same decision as letting the tool replace itself.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import os from 'node:os';
12
+ import {createInterface} from 'node:readline';
13
+
14
+ export const ANNOUNCE_COMMAND='~/.cm-workflow/cm-announce.sh';
15
+ const DECLINED='announce-hook-declined';
16
+
17
+ export const settingsPath=(env=process.env)=>
18
+ path.join(path.resolve(env.CLAUDE_HOME||path.join(env.HOME||os.homedir(),'.claude')),'settings.json');
19
+ export const declinedPath=(env=process.env)=>
20
+ path.join(path.resolve(env.CM_WORKFLOW_HOME||path.join(env.HOME||os.homedir(),'.cm-workflow')),DECLINED);
21
+
22
+ export function readSettings(file){
23
+ let text;
24
+ try{text=fs.readFileSync(file,'utf8');}catch(error){if(error.code==='ENOENT')return {};throw error;}
25
+ if(!text.trim())return {};
26
+ // A settings file we cannot parse is never rewritten: that would destroy user content.
27
+ return JSON.parse(text);
28
+ }
29
+
30
+ export const hasAnnounceHook=settings=>
31
+ (settings?.hooks?.SessionStart??[]).some(group=>
32
+ Array.isArray(group?.hooks)&&group.hooks.some(hook=>hook?.command===ANNOUNCE_COMMAND));
33
+
34
+ // Append to the existing SessionStart list; every other key and hook is preserved.
35
+ export function withAnnounceHook(settings){
36
+ const next=structuredClone(settings??{});
37
+ next.hooks??={};
38
+ const sessionStart=Array.isArray(next.hooks.SessionStart)?[...next.hooks.SessionStart]:[];
39
+ sessionStart.push({hooks:[{type:'command',command:ANNOUNCE_COMMAND,timeout:5}]});
40
+ next.hooks.SessionStart=sessionStart;
41
+ return next;
42
+ }
43
+
44
+ export function writeSettings(file,settings){
45
+ fs.mkdirSync(path.dirname(file),{recursive:true});
46
+ const temporary=`${file}.cm-announce.${process.pid}.tmp`;
47
+ fs.writeFileSync(temporary,JSON.stringify(settings,null,2)+'\n',{mode:0o600});
48
+ try{fs.renameSync(temporary,file);}finally{if(fs.existsSync(temporary))fs.unlinkSync(temporary);}
49
+ }
50
+
51
+ export async function main({env=process.env,input=process.stdin,output=process.stdout,
52
+ interactive=Boolean(process.stdin.isTTY&&process.stdout.isTTY)}={}){
53
+ const file=settingsPath(env);
54
+ let settings;
55
+ try{settings=readSettings(file);}
56
+ catch{output.write(`⚠ 无法解析 ${file},未改动它。更新播报可按 docs/installation.md 手工开启。\n`);return 0;}
57
+ if(hasAnnounceHook(settings)){output.write('更新播报已启用(新版本会在下次启动时告知)。\n');return 0;}
58
+
59
+ const declined=declinedPath(env);
60
+ if(fs.existsSync(declined)){output.write(`更新播报未启用(此前已选择不开启)。要开启:删除 ${declined} 后重新安装。\n`);return 0;}
61
+
62
+ const manual=`要开启:在 ${file} 的 hooks.SessionStart 增加 {"type":"command","command":"${ANNOUNCE_COMMAND}","timeout":5}`;
63
+ if(!interactive){output.write(`更新播报未启用。${manual}\n`);return 0;}
64
+
65
+ const rl=createInterface({input,output,terminal:false});
66
+ let answer;
67
+ try{answer=await new Promise(resolve=>{
68
+ output.write(' 开启更新播报?新版本会在下次启动 Claude Code 时告知一次。这只增加一条播报 hook,不会自动升级。[y/N] ');
69
+ rl.once('line',line=>resolve(line));rl.once('close',()=>resolve(null));
70
+ });}finally{rl.close();}
71
+
72
+ if(!/^y(es)?$/i.test((answer??'').trim())){
73
+ try{fs.mkdirSync(path.dirname(declined),{recursive:true});fs.writeFileSync(declined,'');}catch{/* 记不住也只是下次再问一次 */}
74
+ output.write(` 未开启。${manual}\n`);return 0;
75
+ }
76
+ try{writeSettings(file,withAnnounceHook(settings));}
77
+ catch{output.write(` ⚠ 写入 ${file} 失败,未改动它。${manual}\n`);return 0;}
78
+ output.write(' 已开启:下次启动 Claude Code 时会告知更新。\n');
79
+ return 0;
80
+ }
81
+
82
+ if(process.argv[1]&&fs.realpathSync(process.argv[1])===fs.realpathSync(new URL(import.meta.url).pathname))
83
+ process.exitCode=await main();
@@ -0,0 +1,90 @@
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 {Readable,Writable} from 'node:stream';
7
+ import {main,settingsPath,declinedPath,hasAnnounceHook,withAnnounceHook,ANNOUNCE_COMMAND} from './cm-announce-hook.mjs';
8
+
9
+ function fixture(t,settings){
10
+ const home=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-announce-')));
11
+ t.after(()=>fs.rmSync(home,{recursive:true,force:true}));
12
+ const env={HOME:home,CLAUDE_HOME:path.join(home,'.claude'),CM_WORKFLOW_HOME:path.join(home,'.cm-workflow')};
13
+ if(settings!==undefined){
14
+ fs.mkdirSync(env.CLAUDE_HOME,{recursive:true});
15
+ fs.writeFileSync(settingsPath(env),typeof settings==='string'?settings:JSON.stringify(settings,null,2));
16
+ }
17
+ return {env,read:()=>JSON.parse(fs.readFileSync(settingsPath(env),'utf8'))};
18
+ }
19
+ const run=async(env,answer,interactive=true)=>{
20
+ let text='';
21
+ const output=new Writable({write(chunk,_e,cb){text+=chunk;cb();}});
22
+ await main({env,input:Readable.from(answer===null?[]:[`${answer}\n`]),output,interactive});
23
+ return text;
24
+ };
25
+
26
+ test('an existing hook is reported, never duplicated',async t=>{
27
+ const existing={hooks:{SessionStart:[{hooks:[{type:'command',command:ANNOUNCE_COMMAND,timeout:5}]}]}};
28
+ const f=fixture(t,existing);
29
+ const text=await run(f.env,'y');
30
+ assert.match(text,/已启用/);
31
+ assert.deepEqual(f.read(),existing,'settings must be untouched');
32
+ });
33
+
34
+ test('yes adds only the announcement hook and preserves every other setting',async t=>{
35
+ const original={statusLine:{type:'command',command:'~/.claude/statusline.sh'},
36
+ env:{FOO:'bar'},hooks:{SessionStart:[{hooks:[{type:'command',command:'~/mine.sh'}]}],
37
+ PreToolUse:[{hooks:[{type:'command',command:'~/guard.sh'}]}]}};
38
+ const f=fixture(t,original);
39
+ await run(f.env,'y');
40
+ const after=f.read();
41
+ assert.deepEqual(after.statusLine,original.statusLine,'the user statusline survives');
42
+ assert.deepEqual(after.env,original.env);
43
+ assert.deepEqual(after.hooks.PreToolUse,original.hooks.PreToolUse,'other hook kinds survive');
44
+ assert.deepEqual(after.hooks.SessionStart[0],original.hooks.SessionStart[0],'the existing SessionStart hook survives');
45
+ assert.equal(hasAnnounceHook(after),true);
46
+ assert.equal(after.hooks.SessionStart.length,2);
47
+ // The background updater is a separate decision and must never be added here.
48
+ assert.equal(JSON.stringify(after).includes('cm-update.sh'),false);
49
+ });
50
+
51
+ test('no answer leaves settings alone and is remembered',async t=>{
52
+ const f=fixture(t,{statusLine:{type:'command',command:'~/mine.sh'}});
53
+ const text=await run(f.env,'n');
54
+ assert.equal(hasAnnounceHook(f.read()),false);
55
+ assert.match(text,/未开启/);
56
+ assert.equal(fs.existsSync(declinedPath(f.env)),true);
57
+ const again=await run(f.env,'y');
58
+ assert.match(again,/此前已选择不开启/);
59
+ assert.equal(hasAnnounceHook(f.read()),false,'a remembered refusal is not overridden');
60
+ });
61
+
62
+ test('non-interactive installs never write and print the exact manual step',async t=>{
63
+ const f=fixture(t,{});
64
+ const text=await run(f.env,null,false);
65
+ assert.equal(hasAnnounceHook(f.read()),false);
66
+ assert.match(text,/hooks\.SessionStart/);
67
+ assert.match(text,new RegExp(ANNOUNCE_COMMAND.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')));
68
+ assert.equal(fs.existsSync(declinedPath(f.env)),false,'declining was never asked, so nothing is remembered');
69
+ });
70
+
71
+ test('unparsable settings are reported and left byte-identical',async t=>{
72
+ const broken='{ this is not json';
73
+ const f=fixture(t,broken);
74
+ const text=await run(f.env,'y');
75
+ assert.match(text,/无法解析/);
76
+ assert.equal(fs.readFileSync(settingsPath(f.env),'utf8'),broken);
77
+ });
78
+
79
+ test('a missing settings file is created with just the hook',async t=>{
80
+ const f=fixture(t);
81
+ await run(f.env,'y');
82
+ assert.deepEqual(f.read(),{hooks:{SessionStart:[{hooks:[{type:'command',command:ANNOUNCE_COMMAND,timeout:5}]}]}});
83
+ });
84
+
85
+ test('withAnnounceHook does not mutate its input',()=>{
86
+ const input={hooks:{SessionStart:[]}};
87
+ const snapshot=JSON.stringify(input);
88
+ withAnnounceHook(input);
89
+ assert.equal(JSON.stringify(input),snapshot);
90
+ });
@@ -28,8 +28,9 @@ test('host handoff uses existing gate and binds actual changed bytes',()=>fixtur
28
28
  const handoff=loadHandoff(input.handoffPath,{task:'T-001',attempt:1});
29
29
  assert.deepEqual(handoff.changed_files,['a.mjs']);
30
30
  assert.equal(handoff.implementation_sha256,implementationSha256(input.root,['a.mjs']));
31
+ // Republishing the same bytes is the crash-after-link case: already published.
31
32
  const before=fs.readFileSync(input.handoffPath);
32
- assert.throws(()=>createHostHandoff(input),{code:'EEXIST'});
33
+ assert.equal(createHostHandoff(input).status,'ready_for_review');
33
34
  assert.deepEqual(fs.readFileSync(input.handoffPath),before);
34
35
  }));
35
36
  test('failed host check produces blocked handoff rather than invented success',()=>fixture(input=>{
@@ -56,3 +57,117 @@ test('new host handoff feeds existing Learning writer and verifier',()=>fixture(
56
57
  const evidence=loadHandoff(input.handoffPath).evidence;
57
58
  assert.equal(evidence.filter(x=>x.startsWith('cm-learning-')).length,2);
58
59
  }));
60
+
61
+ // A run that dies before review leaves a handoff behind. Refusing to replace it
62
+ // blocks every later attempt of that task forever, which is what #81 reported.
63
+ // Approval evidence still must never be overwritten, so the receipt decides.
64
+ function collisionFixture(fn){
65
+ const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-handoff-collision-')));
66
+ const root=path.join(temp,'code'),reviews=path.join(temp,'reviews');fs.mkdirSync(root);fs.mkdirSync(reviews);
67
+ fs.writeFileSync(path.join(root,'a.mjs'),'old');fs.writeFileSync(path.join(root,'requirements.md'),'synthetic task');
68
+ const handoffPath=path.join(reviews,'9.demo-T-001-a1-handoff.json');
69
+ const build=body=>{
70
+ fs.writeFileSync(path.join(root,'a.mjs'),'old');
71
+ const baseline=captureReviewBaseline({root,identity:{repositoryId:'test',runId:'run',taskId:'T-001',attempt:1},
72
+ scope:['a.mjs'],requirements:['requirements.md']});
73
+ fs.writeFileSync(path.join(root,'a.mjs'),body);
74
+ return {root,baseline,handoffPath,
75
+ checks:[{id:'unit',command:['node','--test'],outcome:'passed',exitCode:0,evidence:'host fixture check'}]};
76
+ };
77
+ try{fn({reviews,handoffPath,build});}finally{fs.rmSync(temp,{recursive:true,force:true});}
78
+ }
79
+
80
+ test('an unreviewed handoff from a dead run is archived so the retry can publish',()=>collisionFixture(f=>{
81
+ createHostHandoff(f.build('first attempt'));
82
+ const stale=fs.readFileSync(f.handoffPath);
83
+ assert.equal(createHostHandoff(f.build('second attempt')).status,'ready_for_review');
84
+ const republished=fs.readFileSync(f.handoffPath);
85
+ assert.notDeepEqual(republished,stale);
86
+ const archive=path.join(f.reviews,'.superseded');
87
+ const archived=fs.readdirSync(archive);
88
+ assert.equal(archived.length,1);
89
+ assert.match(archived[0],/^9\.demo-T-001-a1-handoff\.json\.[0-9a-f]{16}$/);
90
+ assert.deepEqual(fs.readFileSync(path.join(archive,archived[0])),stale);
91
+ }));
92
+
93
+ test('a handoff the matching receipt names is never replaced',()=>collisionFixture(f=>{
94
+ createHostHandoff(f.build('first attempt'));
95
+ const reviewed=fs.readFileSync(f.handoffPath);
96
+ fs.writeFileSync(path.join(f.reviews,'9.demo-T-001-r1.md'),
97
+ ['---','at: 2026-01-01T00:00:00.000Z','reviewer: claude-cli','independent: true','task: T-001',
98
+ 'attempt: 1','round: 1','verdict: approved','handoff: 9.demo-T-001-a1-handoff.json',
99
+ 'handoff_sha256: '+'0'.repeat(64),'blocking_findings: 0','---',''].join('\n'));
100
+ assert.throws(()=>createHostHandoff(f.build('second attempt')),error=>error.code==='handoff_exists');
101
+ assert.deepEqual(fs.readFileSync(f.handoffPath),reviewed);
102
+ assert.equal(fs.existsSync(path.join(f.reviews,'.superseded')),false);
103
+ }));
104
+
105
+ test('a receipt for another handoff does not protect this one',()=>collisionFixture(f=>{
106
+ createHostHandoff(f.build('first attempt'));
107
+ fs.writeFileSync(path.join(f.reviews,'9.demo-T-001-r1.md'),
108
+ ['---','verdict: approved','handoff: 9.demo-T-002-a1-handoff.json','---',''].join('\n'));
109
+ assert.equal(createHostHandoff(f.build('second attempt')).status,'ready_for_review');
110
+ assert.equal(fs.readdirSync(path.join(f.reviews,'.superseded')).length,1);
111
+ }));
112
+
113
+ // The receipt names the handoff it reviewed inside its front matter, and the
114
+ // scope list after that line is as long as the task's changed file list. Reading
115
+ // a fixed number of lines made the decision depend on field order; a reordering
116
+ // would silently turn reviewed evidence into a supersedable leftover.
117
+ const receipt=(handoffName,scopeLength,{order='handoff-first',terminated=true}={})=>{
118
+ const head=['---','at: 2026-01-01T00:00:00.000Z','reviewer: claude-cli','independent: true',
119
+ 'task: T-001','attempt: 1','round: 1','verdict: approved'];
120
+ const bound=[`handoff: ${handoffName}`,'handoff_sha256: '+'0'.repeat(64),'blocking_findings: 0'];
121
+ const scope=['scope:',...Array.from({length:scopeLength},(_,i)=>` - src/file${i}.mjs`)];
122
+ return [...head,...(order==='handoff-first'?[...bound,...scope]:[...scope,...bound]),
123
+ ...(terminated?['---','','No blocking findings.']:[])].join('\n');
124
+ };
125
+
126
+ test('a reviewed handoff stays protected however long the scope list is',()=>collisionFixture(f=>{
127
+ createHostHandoff(f.build('first attempt'));
128
+ const reviewed=fs.readFileSync(f.handoffPath);
129
+ // 200 scope entries push the handoff line far past any fixed window.
130
+ fs.writeFileSync(path.join(f.reviews,'9.demo-T-001-r1.md'),
131
+ receipt('9.demo-T-001-a1-handoff.json',200));
132
+ assert.throws(()=>createHostHandoff(f.build('second attempt')),error=>error.code==='handoff_exists');
133
+ assert.deepEqual(fs.readFileSync(f.handoffPath),reviewed);
134
+ }));
135
+
136
+ test('a reviewed handoff stays protected if the front matter is reordered',()=>collisionFixture(f=>{
137
+ createHostHandoff(f.build('first attempt'));
138
+ const reviewed=fs.readFileSync(f.handoffPath);
139
+ fs.writeFileSync(path.join(f.reviews,'9.demo-T-001-r1.md'),
140
+ receipt('9.demo-T-001-a1-handoff.json',40,{order:'scope-first'}));
141
+ assert.throws(()=>createHostHandoff(f.build('second attempt')),error=>error.code==='handoff_exists');
142
+ assert.deepEqual(fs.readFileSync(f.handoffPath),reviewed);
143
+ }));
144
+
145
+ test('a receipt that is not recognisable front matter fails closed',()=>collisionFixture(f=>{
146
+ createHostHandoff(f.build('first attempt'));
147
+ const reviewed=fs.readFileSync(f.handoffPath);
148
+ for(const body of [
149
+ receipt('9.demo-T-001-a1-handoff.json',3,{terminated:false}), // 未闭合
150
+ 'no front matter at all\nhandoff: 9.demo-T-001-a1-handoff.json\n', // 没有起始 ---
151
+ ]){
152
+ fs.writeFileSync(path.join(f.reviews,'9.demo-T-001-r1.md'),body);
153
+ assert.throws(()=>createHostHandoff(f.build('second attempt')),error=>error.code==='handoff_exists');
154
+ assert.deepEqual(fs.readFileSync(f.handoffPath),reviewed);
155
+ }
156
+ }));
157
+
158
+ test('a handoff line in the body rather than the front matter does not protect',()=>collisionFixture(f=>{
159
+ // Only the front matter binds a receipt to a handoff; prose must not.
160
+ createHostHandoff(f.build('first attempt'));
161
+ fs.writeFileSync(path.join(f.reviews,'9.demo-T-001-r1.md'),
162
+ ['---','verdict: approved','---','','handoff: 9.demo-T-001-a1-handoff.json'].join('\n'));
163
+ assert.equal(createHostHandoff(f.build('second attempt')).status,'ready_for_review');
164
+ assert.equal(fs.readdirSync(path.join(f.reviews,'.superseded')).length,1);
165
+ }));
166
+
167
+ test('an oversized receipt fails closed instead of being parsed',()=>collisionFixture(f=>{
168
+ createHostHandoff(f.build('first attempt'));
169
+ const reviewed=fs.readFileSync(f.handoffPath);
170
+ fs.writeFileSync(path.join(f.reviews,'9.demo-T-001-r1.md'),'x'.repeat(256*1024+1));
171
+ assert.throws(()=>createHostHandoff(f.build('second attempt')),error=>error.code==='handoff_exists');
172
+ assert.deepEqual(fs.readFileSync(f.handoffPath),reviewed);
173
+ }));
@@ -0,0 +1,82 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import {PassThrough} from 'node:stream';
4
+
5
+ import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
6
+
7
+ // Drives one request through the real JSONL transport and returns both channels.
8
+ async function exchange(request,handle){
9
+ const input=new PassThrough(),output=new PassThrough(),errorOutput=new PassThrough();
10
+ const replies=[],diagnostics=[];
11
+ output.on('data',chunk=>{for(const line of chunk.toString().split('\n'))if(line.trim())replies.push(JSON.parse(line));});
12
+ errorOutput.on('data',chunk=>{for(const line of chunk.toString().split('\n'))if(line.trim())diagnostics.push(JSON.parse(line));});
13
+ const serving=serveCmAiHost({host:{handle},input,output,errorOutput});
14
+ input.write(JSON.stringify(request)+'\n');
15
+ input.end();
16
+ await serving;
17
+ await new Promise(resolve=>setImmediate(resolve));
18
+ return {replies,diagnostics};
19
+ }
20
+
21
+ const failing=code=>()=>{throw Object.assign(new Error(code),{code});};
22
+
23
+ test('the redacted reply is unchanged and the real code goes to stderr', async () => {
24
+ // The peer must keep seeing host_request_failed: which codes may cross that
25
+ // boundary is a deliberate design, not an oversight.
26
+ const {replies,diagnostics}=await exchange({operation:'save_draft',requestId:'r1'},
27
+ failing('prd_review_sections_missing'));
28
+ assert.deepEqual(replies,[{requestId:'r1',error:{code:'host_request_failed'}}]);
29
+ assert.deepEqual(diagnostics,[{diagnostic:'host_request_failed',operation:'save_draft',
30
+ code:'prd_review_sections_missing'}]);
31
+ });
32
+
33
+ test('the failing operation is named so a strict field set can be told apart', async () => {
34
+ const {diagnostics}=await exchange({operation:'final_review_package',requestId:'r2'},
35
+ failing('invalid_input'));
36
+ assert.equal(diagnostics[0].operation,'final_review_package');
37
+ assert.equal(diagnostics[0].code,'invalid_input');
38
+ });
39
+
40
+ test('a success emits no diagnostic', async () => {
41
+ const {replies,diagnostics}=await exchange({operation:'status',requestId:'r3'},
42
+ async()=>({outcome:'reported'}));
43
+ assert.deepEqual(replies,[{requestId:'r3',result:{outcome:'reported'}}]);
44
+ assert.deepEqual(diagnostics,[]);
45
+ });
46
+
47
+ test('an error carrying no code still produces one line', async () => {
48
+ const {replies,diagnostics}=await exchange({operation:'advance',requestId:'r4'},
49
+ ()=>{throw new Error('anonymous failure');});
50
+ assert.deepEqual(replies,[{requestId:'r4',error:{code:'host_request_failed'}}]);
51
+ assert.deepEqual(diagnostics,[{diagnostic:'host_request_failed',operation:'advance',detail:'unavailable'}]);
52
+ });
53
+
54
+ test('the raw message never reaches either channel', async () => {
55
+ // Assembled at runtime so the safety scanner does not see a key-shaped literal.
56
+ const secret=['sk','live','0123456789abcdef'].join('-')+' leaked from provider output';
57
+ const {replies,diagnostics}=await exchange({operation:'advance',requestId:'r5'},
58
+ ()=>{throw Object.assign(new Error(secret),{code:'invalid_input'});});
59
+ const text=JSON.stringify(replies)+JSON.stringify(diagnostics);
60
+ assert.equal(text.includes(['sk','live'].join('-')),false);
61
+ assert.equal(text.includes('leaked'),false);
62
+ });
63
+
64
+ test('a malformed request is rejected without a diagnostic', async () => {
65
+ // invalid_request already says what is wrong; it never reaches host.handle.
66
+ const {replies,diagnostics}=await exchange({operation:'not_an_operation',requestId:'r6'},
67
+ ()=>{throw new Error('unreachable');});
68
+ assert.deepEqual(replies,[{requestId:null,error:{code:'invalid_request'}}]);
69
+ assert.deepEqual(diagnostics,[]);
70
+ });
71
+
72
+ test('a stderr that throws does not change the reply', async () => {
73
+ const input=new PassThrough(),output=new PassThrough();
74
+ const replies=[];
75
+ output.on('data',chunk=>{for(const line of chunk.toString().split('\n'))if(line.trim())replies.push(JSON.parse(line));});
76
+ const errorOutput={write(){throw new Error('stderr is gone');}};
77
+ const serving=serveCmAiHost({host:{handle:failing('invalid_input')},input,output,errorOutput});
78
+ input.write(JSON.stringify({operation:'advance',requestId:'r7'})+'\n');
79
+ input.end();
80
+ await serving;
81
+ assert.deepEqual(replies,[{requestId:'r7',error:{code:'host_request_failed'}}]);
82
+ });
@@ -106,6 +106,16 @@ AGENTS.md 增量写回;将学习结果、文件摘要记入已有交接字段
106
106
  `../../../runtime/task-gates.md`。子代理只能返回候选字段;由主执行者核对并落盘,
107
107
  不得让子代理写 `.reviews/`。`ready_for_review` 必须所有 verification 都是 `passed`,
108
108
  且 blockers/scope_deviation 为空;`changed_files` 使用正斜杠分隔的项目相对路径。
109
+
110
+ **交付前逐条核对任务的 `verification`**:开发请求的 `specification.task.verification`
111
+ 来自 `tasks.md` 的「验证要求」段(由 `runtime/js/cm-ai/specification-material.mjs` 提取)。
112
+ 把它当检查清单,**逐条**写出满足它的证据位置——哪个文件哪一行、哪次命令的哪段输出。
113
+ 有一条对不上就补做,补不了就写 `blocked` 说明缺口,不得交付。要求里写「分别记录
114
+ A、B、C 三种状态」就必须三种都在,写「在 X 路径上走查」就必须是 X 而不是等价替代;
115
+ 用了替身(命令桩、脚本派发事件、非指定服务器)时,在证据里显式标注边界,不要让
116
+ 结论读起来像端到端验证过。这一步不是形式:本仓库实跑统计显示末任务
117
+ (承担 feature 级走查与证据文档的那个)第一轮审查通过率仅 1/5,被打回的 P2 全部是
118
+ 「证据没满足任务里已写明的验证要求」——不是代码缺陷,是本可在此自查掉的遗漏。
109
119
  否则写 `blocked` 并停止,不进入 N4。写 handoff 前,必须以完全相同的
110
120
  `changed_files` 计算实现内容摘要:
111
121