@aibyzero/cm-workflow 0.16.7 → 0.16.9
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 +37 -0
- package/README.md +39 -3
- package/VERSION +1 -1
- package/assets/readme/workflow-recovery-detailed.png +0 -0
- package/assets/readme/workflow-stages-detailed.png +0 -0
- package/compat/claude-commands/cm-notify.md +3 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +61 -4
- package/docs/next-steps.md +8 -2
- package/docs/user-guide.md +204 -0
- package/package.json +2 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
- package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
- package/runtime/js/cm-ai/code-projects.mjs +4 -1
- package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
- package/runtime/js/cm-ai/drive-core.mjs +26 -4
- package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
- package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
- package/runtime/js/cm-ai/effect-contract.mjs +6 -1
- package/runtime/js/cm-ai/execution-store.mjs +4 -2
- package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
- package/runtime/js/cm-ai/host-check.mjs +4 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
- package/runtime/js/cm-ai/host-documentation.mjs +53 -12
- package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
- package/runtime/js/cm-ai/host-session.mjs +47 -7
- package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
- package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
- package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
- package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
- package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
- package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
- package/runtime/js/cm-ai/review-package.mjs +10 -1
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
- package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
- package/runtime/js/cm-ai/task-commit.mjs +39 -0
- package/runtime/js/cm-ai/task-runner.mjs +636 -65
- package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
- package/runtime/js/cm-ai/worker-claude.mjs +10 -3
- package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
- 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 +356 -187
- package/runtime/js/cm-fix/host.mjs +2 -1
- package/runtime/js/cm-fix/investigation.mjs +25 -9
- package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
- package/runtime/js/cm-fix/progress.mjs +15 -3
- package/runtime/js/cm-fix/protected-edits.mjs +10 -3
- package/runtime/js/cm-fix/repair.mjs +11 -3
- package/runtime/js/cm-fix/test-author.mjs +10 -3
- package/runtime/js/cm-idea/session.mjs +67 -4
- package/runtime/js/cm-prd/review-correction.mjs +10 -4
- package/runtime/js/cm-prd/session.mjs +43 -0
- package/runtime/js/cm-refactor/records.mjs +98 -8
- package/runtime/js/cm-refactor/workflow.mjs +79 -9
- package/runtime/js/cm-test/host.mjs +10 -3
- package/runtime/js/cm-test/session.mjs +45 -6
- package/runtime/js/notify-run.mjs +26 -0
- package/runtime/js/notify-safe-read.mjs +49 -0
- package/runtime/js/notify-send.mjs +312 -0
- package/runtime/js/notify.mjs +492 -0
- package/runtime/js/policy-binding-compat.mjs +54 -0
- package/runtime/model-efficiency.md +17 -0
- package/scripts/ci-test-shards.mjs +67 -0
- package/scripts/ci-test-shards.test.mjs +64 -0
- package/scripts/ci-test-weights.json +222 -0
- package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
- package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
- package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
- package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
- package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
- package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
- package/scripts/cm-ai-batch-drive.mjs +55 -10
- package/scripts/cm-ai-batch-drive.test.mjs +65 -0
- package/scripts/cm-ai-batch-host.mjs +132 -13
- package/scripts/cm-ai-batch-host.test.mjs +255 -7
- package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
- package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
- package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
- package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
- package/scripts/cm-ai-batch-run.mjs +189 -22
- package/scripts/cm-ai-batch-run.test.mjs +22 -334
- package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
- package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
- package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
- package/scripts/cm-ai-drive.mjs +68 -23
- package/scripts/cm-ai-drive.test.mjs +37 -2
- package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
- package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
- package/scripts/cm-ai-host-fixture.mjs +268 -0
- package/scripts/cm-ai-host-protected.test.mjs +251 -0
- package/scripts/cm-ai-host.mjs +28 -16
- package/scripts/cm-ai-host.test.mjs +17 -759
- package/scripts/cm-ai-light-modules.test.mjs +57 -0
- package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
- package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
- package/scripts/cm-ai-protected-scope.test.mjs +7 -3
- package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
- package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
- package/scripts/cm-ai-review-failure.test.mjs +124 -13
- package/scripts/cm-ai-review-timeout.test.mjs +188 -10
- package/scripts/cm-ai-run.mjs +15 -6
- package/scripts/cm-ai-supersede.test.mjs +486 -41
- package/scripts/cm-check-drive-files.mjs +8 -0
- package/scripts/cm-check-drive.test.mjs +2 -5
- package/scripts/cm-check-runtime.sh +4 -2
- package/scripts/cm-claude-developer-worker.test.mjs +15 -0
- package/scripts/cm-claude-review-stream.test.mjs +21 -16
- package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
- package/scripts/cm-claude-worker.test.mjs +18 -2
- package/scripts/cm-external-model-recovery.test.mjs +29 -3
- package/scripts/cm-fix-abandon.test.mjs +249 -10
- package/scripts/cm-fix-cause-package.test.mjs +33 -0
- package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
- package/scripts/cm-fix-drive.mjs +34 -8
- package/scripts/cm-fix-host.mjs +8 -7
- package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
- package/scripts/cm-fix-review-budget.test.mjs +13 -0
- package/scripts/cm-fix-review-recovery.test.mjs +35 -0
- package/scripts/cm-host-answer-timeout.test.mjs +65 -0
- package/scripts/cm-host-call-kinds.test.mjs +28 -0
- package/scripts/cm-host-documentation.test.mjs +49 -0
- package/scripts/cm-host-qa-executor.test.mjs +143 -10
- package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
- package/scripts/cm-idea-drive.mjs +49 -11
- package/scripts/cm-idea-drive.test.mjs +66 -0
- package/scripts/cm-idea-host.mjs +106 -16
- package/scripts/cm-init-answer-gaps.test.mjs +258 -0
- package/scripts/cm-init-drive.mjs +41 -7
- package/scripts/cm-init-host.mjs +61 -12
- package/scripts/cm-log-event.mjs +49 -12
- package/scripts/cm-notify-command.test.mjs +900 -0
- package/scripts/cm-notify-read-drift.test.mjs +205 -0
- package/scripts/cm-notify.mjs +469 -0
- package/scripts/cm-notify.test.mjs +685 -0
- package/scripts/cm-patrol.mjs +83 -0
- package/scripts/cm-patrol.test.mjs +161 -0
- package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
- package/scripts/cm-prd-drive.mjs +18 -5
- package/scripts/cm-prd-drive.test.mjs +15 -0
- package/scripts/cm-prd-host.mjs +37 -4
- package/scripts/cm-prd-review-disposition.test.mjs +6 -1
- package/scripts/cm-prd-review-gate.mjs +56 -0
- package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
- package/scripts/cm-refactor-drive.mjs +52 -8
- package/scripts/cm-refactor-drive.test.mjs +44 -0
- package/scripts/cm-refactor-host.test.mjs +10 -6
- package/scripts/cm-release-smoke.sh +2 -0
- package/scripts/cm-test-answer-gaps.test.mjs +151 -0
- package/scripts/cm-test-drive.mjs +21 -5
- package/scripts/cm-token-report.mjs +497 -0
- package/scripts/cm-token-report.test.mjs +346 -0
- package/scripts/fixtures/claude-review-process.mjs +1 -1
- package/scripts/policy-binding-compat.test.mjs +99 -0
- package/scripts/scan-public-safety.py +4 -0
- package/scripts/validate-public-repo.py +4 -0
- package/skills/cm-ai/SKILL.md +7 -3
- 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 +136 -0
- package/skills/cm-ai/references/js-host-recovery.md +311 -0
- package/skills/cm-ai/references/js-host.md +76 -331
- package/skills/cm-check/SKILL.md +3 -3
- package/skills/cm-fix/SKILL.md +2 -0
- package/skills/cm-fix/references/js-host.md +56 -10
- package/skills/cm-idea/references/js-host.md +27 -2
- package/skills/cm-init/references/js-host.md +16 -3
- package/skills/cm-notify/SKILL.md +34 -0
- package/skills/cm-prd/SKILL.md +2 -0
- package/skills/cm-prd/references/js-change-recovery.md +35 -1
- package/skills/cm-refactor/references/js-host.md +17 -0
- package/skills/cm-test/references/js-host.md +14 -1
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// External answer gaps, batch 3 (O13-O15): cm-idea re-asks the interview and the
|
|
2
|
+
// save confirmation under the same pending request, and reconciles an interrupted
|
|
3
|
+
// PRD save against the recorded content digest. Every scenario drives the real host.
|
|
4
|
+
import test from 'node:test';
|
|
5
|
+
import assert from 'node:assert/strict';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import {spawn} from 'node:child_process';
|
|
10
|
+
import {createInterface} from 'node:readline';
|
|
11
|
+
import {once} from 'node:events';
|
|
12
|
+
import {fileURLToPath} from 'node:url';
|
|
13
|
+
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
14
|
+
const draft=maturity=>({status:'draft',content:'# Synthetic '+maturity,maturity,productType:'B',followup:'What should change?'});
|
|
15
|
+
const question={status:'question',question:'Who needs this?',productType:'B'};
|
|
16
|
+
function fixture(t){const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-idea-gaps-')));
|
|
17
|
+
t.after(()=>{try{fs.chmodSync(path.join(dir,'prd'),0o700);}catch{}fs.rmSync(dir,{recursive:true,force:true});});
|
|
18
|
+
return {dir,file:path.join(dir,'interview.json')};}
|
|
19
|
+
async function client(t,{dir,file},respond,{memory=false}={}){
|
|
20
|
+
const child=spawn(process.execPath,[path.join(root,'scripts/cm-idea-host.mjs'),'serve','--skill-dir',path.join(root,'skills/cm-idea'),
|
|
21
|
+
...(memory?[]:['--session-file',file])],{cwd:dir,stdio:['pipe','pipe','pipe']});
|
|
22
|
+
t.after(()=>{if(child.exitCode===null&&!child.killed)child.kill();});
|
|
23
|
+
let sessionId,seq=0,stderr='';const pending=new Map(),closed=once(child,'close'),requests=[];
|
|
24
|
+
let acceptReady,rejectReady;const ready=new Promise((yes,no)=>{acceptReady=yes;rejectReady=no;});
|
|
25
|
+
const send=value=>child.stdin.write(JSON.stringify(value)+'\n');child.stderr.on('data',bytes=>stderr+=bytes);
|
|
26
|
+
createInterface({input:child.stdout}).on('line',line=>{
|
|
27
|
+
const message=JSON.parse(line);
|
|
28
|
+
if(message.type==='host_ready'){sessionId=message.sessionId;acceptReady();}
|
|
29
|
+
else if(message.type==='host_request'){requests.push(message);Promise.resolve().then(()=>respond(message,child)).then(result=>{
|
|
30
|
+
if(result!==undefined)send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,result});
|
|
31
|
+
}).catch(rejectReady);}
|
|
32
|
+
else if(pending.has(message.requestId)){pending.get(message.requestId)(message);pending.delete(message.requestId);}
|
|
33
|
+
});
|
|
34
|
+
child.on('close',code=>{if(!sessionId)rejectReady(Error(stderr));for(const resolve of pending.values())resolve({closed:code});pending.clear();});
|
|
35
|
+
await ready;
|
|
36
|
+
return {child,requests,stderr:()=>stderr,
|
|
37
|
+
// stderr is a separate pipe from the reply on stdout: wait for the diagnostic line instead of racing it.
|
|
38
|
+
stderrMatch:async(pattern,ms=5000)=>{const end=Date.now()+ms;while(!pattern.test(stderr)&&Date.now()<end)await new Promise(r=>setTimeout(r,10));assert.match(stderr,pattern);},request:(operation,fields={})=>new Promise(resolve=>{
|
|
39
|
+
const requestId=`test-${++seq}`;pending.set(requestId,resolve);send({requestId,operation,...fields});}),
|
|
40
|
+
close:async()=>{send({type:'host_close',sessionId});const [code]=await closed;assert.equal(code,0,stderr);}};
|
|
41
|
+
}
|
|
42
|
+
const state=f=>JSON.parse(fs.readFileSync(f.file,'utf8'));
|
|
43
|
+
async function toDraft(t,f){
|
|
44
|
+
const c=await client(t,f,message=>message.payload.messages.length===1?question:draft('L1'));
|
|
45
|
+
await c.request('start',{text:'Synthetic idea'});await c.request('advance',{text:'Developers',maturity:'L1'});
|
|
46
|
+
await c.request('prepare_save',{saveRoot:f.dir});await c.close();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
test('real host: a refused interview reply is discarded and asked again; the third discard is over the limit',{timeout:20000},async t=>{
|
|
50
|
+
const f=fixture(t);let bad=3;
|
|
51
|
+
const respond=()=>bad-->0?{status:'question',question:' ',productType:'B'}:question;
|
|
52
|
+
let c=await client(t,f,respond);assert.ok((await c.request('start',{text:'Synthetic idea'})).error);await c.close();
|
|
53
|
+
for(let round=1;round<=3;round++){
|
|
54
|
+
c=await client(t,f,respond);const status=(await c.request('status')).result;
|
|
55
|
+
assert.equal(status.recovery.call.status,'recorded');assert.match(status.guidance.nextStep,/discard:true/);
|
|
56
|
+
const {callId,requestDigest}=status.recovery.call;
|
|
57
|
+
const result=await c.request('resume',{resolution:{callId,requestDigest,discard:true,evidence:'blank question'}});
|
|
58
|
+
assert.ok(result.error);if(round===3){await c.stderrMatch(/idea_session_abandon_limit/);assert.equal(c.requests.length,0);}
|
|
59
|
+
else{assert.equal(c.requests.length,1);assert.notEqual(c.requests[0].callId,callId);}
|
|
60
|
+
await c.close();
|
|
61
|
+
}
|
|
62
|
+
assert.deepEqual(state(f).abandonedCalls.map(item=>[item.kind,item.reason]),[['idea_interview','answer_rejected'],['idea_interview','answer_rejected']]);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('real host: an unknown interview is abandoned and re-asked; the late original receipt is refused',{timeout:20000},async t=>{
|
|
66
|
+
const f=fixture(t);let original;
|
|
67
|
+
let c=await client(t,f,(message,child)=>{original=message;setImmediate(()=>child.kill('SIGKILL'));});
|
|
68
|
+
await c.request('start',{text:'Synthetic idea'});
|
|
69
|
+
// The re-asked call is lost too, so a call is pending again under a new callId.
|
|
70
|
+
c=await client(t,f,(message,child)=>{setImmediate(()=>child.kill('SIGKILL'));});
|
|
71
|
+
const {callId,requestDigest}=(await c.request('status')).result.recovery.call;
|
|
72
|
+
await c.request('resume',{resolution:{callId,requestDigest,abandon:true,evidence:'session lost it'}});
|
|
73
|
+
c=await client(t,f,()=>question);
|
|
74
|
+
const late={...original.payload.recovery,result:question,evidence:'late original'};
|
|
75
|
+
assert.ok((await c.request('resume',{resolution:late})).error);await c.stderrMatch(/idea_session_call_abandoned/);
|
|
76
|
+
const again=(await c.request('status')).result.recovery.call;assert.notEqual(again.callId,original.payload.recovery.callId);
|
|
77
|
+
const second=await c.request('resume',{resolution:{callId:again.callId,requestDigest:again.requestDigest,abandon:true,evidence:'lost twice'}});
|
|
78
|
+
assert.equal(second.result?.stage,'awaiting_user',c.stderr());await c.close();
|
|
79
|
+
assert.deepEqual(state(f).abandonedCalls.map(item=>item.reason),['answer_missing','answer_missing']);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('real host V7: an invalid save decision asks the current user again, and only then writes',{timeout:20000},async t=>{
|
|
83
|
+
const f=fixture(t);await toDraft(t,f);
|
|
84
|
+
let c=await client(t,f,()=>({decision:'maybe'}));
|
|
85
|
+
assert.ok((await c.request('finish',{filename:'prd-fixture.md'})).error);
|
|
86
|
+
let status=(await c.request('status')).result;assert.equal(status.stage,'save_blocked');assert.equal(status.recovery.call.status,'recorded');
|
|
87
|
+
await c.close();assert.equal(fs.existsSync(path.join(f.dir,'prd')),false);
|
|
88
|
+
const asked=[];
|
|
89
|
+
c=await client(t,f,message=>{asked.push(message);return {decision:'approved'};});
|
|
90
|
+
status=(await c.request('status')).result;const {callId,requestDigest}=status.recovery.call;
|
|
91
|
+
const result=(await c.request('resume',{resolution:{callId,requestDigest,discard:true,evidence:'decision was not approved|rejected'}})).result;
|
|
92
|
+
assert.equal(result.stage,'saved');assert.equal(asked.length,1);assert.equal(asked[0].kind,'idea_confirm_save');
|
|
93
|
+
assert.notEqual(asked[0].callId,callId);await c.close();
|
|
94
|
+
assert.equal(fs.readFileSync(path.join(f.dir,'prd/prd-fixture.md'),'utf8'),'# Synthetic L1');
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('real host: a refused finish (target exists) keeps draft_ready, so another filename can be confirmed',{timeout:20000},async t=>{
|
|
98
|
+
const f=fixture(t);await toDraft(t,f);fs.mkdirSync(path.join(f.dir,'prd'));fs.writeFileSync(path.join(f.dir,'prd/taken.md'),'user file');
|
|
99
|
+
const c=await client(t,f,()=>({decision:'approved'}));
|
|
100
|
+
assert.ok((await c.request('finish',{filename:'taken.md'})).error);assert.equal(c.requests.length,0);
|
|
101
|
+
assert.equal((await c.request('status')).result.recovery,null);
|
|
102
|
+
assert.equal((await c.request('finish',{filename:'other.md'})).result.stage,'saved');await c.close();
|
|
103
|
+
assert.equal(fs.readFileSync(path.join(f.dir,'prd/taken.md'),'utf8'),'user file');
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('real host V6: an interrupted save reconciles absent, matching and conflicting files against the recorded digest',{timeout:30000},async t=>{
|
|
107
|
+
for(const mode of ['absent','matches','conflict']){
|
|
108
|
+
const f=fixture(t);await toDraft(t,f);
|
|
109
|
+
// A read-only prd/ makes the host-owned write fail after the save was approved and recorded.
|
|
110
|
+
fs.mkdirSync(path.join(f.dir,'prd'),{mode:0o500});
|
|
111
|
+
let c=await client(t,f,()=>({decision:'approved'}));
|
|
112
|
+
assert.ok((await c.request('finish',{filename:'prd-fixture.md'})).error);
|
|
113
|
+
let status=(await c.request('status')).result;assert.equal(status.stage,'save_unknown');
|
|
114
|
+
assert.equal(status.recovery.writing,true);assert.equal(status.recovery.expected.length,'# Synthetic L1'.length);
|
|
115
|
+
assert.match(status.guidance.nextStep,/idea_save_recovery_conflict/);await c.close();
|
|
116
|
+
fs.chmodSync(path.join(f.dir,'prd'),0o700);const target=path.join(f.dir,'prd/prd-fixture.md');
|
|
117
|
+
if(mode==='matches')fs.writeFileSync(target,'# Synthetic L1',{mode:0o600});
|
|
118
|
+
if(mode==='conflict')fs.writeFileSync(target,'# Someone else',{mode:0o600});
|
|
119
|
+
c=await client(t,f,()=>assert.fail('the recorded approval is reused, the user is not asked for the same request'));
|
|
120
|
+
const result=await c.request('resume',{resolution:null});
|
|
121
|
+
if(mode==='conflict'){assert.ok(result.error);await c.stderrMatch(/idea_save_recovery_conflict/);
|
|
122
|
+
assert.equal(fs.readFileSync(target,'utf8'),'# Someone else');assert.equal((await c.request('status')).result.recovery.writing,true);}
|
|
123
|
+
else{assert.equal(result.result.stage,'saved',JSON.stringify(result));assert.equal(fs.readFileSync(target,'utf8'),'# Synthetic L1');
|
|
124
|
+
assert.equal(fs.statSync(target).mode&0o777,0o600);
|
|
125
|
+
if(mode==='matches')assert.equal(result.result.saved.source,'recovered_write_readback');
|
|
126
|
+
assert.equal((await c.request('status')).result.recovery,null);}
|
|
127
|
+
await c.close();
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('memory mode: a failed turn is re-sent twice in the same process, then idea_retry_limit',{timeout:20000},async t=>{
|
|
132
|
+
const f=fixture(t);let bad=3;
|
|
133
|
+
const c=await client(t,f,()=>bad-->0?{status:'unknown'}:question,{memory:true});
|
|
134
|
+
assert.ok((await c.request('start',{text:'Synthetic idea'})).error);
|
|
135
|
+
let status=(await c.request('status')).result;assert.equal(status.stage,'failed');assert.equal(status.retry.remaining,2);
|
|
136
|
+
assert.match(status.guidance.nextStep,/--session-file/);
|
|
137
|
+
assert.ok((await c.request('start',{text:'Synthetic idea'})).error);assert.ok((await c.request('start',{text:'Synthetic idea'})).error);
|
|
138
|
+
assert.ok((await c.request('start',{text:'Synthetic idea'})).error);await c.stderrMatch(/idea_retry_limit/);
|
|
139
|
+
status=(await c.request('status')).result;assert.equal(status.retry.remaining,0);
|
|
140
|
+
assert.equal(c.requests.length,3);await c.close();
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test('real host V6: recovery refuses a symlinked prd/ and removes only the host temp link of the verified file',{timeout:30000},async t=>{
|
|
144
|
+
for(const mode of ['symlink','twin']){
|
|
145
|
+
const f=fixture(t);await toDraft(t,f);fs.mkdirSync(path.join(f.dir,'prd'),{mode:0o500});
|
|
146
|
+
let c=await client(t,f,()=>({decision:'approved'}));assert.ok((await c.request('finish',{filename:'prd-fixture.md'})).error);await c.close();
|
|
147
|
+
fs.chmodSync(path.join(f.dir,'prd'),0o700);
|
|
148
|
+
const elsewhere=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-idea-elsewhere-')));t.after(()=>fs.rmSync(elsewhere,{recursive:true,force:true}));
|
|
149
|
+
if(mode==='symlink'){
|
|
150
|
+
// prd/ was replaced by a link to another directory holding a byte-identical file and a same-inode temp name.
|
|
151
|
+
fs.rmdirSync(path.join(f.dir,'prd'));fs.symlinkSync(elsewhere,path.join(f.dir,'prd'));
|
|
152
|
+
fs.writeFileSync(path.join(elsewhere,'prd-fixture.md'),'# Synthetic L1',{mode:0o600});
|
|
153
|
+
fs.linkSync(path.join(elsewhere,'prd-fixture.md'),path.join(elsewhere,'.cm-review-00000000-0000-0000-0000-000000000000'));
|
|
154
|
+
}else{
|
|
155
|
+
const target=path.join(f.dir,'prd/prd-fixture.md');fs.writeFileSync(target,'# Synthetic L1',{mode:0o600});
|
|
156
|
+
fs.linkSync(target,path.join(f.dir,'prd/.cm-review-00000000-0000-0000-0000-000000000000'));
|
|
157
|
+
}
|
|
158
|
+
c=await client(t,f,()=>assert.fail('no call'));const result=await c.request('resume',{resolution:null});await c.close();
|
|
159
|
+
if(mode==='symlink'){assert.ok(result.error);await c.stderrMatch(/idea_save_recovery_conflict/);
|
|
160
|
+
assert.deepEqual(fs.readdirSync(elsewhere).sort(),['.cm-review-00000000-0000-0000-0000-000000000000','prd-fixture.md']);}
|
|
161
|
+
else{assert.equal(result.result.stage,'saved');assert.deepEqual(fs.readdirSync(path.join(f.dir,'prd')),['prd-fixture.md']);
|
|
162
|
+
assert.equal(fs.statSync(path.join(f.dir,'prd/prd-fixture.md')).nlink,1);}
|
|
163
|
+
}
|
|
164
|
+
});
|
|
@@ -10,7 +10,7 @@ import fs from 'node:fs';
|
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import {fileURLToPath} from 'node:url';
|
|
12
12
|
import {inspectCmIdeaAdmission} from './cm-idea-entry.mjs';
|
|
13
|
-
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
13
|
+
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,deliberatelyUnanswered} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
14
14
|
|
|
15
15
|
const HOST=fileURLToPath(new URL('./cm-idea-host.mjs',import.meta.url));
|
|
16
16
|
const KNOWN=new Set(['start','advance','status','cancel','prepare_save','finish','resume']);
|
|
@@ -19,7 +19,7 @@ const obj=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
|
19
19
|
function valid(ok,label){if(!ok)stop(2,`答案格式错误:${label}`);}
|
|
20
20
|
function main(){
|
|
21
21
|
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
22
|
-
process.stdout.write('用法: cm-idea-drive.mjs --plan PLAN.json <operation>\nPLAN: project, sessionFile, mode:create|resume, text/maturity, answers;finish 需 saveRoot、filename
|
|
22
|
+
process.stdout.write('用法: cm-idea-drive.mjs --plan PLAN.json <operation>\nPLAN: project, sessionFile, mode:create|resume, text/maturity, answers;finish 需 saveRoot、filename 和当前用户的确认答案。宿主负责真实保存与回读。resume 的 resolution 可为 null、原回执,或 {callId,requestDigest,discard|abandon:true,evidence} 作废后重问。\n');return;
|
|
23
23
|
}
|
|
24
24
|
const {plan,operation,base}=loadPlanFile({name:'cm-idea-drive.mjs',known:KNOWN});
|
|
25
25
|
requireFields(plan,['project','sessionFile','mode']);
|
|
@@ -38,13 +38,36 @@ function main(){
|
|
|
38
38
|
if(state?.pending&&operation!=='resume')stop(2,'恢复存档存在 pending;必须用 resume 和原调用回执,不能重派');
|
|
39
39
|
const stage=state?.checkpoint?.stage??'ready';
|
|
40
40
|
if(operation==='status'&&plan.mode!=='resume')stop(2,'status 需要已有会话');
|
|
41
|
+
let boundDecision=null;
|
|
41
42
|
if(operation==='resume'){
|
|
42
43
|
if(plan.mode!=='resume')stop(2,'resume 需要已有存档');
|
|
43
|
-
if(state.pending?.writing)stop(2,'
|
|
44
|
+
if(state.pending?.writing&&!state.pending.expected)stop(2,'保存结果未知(旧版会话没有记下应写内容的摘要),不能自动恢复;人工核对 prd/ 下目标文件');
|
|
44
45
|
const call=state.pending?.call,resolution=plan.resolution??null;
|
|
45
|
-
|
|
46
|
+
const reask=obj(resolution)&&(resolution.discard===true||resolution.abandon===true);
|
|
47
|
+
if(state.pending?.writing)valid(resolution===null,'保存中断的恢复只接受 resolution:null(宿主按记下的摘要比对磁盘)');
|
|
48
|
+
else if(reask){
|
|
49
|
+
valid(call&&resolution.callId===call.callId&&resolution.requestDigest===call.requestDigest&&nonempty(resolution.evidence)
|
|
50
|
+
&&!Object.hasOwn(resolution,'result')&&(resolution.discard===true)!==(resolution.abandon===true)
|
|
51
|
+
&&(resolution.discard===true?Object.hasOwn(call,'result'):!Object.hasOwn(call,'result'))
|
|
52
|
+
&&Object.keys(resolution).every(key=>['callId','requestDigest','discard','abandon','evidence'].includes(key)),
|
|
53
|
+
'resume 作废需要 {callId,requestDigest,discard:true|abandon:true,evidence}:discard 只针对已记录被拒的应答,abandon 只针对结果未知的调用');
|
|
54
|
+
if((state.abandonedCalls??[]).filter(item=>item.kind===call.kind).length>=2)
|
|
55
|
+
stop(2,`${call.kind} 本会话已作废 2 次,宿主会报 idea_session_abandon_limit;交人处理`);
|
|
56
|
+
}else if(call&&!Object.hasOwn(call,'result')&&call.kind==='idea_confirm_save'&&resolution===null){
|
|
57
|
+
// V7: a registered, unanswered confirmation takes only the current user's
|
|
58
|
+
// decision bound to this exact callId and request digest; never a stale file.
|
|
59
|
+
const file=path.join(plan.answers?path.resolve(base,plan.answers):base,'confirm-save-reask.json');
|
|
60
|
+
const expected=`{"callId":"${call.callId}","requestDigest":"${call.requestDigest}","decision":"approved|rejected"}`;
|
|
61
|
+
const value=readJson(file,'idea_confirm_save');
|
|
62
|
+
if(value===undefined)stop(2,`confirm_reask_decision_required:保存确认已由宿主登记(callId ${call.callId}、requestDigest ${call.requestDigest})、尚未作答;请当前用户核对后写 ${file}:${expected},再 resume;旧的确认文件不会沿用`);
|
|
63
|
+
if(!obj(value)||value.callId!==call.callId||value.requestDigest!==call.requestDigest)
|
|
64
|
+
stop(2,`confirm_reask_decision_stale:${file} 绑定的是 callId ${obj(value)?value.callId:'无效内容'},不是当前登记的 ${call.callId}(requestDigest ${call.requestDigest});不会使用,请按 ${expected} 重写`);
|
|
65
|
+
valid(Object.keys(value).sort().join(',')==='callId,decision,requestDigest'&&['approved','rejected'].includes(value.decision),`${file} 须为 ${expected}`);
|
|
66
|
+
boundDecision={callId:call.callId,requestDigest:call.requestDigest,result:{decision:value.decision},
|
|
67
|
+
evidence:`当前用户对已登记确认 ${call.callId} 的新决定(confirm-save-reask.json)`};
|
|
68
|
+
}else if(call&&!Object.hasOwn(call,'result'))valid(obj(resolution)&&resolution.callId===call.callId
|
|
46
69
|
&&resolution.requestDigest===call.requestDigest&&nonempty(resolution.evidence)
|
|
47
|
-
&&Object.hasOwn(resolution,'result'),'resume
|
|
70
|
+
&&Object.hasOwn(resolution,'result'),'resume 缺少原调用的真实回执;找不到时可用 abandon:true 作废后重问');
|
|
48
71
|
else valid(resolution===null,'resume 不应提供新回执');
|
|
49
72
|
}
|
|
50
73
|
const actualOp=operation==='resume'?(state.pending?.request?.operation??'status'):operation;
|
|
@@ -57,20 +80,28 @@ function main(){
|
|
|
57
80
|
if(saveRoot!==null)valid(fs.existsSync(saveRoot)&&fs.realpathSync(saveRoot)===saveRoot
|
|
58
81
|
&&fs.statSync(saveRoot).isDirectory(),'saveRoot');
|
|
59
82
|
if(actualOp==='prepare_save')valid(stage==='draft_ready'&&saveRoot!==null,'prepare_save 缺少 saveRoot 或草稿');
|
|
83
|
+
// resume 重放的 finish 用原请求的 filename;保存中断时目标可能已存在,由宿主按摘要对账。
|
|
84
|
+
const filename=operation==='resume'?state.pending?.request?.filename:plan.filename;
|
|
85
|
+
const reconciling=operation==='resume'&&state.pending?.writing===true;
|
|
60
86
|
if(actualOp==='finish'){
|
|
61
|
-
valid(
|
|
87
|
+
valid(['draft_ready','save_blocked'].includes(stage)&&nonempty(filename)&&/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/.test(filename),
|
|
62
88
|
'finish 缺少草稿或安全的 filename');
|
|
63
89
|
const root=saveRoot??state?.checkpoint?.saveRoot;
|
|
64
90
|
valid(nonempty(root),'finish 缺少 saveRoot');
|
|
65
91
|
valid(state?.checkpoint?.saveRoot===null||state?.checkpoint?.saveRoot===root,'finish saveRoot 与已绑定会话不符');
|
|
66
|
-
const directory=path.join(root,'prd'),target=path.join(directory,
|
|
92
|
+
const directory=path.join(root,'prd'),target=path.join(directory,filename);
|
|
67
93
|
valid(!fs.existsSync(directory)||fs.lstatSync(directory).isDirectory()&&!fs.lstatSync(directory).isSymbolicLink(),
|
|
68
94
|
'finish 保存目录越界');
|
|
69
|
-
valid(!fs.existsSync(target),'finish 目标文件已存在');
|
|
95
|
+
if(!reconciling)valid(!fs.existsSync(target),'finish 目标文件已存在');
|
|
70
96
|
}
|
|
71
97
|
const kind=['start','advance'].includes(actualOp)?'idea_interview':actualOp==='finish'?'idea_confirm_save':null;
|
|
98
|
+
// V7: the driver never pre-answers a save confirmation asked during resume (a
|
|
99
|
+
// re-ask after an abandon, or a call re-issued after a crash): the host registers
|
|
100
|
+
// it first, the driver stops naming the new callId and request digest, and the
|
|
101
|
+
// next resume takes only a decision bound to that call (boundDecision above).
|
|
102
|
+
const reasking=operation==='resume';
|
|
72
103
|
const answers=plan.answers?path.resolve(base,plan.answers):null;
|
|
73
|
-
const answer=preflightAnswers(kind?[kind]:[],key=>{
|
|
104
|
+
const answer=preflightAnswers(kind&&!(reasking&&kind==='idea_confirm_save')?[kind]:[],key=>{
|
|
74
105
|
const file=path.join(answers??base,key==='idea_interview'?'interview.json':'confirm-save.json');
|
|
75
106
|
const value=readJson(file,key);
|
|
76
107
|
if(value===undefined)stop(2,`步骤 ${operation} 会反问 ${key},但答案文件不存在: ${file}`);
|
|
@@ -93,7 +124,14 @@ function main(){
|
|
|
93
124
|
...(operation==='advance'?{maturity:plan.maturity}:{}),
|
|
94
125
|
...(operation==='finish'?{filename:plan.filename}:{}),
|
|
95
126
|
...(operation==='prepare_save'?{saveRoot}:{}),
|
|
96
|
-
...(operation==='resume'?{resolution:plan.resolution??null}:{})},answers:answer,
|
|
97
|
-
answerFor:row=>
|
|
127
|
+
...(operation==='resume'?{resolution:boundDecision??plan.resolution??null}:{})},answers:answer,
|
|
128
|
+
answerFor:row=>{
|
|
129
|
+
if(row.kind==='idea_confirm_save'&&reasking){
|
|
130
|
+
const recovery=row.payload?.recovery??{};
|
|
131
|
+
throw deliberatelyUnanswered(`confirm_reask_decision_required:宿主已登记新的保存确认(callId ${recovery.callId}、requestDigest ${recovery.requestDigest}),驾驶员不预先作答;`
|
|
132
|
+
+`请当前用户核对后写 ${path.join(answers??base,'confirm-save-reask.json')}:{"callId":"${recovery.callId}","requestDigest":"${recovery.requestDigest}","decision":"approved|rejected"},再 resume;旧的确认文件与绑定其他调用的决定都不会使用`);
|
|
133
|
+
}
|
|
134
|
+
return answer[row.kind]??null;
|
|
135
|
+
}});
|
|
98
136
|
}
|
|
99
137
|
main();
|
|
@@ -48,3 +48,69 @@ test('missing save decision and resume session binding refuse before launch',t=>
|
|
|
48
48
|
run=f.drive(f.plan({sessionFile:undefined}),'finish');assert.equal(run.status,2);assert.match(run.stderr,/sessionFile/);
|
|
49
49
|
assert.deepEqual(fs.readFileSync(f.sessionFile),before);
|
|
50
50
|
});
|
|
51
|
+
|
|
52
|
+
// V7 blocker: a re-asked save confirmation is never answered from the earlier
|
|
53
|
+
// confirm-save.json; it needs a new decision that names the abandoned callId.
|
|
54
|
+
import {spawn} from 'node:child_process';
|
|
55
|
+
import {createInterface} from 'node:readline';
|
|
56
|
+
async function loseConfirmation(f){
|
|
57
|
+
const child=spawn(process.execPath,[path.join(root,'scripts/cm-idea-host.mjs'),'serve','--skill-dir',path.join(root,'skills/cm-idea'),
|
|
58
|
+
'--session-file',f.sessionFile,'--save-root',f.project],{cwd:f.project,stdio:['pipe','pipe','pipe']});
|
|
59
|
+
const closed=new Promise(resolve=>child.on('close',resolve));
|
|
60
|
+
createInterface({input:child.stdout}).on('line',line=>{const message=JSON.parse(line);
|
|
61
|
+
if(message.type==='host_ready')child.stdin.write(JSON.stringify({requestId:'f',operation:'finish',filename:'fixture.md'})+'\n');
|
|
62
|
+
if(message.type==='host_request')child.kill('SIGKILL');});
|
|
63
|
+
await closed;return JSON.parse(fs.readFileSync(f.sessionFile,'utf8')).pending.call;
|
|
64
|
+
}
|
|
65
|
+
const reaskFile=f=>path.join(f.answers,'confirm-save-reask.json');
|
|
66
|
+
const pendingCall=f=>JSON.parse(fs.readFileSync(f.sessionFile,'utf8')).pending?.call??null;
|
|
67
|
+
// After the stop: only a decision bound to the newly registered call is used.
|
|
68
|
+
function answerRegistered(f,old){
|
|
69
|
+
const call=pendingCall(f);assert.equal(call.kind,'idea_confirm_save');assert.equal(Object.hasOwn(call,'result'),false);
|
|
70
|
+
if(old)assert.notEqual(call.callId,old.callId);
|
|
71
|
+
// A decision bound to the old call (if any) is refused as stale, then removed.
|
|
72
|
+
if(fs.existsSync(reaskFile(f))){const stale=f.drive(f.plan({resolution:null}),'resume');assert.equal(stale.status,2);
|
|
73
|
+
assert.match(stale.stderr,/confirm_reask_decision_stale/);fs.rmSync(reaskFile(f));}
|
|
74
|
+
let run=f.drive(f.plan({resolution:null}),'resume');assert.equal(run.status,2);assert.match(run.stderr,/confirm_reask_decision_required/);
|
|
75
|
+
assert.match(run.stderr,new RegExp(call.callId));
|
|
76
|
+
// The earlier confirm-save.json style, and a decision bound to another call, are refused.
|
|
77
|
+
for(const stale of [{decision:'approved'},{decision:'approved',replaces:old?.callId??'x'},
|
|
78
|
+
{callId:old?.callId??'other',requestDigest:call.requestDigest,decision:'approved'},{callId:call.callId,requestDigest:'0'.repeat(64),decision:'approved'}]){
|
|
79
|
+
fs.writeFileSync(reaskFile(f),JSON.stringify(stale));
|
|
80
|
+
run=f.drive(f.plan({resolution:null}),'resume');assert.equal(run.status,2);assert.match(run.stderr,/confirm_reask_decision_stale/);
|
|
81
|
+
assert.equal(Object.hasOwn(pendingCall(f),'result'),false);
|
|
82
|
+
}
|
|
83
|
+
fs.writeFileSync(reaskFile(f),JSON.stringify({callId:call.callId,requestDigest:call.requestDigest,decision:'rejected'}));
|
|
84
|
+
run=f.drive(f.plan({resolution:null}),'resume');assert.equal(run.status,0,run.stderr);
|
|
85
|
+
assert.equal(JSON.parse(run.stdout).result.saveDecision,'rejected');assert.equal(fs.existsSync(path.join(f.project,'prd/fixture.md')),false);
|
|
86
|
+
}
|
|
87
|
+
test('re-asked save confirmation: the host registers the new call, the driver stops, only a decision bound to it is used',async t=>{
|
|
88
|
+
const f=fixture(t);assert.equal(f.drive(f.plan()).status,0);
|
|
89
|
+
const call=await loseConfirmation(f);assert.equal(call.kind,'idea_confirm_save');
|
|
90
|
+
const resolution={callId:call.callId,requestDigest:call.requestDigest,abandon:true,evidence:'confirmation lost'};
|
|
91
|
+
// confirm-save.json says approved; the driver must not answer the re-ask with it.
|
|
92
|
+
const run=f.drive(f.plan({resolution}),'resume');
|
|
93
|
+
assert.equal(run.status,2);assert.match(run.stderr,/confirm_reask_decision_required/);
|
|
94
|
+
assert.equal(fs.existsSync(path.join(f.project,'prd')),false);
|
|
95
|
+
answerRegistered(f,call);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// Round-2 blocker: the host recorded the abandon (pending.call cleared) and exited
|
|
99
|
+
// before registering the re-asked call. A plain resume reads the re-ask from the
|
|
100
|
+
// persisted abandon history and still needs the fresh decision.
|
|
101
|
+
test('crash after the abandon was recorded: the re-issued call is registered first and answered only from a bound decision',async t=>{
|
|
102
|
+
const f=fixture(t);assert.equal(f.drive(f.plan()).status,0);
|
|
103
|
+
const call=await loseConfirmation(f);assert.equal(call.kind,'idea_confirm_save');
|
|
104
|
+
const state=JSON.parse(fs.readFileSync(f.sessionFile,'utf8'));
|
|
105
|
+
const {createHash}=await import('node:crypto');const evidence='confirmation lost';
|
|
106
|
+
state.abandonedCalls=[{kind:call.kind,callId:call.callId,requestDigest:call.requestDigest,operation:state.pending.request.operation,
|
|
107
|
+
reason:'answer_missing',resultDigest:null,evidence:{sha256:createHash('sha256').update(JSON.stringify(evidence)).digest('hex'),length:evidence.length},
|
|
108
|
+
at:new Date().toISOString()}];
|
|
109
|
+
state.pending={...state.pending,call:null};fs.writeFileSync(f.sessionFile,JSON.stringify(state),{mode:0o600});
|
|
110
|
+
// A decision bound to the abandoned call is already on disk: it must not be used.
|
|
111
|
+
fs.writeFileSync(reaskFile(f),JSON.stringify({callId:call.callId,requestDigest:call.requestDigest,decision:'approved'}));
|
|
112
|
+
const run=f.drive(f.plan({resolution:null}),'resume');
|
|
113
|
+
assert.equal(run.status,2,run.stdout);assert.match(run.stderr,/confirm_reask_decision_required/);
|
|
114
|
+
assert.equal(fs.existsSync(path.join(f.project,'prd')),false);
|
|
115
|
+
answerRegistered(f,call);
|
|
116
|
+
});
|
package/scripts/cm-idea-host.mjs
CHANGED
|
@@ -8,7 +8,30 @@ import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
|
|
|
8
8
|
import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
|
|
9
9
|
import {need,shape,json,digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
10
10
|
import {writeReviewEvidence} from '../runtime/js/cm-ai/review-evidence-file.mjs';
|
|
11
|
-
import {openIdeaSession} from '../runtime/js/cm-idea/session.mjs';
|
|
11
|
+
import {openIdeaSession,MAX_CALL_ABANDONS} from '../runtime/js/cm-idea/session.mjs';
|
|
12
|
+
import {createHash} from 'node:crypto';
|
|
13
|
+
|
|
14
|
+
// Chinese next steps for a blocked conversation (R4). Presentation only.
|
|
15
|
+
export function ideaRecoveryGuidance({pending,abandoned,stage,retry}){
|
|
16
|
+
const used=kind=>abandoned.filter(item=>item.kind===kind).length;
|
|
17
|
+
if(pending?.writing)return pending.expected
|
|
18
|
+
?{summary:'保存 PRD 时宿主中途退出,已记下应写入的内容摘要。',nextStep:'resume {resolution:null}:文件与已批准草稿一致就记为已保存;文件不存在就按原批准重新写;内容不一致报 idea_save_recovery_conflict,交人核对,不覆盖。',authorizationGranted:false}
|
|
19
|
+
:{summary:'旧版会话在保存中途中断,没有记录应写入内容的摘要。',nextStep:'人工核对 prd/ 下目标文件后决定,宿主不覆盖也不推断;新保存会自动记录摘要。',authorizationGranted:false};
|
|
20
|
+
const call=pending?.call;
|
|
21
|
+
if(call){
|
|
22
|
+
const left=MAX_CALL_ABANDONS-used(call.kind),person=call.kind==='idea_confirm_save';
|
|
23
|
+
if(call.status==='unknown')return {summary:`${call.kind} 的应答没有拿到(超时、断开或宿主退出)。`,
|
|
24
|
+
nextStep:`有原回执就 resume 交回;没有就 resume {resolution:{callId,requestDigest,abandon:true,evidence}} 作废后${person?'重新问当前用户':'重问'}(本会话 ${call.kind} 还可 ${left} 次)。迟到的旧答复一律不用。`,authorizationGranted:false};
|
|
25
|
+
return {summary:`${call.kind} 的应答已记录。`,
|
|
26
|
+
nextStep:`resume {resolution:null} 消费原结果;若宿主拒收(stderr diagnostic 的码),用 {callId,requestDigest,discard:true,evidence} 作废后${person?'重新问当前用户':'重问'}(还可 ${left} 次)。`,authorizationGranted:false};
|
|
27
|
+
}
|
|
28
|
+
if(stage==='failed'&&retry)return {summary:'上一轮访谈没有拿到合格应答(超时、校验不过或断开)。',
|
|
29
|
+
nextStep:retry.remaining>0?`再发一次同样的 ${retry.operation}(同一 text/maturity)重问,还可 ${retry.remaining} 次。内存模式下宿主退出就只能从头开始,需要可恢复请改用 --session-file。`
|
|
30
|
+
:'本进程重问次数已用完(idea_retry_limit);交人处理,或改用 --session-file 重新开始。',authorizationGranted:false};
|
|
31
|
+
if(stage==='save_blocked')return {summary:'这次保存没有写入(决定无效、取消前失败或目标已存在)。',
|
|
32
|
+
nextStep:'核对原因后再发 finish,宿主会重新问当前用户;目标已存在时换一个 filename。',authorizationGranted:false};
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
12
35
|
|
|
13
36
|
export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
|
|
14
37
|
let bridge,session;
|
|
@@ -17,6 +40,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
17
40
|
output.write('Optional --session-file ABSOLUTE_PRIVATE_JSON enables private recovery records (questions, answers, draft, maturity, pending call). Its parent must exist; existing files must be a matching CM idea session with mode 0600. Reopen with the same file and working directory, inspect status, then advance or resume {requestId,operation,resolution:null|{callId,requestDigest,result,evidence}}. Only actual original host results resolve unknown calls; never redispatch. Explicit cancel is terminal. An interrupted PRD write remains manual reconciliation, never overwrite or infer ownership from matching bytes. This option does not authorize PRD saving.\n');
|
|
18
41
|
output.write('In a default interview, prepare_save {requestId,operation,saveRoot} binds the canonical Git root/cwd when the user later wants to save. Only draft_ready accepts it; the root cannot be changed. It does not write or approve saving. finish still asks the current user through idea_confirm_save.\n');
|
|
19
42
|
output.write('Optional --save-root ABSOLUTE_ROOT enables finish {requestId,operation,filename} in draft_ready. Host first selects the Git root (or cwd without Git) per the interview reference. Save is restricted to ROOT/prd/<ASCII .md filename>. idea_confirm_save must convey the current user decision on exact path/content; nothing is written before approval. Existing files are never overwritten, conflicts stop, unknown write outcomes are not retried. saved is not task completion.\n');
|
|
43
|
+
output.write('Recovery (V1/V6/V7): resume {resolution:{callId,requestDigest,discard:true,evidence}} discards a recorded answer the host refused; {callId,requestDigest,abandon:true,evidence} abandons an unknown idea_interview/idea_confirm_save; both ask again under the same pending request with a fresh callId (a confirmation asks the current user again), keep append-only abandonedCalls and allow 2 per kind per session. An interrupted save records the expected content digest; resume compares disk: equal -> saved, absent -> rewrite under the recorded approval, different -> idea_save_recovery_conflict for a person. Without --session-file, a failed turn may be re-sent twice in the same process; a dead memory-only host starts over.\n');
|
|
20
44
|
output.write('cm-idea-host.mjs serve --skill-dir PATH [--session-file ABSOLUTE_PRIVATE_JSON] [--save-root ABSOLUTE_ROOT]\nstart {requestId,operation,text}; advance {requestId,operation,text,maturity} after a question or draft. maturity is L1/L2/L3, first draft must be L1. Current host handles idea_interview using the authoritative interview reference. status/cancel/host_close use the shared JSONL protocol. No provider, cm-prd or development authority. Saving requires --save-root or prepare_save, plus current confirmation; without --session-file interview remains memory-only.\n');return 0;
|
|
21
45
|
}
|
|
22
46
|
need(argv[0]==='serve','invalid_arguments');const options={};
|
|
@@ -28,7 +52,7 @@ output.write('cm-idea-host.mjs serve --skill-dir PATH [--session-file ABSOLUTE_P
|
|
|
28
52
|
const admission=inspectCmIdeaAdmission({skillDir:options['--skill-dir']});
|
|
29
53
|
need(fileURLToPath(import.meta.url)===path.join(admission.workflowRoot,'scripts/cm-idea-host.mjs'),'entry_path_invalid');
|
|
30
54
|
bridge=createHostToolBridge();const controller=new AbortController();
|
|
31
|
-
let stage='ready',draft=null,lastReply=null,saved=null;const transcript=[];
|
|
55
|
+
let stage='ready',draft=null,lastReply=null,saved=null,failedTurn=null;const transcript=[],retries={};
|
|
32
56
|
const snapshot=()=>json({stage,draft,lastReply,saved,saveRoot,transcript});
|
|
33
57
|
const restore=value=>{if(value===null)return;
|
|
34
58
|
({stage,draft,lastReply,saved,saveRoot}=value);transcript.splice(0,transcript.length,...value.transcript);};
|
|
@@ -43,11 +67,24 @@ output.write('cm-idea-host.mjs serve --skill-dir PATH [--session-file ABSOLUTE_P
|
|
|
43
67
|
}
|
|
44
68
|
const call=(kind,payload,signal)=>session?session.call(kind,payload,signal,(body,sig)=>bridge.call(kind,body,sig)):bridge.call(kind,payload,signal);
|
|
45
69
|
const nonempty=value=>typeof value==='string'&&value.trim().length>0;
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
70
|
+
// Shared by a normal save and its recovery: the bound root must still be
|
|
71
|
+
// canonical; prd/ may be absent, otherwise a real canonical directory.
|
|
72
|
+
const checkSaveLocation=(directory,code=null)=>{
|
|
73
|
+
need(fs.realpathSync(saveRoot)===saveRoot,code??'idea_save_root_invalid');
|
|
74
|
+
try{need(fs.lstatSync(directory).isDirectory()&&!fs.lstatSync(directory).isSymbolicLink()
|
|
75
|
+
&&fs.realpathSync(directory)===directory,code??'idea_save_path_invalid');}catch(cause){if(cause.code!=='ENOENT')throw cause;}
|
|
76
|
+
};
|
|
77
|
+
const retryInfo=()=>failedTurn&&!session?{operation:failedTurn.operation,remaining:MAX_CALL_ABANDONS-(retries.idea_interview??0)}:null;
|
|
78
|
+
const status=()=>{
|
|
79
|
+
const recovery=session?.state.pending?{operation:session.state.pending.request.operation,
|
|
80
|
+
writing:session.state.pending.writing,...(session.state.pending.expected?{expected:session.state.pending.expected}:{}),
|
|
81
|
+
call:session.state.pending.call===null?null:{kind:session.state.pending.call.kind,
|
|
49
82
|
callId:session.state.pending.call.callId,requestDigest:session.state.pending.call.requestDigest,
|
|
50
|
-
status:Object.hasOwn(session.state.pending.call,'result')?'recorded':'unknown'}}:null
|
|
83
|
+
status:Object.hasOwn(session.state.pending.call,'result')?'recorded':'unknown'}}:null;
|
|
84
|
+
const guidance=ideaRecoveryGuidance({pending:recovery,abandoned:session?.abandonedCalls??[],stage,retry:retryInfo()});
|
|
85
|
+
return {stage,draft,lastReply,saved,saveRoot,turns:transcript.length/2,writeAuthorized:false,completionAuthorized:false,
|
|
86
|
+
sessionFile:options['--session-file']??null,recovery,...(retryInfo()?{retry:retryInfo()}:{}),...(guidance?{guidance}:{})};
|
|
87
|
+
};
|
|
51
88
|
const handle=async raw=>{
|
|
52
89
|
const request=json(raw);need(['start','advance','status','cancel','finish','prepare_save'].includes(request.operation),'host_operation_invalid');
|
|
53
90
|
shape(request,['requestId','operation',...(request.operation==='start'?['text']:request.operation==='advance'?['text','maturity']:request.operation==='finish'?['filename']:request.operation==='prepare_save'?['saveRoot']:[])]);
|
|
@@ -61,13 +98,12 @@ output.write('cm-idea-host.mjs serve --skill-dir PATH [--session-file ABSOLUTE_P
|
|
|
61
98
|
return {stage,saveRoot,writeAuthorized:false,confirmationRequired:true};
|
|
62
99
|
}
|
|
63
100
|
if(request.operation==='finish'){
|
|
64
|
-
|
|
101
|
+
// V7: after save_blocked (nothing written) finish asks the current user again.
|
|
102
|
+
need(['draft_ready','save_blocked'].includes(stage)&&draft!==null&&saveRoot!==null,'idea_save_not_authorized');
|
|
65
103
|
need(typeof request.filename==='string'&&/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/.test(request.filename),'idea_filename_invalid');
|
|
66
104
|
const directory=path.join(saveRoot,'prd'),target=path.join(directory,request.filename);
|
|
67
105
|
const check=()=>{
|
|
68
|
-
|
|
69
|
-
try{need(fs.lstatSync(directory).isDirectory()&&!fs.lstatSync(directory).isSymbolicLink()
|
|
70
|
-
&&fs.realpathSync(directory)===directory,'idea_save_path_invalid');}catch(cause){if(cause.code!=='ENOENT')throw cause;}
|
|
106
|
+
checkSaveLocation(directory);
|
|
71
107
|
let exists=true;try{fs.lstatSync(target);}catch(cause){if(cause.code==='ENOENT')exists=false;else throw cause;}
|
|
72
108
|
need(!exists,'idea_save_conflict');
|
|
73
109
|
};
|
|
@@ -79,22 +115,31 @@ output.write('cm-idea-host.mjs serve --skill-dir PATH [--session-file ABSOLUTE_P
|
|
|
79
115
|
need(!controller.signal.aborted,'cancelled');shape(decision,['decision']);
|
|
80
116
|
need(['approved','rejected'].includes(decision.decision),'idea_save_decision_invalid');
|
|
81
117
|
if(decision.decision==='rejected'){stage='draft_ready';return {stage,saveDecision:'rejected',writeAuthorized:false};}
|
|
82
|
-
|
|
118
|
+
const bytes=Buffer.from(content);
|
|
119
|
+
check();session?.writing({path:target,sha256:createHash('sha256').update(bytes).digest('hex'),length:bytes.length,draftDigest,maturity:draft.maturity});
|
|
120
|
+
writing=true;stage='saving';
|
|
83
121
|
try{fs.mkdirSync(directory,{mode:0o700});}catch(cause){if(cause.code!=='EEXIST')throw cause;}
|
|
84
122
|
check();
|
|
85
|
-
const
|
|
123
|
+
const validate=file=>need((fs.lstatSync(file).mode&0o777)===0o600,'idea_save_permissions');
|
|
86
124
|
writeReviewEvidence({reviewsDir:directory,name:request.filename,bytes,validate,exclusive:true});
|
|
87
125
|
writeReviewEvidence({reviewsDir:directory,name:request.filename,bytes,validate,inspectOnly:true});
|
|
88
126
|
saved={path:target,draftDigest,maturity:draft.maturity,source:'confirmed_write_and_readback'};stage='saved';
|
|
89
127
|
return {stage,saved,completionAuthorized:false};
|
|
90
128
|
}catch(cause){stage=writing?'save_unknown':controller.signal.aborted?'cancelled':'save_blocked';throw cause;}
|
|
91
129
|
}
|
|
130
|
+
// V1 without --session-file: a failed turn (timeout, invalid reply, disconnect)
|
|
131
|
+
// recorded nothing, so the same operation may be sent again, twice per process.
|
|
132
|
+
if(stage==='failed'&&failedTurn&&!session){
|
|
133
|
+
need(request.operation===failedTurn.operation,'idea_turn_not_ready');
|
|
134
|
+
need((retries.idea_interview??0)<MAX_CALL_ABANDONS,'idea_retry_limit');
|
|
135
|
+
retries.idea_interview=(retries.idea_interview??0)+1;stage=failedTurn.priorStage;failedTurn=null;
|
|
136
|
+
}
|
|
92
137
|
need(request.operation==='start'?stage==='ready':['awaiting_user','draft_ready'].includes(stage),'idea_turn_not_ready');
|
|
93
138
|
need(nonempty(request.text),'idea_input_invalid');
|
|
94
139
|
const maturity=request.operation==='start'?'L1':request.maturity;
|
|
95
140
|
need(['L1','L2','L3'].includes(maturity)&&(draft!==null||maturity==='L1'),'idea_maturity_invalid');
|
|
96
141
|
const messages=[...transcript,{role:'user',text:request.text}];
|
|
97
|
-
need(Buffer.byteLength(JSON.stringify(messages))<=256*1024,'idea_context_limit');stage='interviewing';
|
|
142
|
+
need(Buffer.byteLength(JSON.stringify(messages))<=256*1024,'idea_context_limit');const priorStage=stage;stage='interviewing';
|
|
98
143
|
try{
|
|
99
144
|
const response=json(await call('idea_interview',{messages,draft,maturity,
|
|
100
145
|
reference:path.join(admission.skillDir,'references/idea-to-prd.md'),
|
|
@@ -114,7 +159,36 @@ output.write('cm-idea-host.mjs serve --skill-dir PATH [--session-file ABSOLUTE_P
|
|
|
114
159
|
if(response.status==='draft')draft=response;
|
|
115
160
|
stage=response.status==='question'?'awaiting_user':response.status==='draft'?'draft_ready':'blocked';
|
|
116
161
|
return {stage,reply:response,writeAuthorized:false,completionAuthorized:false};
|
|
117
|
-
}catch(cause){stage=controller.signal.aborted?'cancelled':'failed';
|
|
162
|
+
}catch(cause){stage=controller.signal.aborted?'cancelled':'failed';
|
|
163
|
+
if(stage==='failed')failedTurn={operation:request.operation,priorStage};throw cause;}
|
|
164
|
+
};
|
|
165
|
+
// V6 (O15): the host alone writes prd/<file>; compare the disk with the
|
|
166
|
+
// digest recorded before writing. A temp link left by a crash between link
|
|
167
|
+
// and unlink is the host's own name for the same inode and is removed.
|
|
168
|
+
const reconcileSave=(expected,filename)=>{
|
|
169
|
+
const directory=saveRoot===null?null:path.join(saveRoot,'prd');
|
|
170
|
+
need(expected&&typeof filename==='string'&&/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/.test(filename)&&directory!==null
|
|
171
|
+
&&expected.path===path.join(directory,filename)&&draft!==null&&expected.draftDigest===digest(draft),'idea_save_recovery_conflict');
|
|
172
|
+
// The same location checks as a normal save: canonical root, and prd/ a
|
|
173
|
+
// real, canonical directory (a symlinked or moved prd/ is a conflict).
|
|
174
|
+
checkSaveLocation(directory,'idea_save_recovery_conflict');
|
|
175
|
+
let stat;try{stat=fs.lstatSync(expected.path);}catch(cause){if(cause.code==='ENOENT')return 'absent';throw cause;}
|
|
176
|
+
const sha=file=>createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
177
|
+
need(stat.isFile()&&!stat.isSymbolicLink()&&(stat.mode&0o777)===0o600&&stat.size===expected.length
|
|
178
|
+
&&sha(expected.path)===expected.sha256,'idea_save_recovery_conflict');
|
|
179
|
+
if(stat.nlink!==1){
|
|
180
|
+
// Only the host's own temp name for this very file (same device/inode as
|
|
181
|
+
// the verified target, the recorded size and digest) is removed.
|
|
182
|
+
const twins=fs.readdirSync(directory).filter(name=>/^\.cm-review-[0-9a-f-]{36}$/.test(name)).map(name=>path.join(directory,name))
|
|
183
|
+
.filter(file=>{const other=fs.lstatSync(file);return other.isFile()&&!other.isSymbolicLink()&&other.ino===stat.ino&&other.dev===stat.dev;});
|
|
184
|
+
need(stat.nlink===2&&twins.length===1,'idea_save_recovery_conflict');
|
|
185
|
+
checkSaveLocation(directory,'idea_save_recovery_conflict');
|
|
186
|
+
const again=fs.lstatSync(twins[0]),target=fs.lstatSync(expected.path);
|
|
187
|
+
need(again.ino===stat.ino&&again.dev===stat.dev&&target.ino===stat.ino&&target.dev===stat.dev
|
|
188
|
+
&&again.size===expected.length&&sha(twins[0])===expected.sha256,'idea_save_recovery_conflict');
|
|
189
|
+
fs.unlinkSync(twins[0]);
|
|
190
|
+
}
|
|
191
|
+
return 'matches';
|
|
118
192
|
};
|
|
119
193
|
const host={handle:async raw=>{
|
|
120
194
|
if(!session)return handle(raw);
|
|
@@ -124,14 +198,30 @@ output.write('cm-idea-host.mjs serve --skill-dir PATH [--session-file ABSOLUTE_P
|
|
|
124
198
|
}
|
|
125
199
|
let request=raw;
|
|
126
200
|
if(raw.operation==='resume'){
|
|
127
|
-
shape(raw,['requestId','operation','resolution']);
|
|
201
|
+
shape(raw,['requestId','operation','resolution']);
|
|
202
|
+
const resolution=raw.resolution;
|
|
203
|
+
if(resolution?.discard===true||resolution?.abandon===true)session.abandonCall(resolution);
|
|
204
|
+
const pending=session.state.pending;
|
|
205
|
+
if(pending?.writing&&pending.expected&&resolution===null){
|
|
206
|
+
restore(session.state.checkpoint);
|
|
207
|
+
if(reconcileSave(pending.expected,pending.request.filename)==='matches'){
|
|
208
|
+
saved={path:pending.expected.path,draftDigest:pending.expected.draftDigest,maturity:pending.expected.maturity,
|
|
209
|
+
source:'recovered_write_readback'};stage='saved';session.commit(snapshot());
|
|
210
|
+
return {stage,saved,recovered:true,completionAuthorized:false};
|
|
211
|
+
}
|
|
212
|
+
session.writeAbsent();
|
|
213
|
+
}
|
|
214
|
+
request=session.resume(resolution?.discard===true||resolution?.abandon===true?null:resolution);
|
|
128
215
|
if(request===null)return status();restore(session.state.checkpoint);
|
|
129
216
|
}else session.begin(json(raw),snapshot());
|
|
130
217
|
try{const result=await handle(request);session.commit(snapshot());return result;}
|
|
131
218
|
catch(cause){
|
|
132
219
|
// Retain original received results as well as unknown calls. Only
|
|
133
220
|
// pre-dispatch validation failures may discard the pending operation.
|
|
134
|
-
|
|
221
|
+
// Like cm-init: restore the operation's starting checkpoint, so a refused
|
|
222
|
+
// request (e.g. the target already exists) never strands the stage.
|
|
223
|
+
if(!session.state.cancelled&&session.state.pending?.call===null&&!session.state.pending?.writing){
|
|
224
|
+
restore(session.state.checkpoint);session.commit(snapshot());}
|
|
135
225
|
throw cause;
|
|
136
226
|
}
|
|
137
227
|
}};
|