@aibyzero/cm-workflow 0.16.8 → 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 +19 -0
- package/README.md +14 -3
- package/VERSION +1 -1
- package/compat/claude-commands/cm-notify.md +3 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +25 -1
- package/docs/next-steps.md +8 -2
- package/docs/user-guide.md +105 -5
- package/package.json +2 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -20
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +69 -22
- package/runtime/js/cm-ai/code-projects.mjs +4 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
- package/runtime/js/cm-ai/drive-core.mjs +9 -0
- 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/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 +49 -4
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
- package/runtime/js/cm-ai/host-session.mjs +1 -1
- package/runtime/js/cm-ai/host-tool-bridge.mjs +40 -3
- 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-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/execution.mjs +176 -48
- package/runtime/js/cm-fix/host.mjs +2 -1
- package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
- package/runtime/js/cm-fix/progress.mjs +13 -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-safe-read.mjs +49 -0
- package/runtime/js/notify-send.mjs +312 -0
- package/runtime/js/notify.mjs +137 -33
- package/runtime/js/policy-binding-compat.mjs +54 -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 +184 -22
- package/scripts/cm-ai-batch-run.test.mjs +21 -341
- 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 +64 -22
- package/scripts/cm-ai-drive.test.mjs +29 -2
- 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 +27 -15
- 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-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 +56 -10
- 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 +163 -10
- package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
- package/scripts/cm-fix-drive.mjs +25 -7
- package/scripts/cm-fix-host.mjs +8 -7
- 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 +22 -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 +21 -10
- 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 +221 -4
- 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/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/references/js-host-qa-recovery.md +27 -1
- package/skills/cm-ai/references/js-host-recovery.md +120 -8
- package/skills/cm-ai/references/js-host.md +14 -7
- package/skills/cm-check/SKILL.md +3 -3
- package/skills/cm-fix/references/js-host.md +44 -5
- 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/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
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
|
}};
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// External answer gaps, batch 3 (O08-O12): cm-init re-asks read-only steps and
|
|
2
|
+
// confirmations under the same pending request, and leaves unknown writes to the
|
|
3
|
+
// archived-draft recovery. Every scenario drives the real cm-init-host.mjs.
|
|
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,spawnSync} from 'node:child_process';
|
|
10
|
+
import {createInterface} from 'node:readline';
|
|
11
|
+
import {once} from 'node:events';
|
|
12
|
+
import {fileURLToPath} from 'node:url';
|
|
13
|
+
import {openDraftSession} from '../runtime/js/cm-idea/session.mjs';
|
|
14
|
+
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
15
|
+
const analyzed={status:'analyzed',selection:{versionControl:'none',modules:[],analysis:'Synthetic local project'},
|
|
16
|
+
evidence:'Synthetic source observation',noGitDecision:'explicit_user_refusal'};
|
|
17
|
+
const checks=status=>({checks:Object.fromEntries(['commands','globs','file_references','constraint_preservation','rule_applicability']
|
|
18
|
+
.map(category=>[category,{status,evidence:'Synthetic fixture evidence'}])),constraintChanges:[]});
|
|
19
|
+
function fixture(t){
|
|
20
|
+
const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-init-gaps-'))),project=path.join(dir,'project');
|
|
21
|
+
fs.mkdirSync(project);fs.writeFileSync(path.join(project,'README.md'),'# Synthetic project\n');
|
|
22
|
+
t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return {dir,project,file:path.join(dir,'init.json')};
|
|
23
|
+
}
|
|
24
|
+
function args(f,{author='author-a',allowWrite=false,memory=false,resumeDraft=null}={}){
|
|
25
|
+
return [path.join(root,'scripts/cm-init-host.mjs'),'serve','--skill-dir',path.join(root,'skills/cm-init'),'--project',f.project,
|
|
26
|
+
'--host-context',author,...(allowWrite?['--allow-write']:[]),...(memory?[]:resumeDraft?['--resume-draft',resumeDraft]:['--session-file',f.file])];
|
|
27
|
+
}
|
|
28
|
+
async function client(t,f,respond,options={}){
|
|
29
|
+
const child=spawn(process.execPath,args(f,options),{stdio:['pipe','pipe','pipe']});
|
|
30
|
+
t.after(()=>{if(child.exitCode===null&&!child.killed)child.kill();});
|
|
31
|
+
let sessionId,seq=0,stderr='';const pending=new Map(),closed=once(child,'close'),requests=[];
|
|
32
|
+
let acceptReady,rejectReady;const ready=new Promise((yes,no)=>{acceptReady=yes;rejectReady=no;});
|
|
33
|
+
const send=value=>child.stdin.write(JSON.stringify(value)+'\n');child.stderr.on('data',bytes=>stderr+=bytes);
|
|
34
|
+
createInterface({input:child.stdout}).on('line',line=>{
|
|
35
|
+
const message=JSON.parse(line);
|
|
36
|
+
if(message.type==='host_ready'){sessionId=message.sessionId;acceptReady();}
|
|
37
|
+
else if(message.type==='host_request'){requests.push(message);Promise.resolve().then(()=>respond(message,child)).then(result=>{
|
|
38
|
+
if(result!==undefined)send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,result});
|
|
39
|
+
}).catch(rejectReady);}
|
|
40
|
+
else if(message.type==='host_response'){if(message.accepted===false)requests.push({rejected:message.code});}
|
|
41
|
+
else if(pending.has(message.requestId)){pending.get(message.requestId)(message);pending.delete(message.requestId);}
|
|
42
|
+
});
|
|
43
|
+
child.on('close',code=>{if(!sessionId)rejectReady(Object.assign(Error(stderr),{stderr,code}));for(const resolve of pending.values())resolve({closed:code});pending.clear();});
|
|
44
|
+
await ready;
|
|
45
|
+
return {child,requests,stderr:()=>stderr,
|
|
46
|
+
// stderr is a separate pipe from the reply on stdout: wait for the diagnostic line instead of racing it.
|
|
47
|
+
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);},send:value=>send({...value,sessionId}),request:(operation,fields={})=>new Promise(resolve=>{
|
|
48
|
+
const requestId=`request-${++seq}`;pending.set(requestId,resolve);send({requestId,operation,...fields});}),
|
|
49
|
+
close:async()=>{send({type:'host_close',sessionId});const [code]=await closed;assert.equal(code,0,stderr);}};
|
|
50
|
+
}
|
|
51
|
+
function reply(message){
|
|
52
|
+
if(message.kind==='init_analyze')return analyzed;
|
|
53
|
+
if(message.kind==='init_generate')return {status:'generated',documents:message.payload.targets.map(file=>({path:file,content:'# Synthetic rules\n'}))};
|
|
54
|
+
if(message.kind==='init_verify')return checks('verified');
|
|
55
|
+
if(message.kind==='init_confirm')return {decision:'approved'};
|
|
56
|
+
if(message.kind==='init_review')return {reviewer:'codex-subagent',contextId:'reviewer-fixture',independent:true,at:new Date().toISOString(),
|
|
57
|
+
result:{verdict:'approved',packageDigest:message.payload.package.packageDigest,examinedPaths:message.payload.package.examinedPaths,findings:[],summary:'Synthetic independent review'}};
|
|
58
|
+
assert.fail('unexpected host call '+message.kind);
|
|
59
|
+
}
|
|
60
|
+
const saved=f=>JSON.parse(fs.readFileSync(f.file,'utf8'));
|
|
61
|
+
|
|
62
|
+
test('real host: a recorded refused analysis is discarded and asked again twice, the third discard hits the limit',{timeout:20000},async t=>{
|
|
63
|
+
const f=fixture(t);let bad=3;
|
|
64
|
+
const respond=message=>message.kind==='init_analyze'&&bad-->0?{...analyzed,evidence:' '}:reply(message);
|
|
65
|
+
let c=await client(t,f,respond);
|
|
66
|
+
assert.equal((await c.request('start')).error.code,'host_request_failed');await c.close();
|
|
67
|
+
c=await client(t,f,()=>assert.fail('a recorded answer is replayed, not re-asked'));
|
|
68
|
+
let status=(await c.request('status')).result;
|
|
69
|
+
assert.equal(status.recovery.call.status,'recorded');assert.match(status.guidance.nextStep,/discard:true/);
|
|
70
|
+
assert.equal((await c.request('resume',{resolution:null})).error.code,'host_request_failed');await c.close();
|
|
71
|
+
for(let round=1;round<=3;round++){
|
|
72
|
+
c=await client(t,f,respond);status=(await c.request('status')).result;
|
|
73
|
+
const {callId,requestDigest}=status.recovery.call;
|
|
74
|
+
const result=await c.request('resume',{resolution:{callId,requestDigest,discard:true,evidence:'evidence was blank'}});
|
|
75
|
+
if(round<3){assert.equal(result.error.code,'host_request_failed');assert.equal(c.requests.at(-1).kind,'init_analyze');
|
|
76
|
+
assert.notEqual(c.requests.at(-1).callId,callId);}
|
|
77
|
+
else{assert.equal(result.error.code,'host_request_failed');await c.stderrMatch(/idea_session_abandon_limit/);assert.equal(c.requests.length,0);}
|
|
78
|
+
await c.close();
|
|
79
|
+
}
|
|
80
|
+
const record=saved(f).abandonedCalls;
|
|
81
|
+
assert.equal(record.length,2);assert.deepEqual(record.map(item=>[item.kind,item.reason,item.operation]),
|
|
82
|
+
[['init_analyze','answer_rejected','start'],['init_analyze','answer_rejected','start']]);
|
|
83
|
+
assert.equal(record[0].evidence.length,'evidence was blank'.length);assert.equal(JSON.stringify(record).includes('evidence was blank'),false);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test('real host: an unknown verification is abandoned and re-asked; the late original receipt is refused',{timeout:20000},async t=>{
|
|
87
|
+
const f=fixture(t);let original;
|
|
88
|
+
let c=await client(t,f,reply);await c.request('start');await c.request('advance');await c.close();
|
|
89
|
+
c=await client(t,f,(message,child)=>{original=message;setImmediate(()=>child.kill('SIGKILL'));});await c.request('advance');
|
|
90
|
+
c=await client(t,f,reply);
|
|
91
|
+
const status=(await c.request('status')).result;assert.equal(status.recovery.call.status,'unknown');
|
|
92
|
+
assert.match(status.guidance.nextStep,/abandon:true/);
|
|
93
|
+
const {callId,requestDigest}=status.recovery.call;
|
|
94
|
+
assert.ok((await c.request('resume',{resolution:{callId,requestDigest,discard:true,evidence:'wrong mode'}})).error,'discard needs a recorded answer');
|
|
95
|
+
const resumed=(await c.request('resume',{resolution:{callId,requestDigest,abandon:true,evidence:'session lost the call'}})).result;
|
|
96
|
+
assert.equal(resumed.stage,'review_required');assert.equal(c.requests.at(-1).kind,'init_verify');await c.close();
|
|
97
|
+
c=await client(t,f,()=>assert.fail('no call'));
|
|
98
|
+
const late={callId:original.payload.recovery.callId,requestDigest:original.payload.recovery.requestDigest,result:checks('verified'),evidence:'late'};
|
|
99
|
+
assert.equal((await c.request('resume',{resolution:late})).error.code,'host_request_failed');await c.close();
|
|
100
|
+
assert.equal(saved(f).abandonedCalls[0].reason,'answer_missing');
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('real host V7: a lost confirmation asks the current user again with a new callId',{timeout:20000},async t=>{
|
|
104
|
+
const f=fixture(t);fs.writeFileSync(path.join(f.project,'AGENTS.md'),'# Original constraint\n');
|
|
105
|
+
const respond=message=>message.kind==='init_verify'?{...checks('verified'),constraintChanges:['AGENTS.md']}:reply(message);
|
|
106
|
+
let c=await client(t,f,respond);await c.request('start');await c.request('advance');
|
|
107
|
+
assert.equal((await c.request('advance')).result.stage,'confirmation_required');await c.close();
|
|
108
|
+
let first;c=await client(t,f,(message,child)=>{first=message;setImmediate(()=>child.kill('SIGKILL'));});await c.request('advance');
|
|
109
|
+
const asked=[];
|
|
110
|
+
c=await client(t,f,message=>{asked.push(message);return {decision:'rejected'};});
|
|
111
|
+
const {callId,requestDigest}=(await c.request('status')).result.recovery.call;
|
|
112
|
+
const result=(await c.request('resume',{resolution:{callId,requestDigest,abandon:true,evidence:'user decision was lost'}})).result;
|
|
113
|
+
assert.equal(result.stage,'confirmation_rejected');assert.equal(asked.length,1);assert.equal(asked[0].kind,'init_confirm');
|
|
114
|
+
assert.notEqual(asked[0].payload.recovery.callId,first.payload.recovery.callId);await c.close();
|
|
115
|
+
assert.equal(fs.readFileSync(path.join(f.project,'AGENTS.md'),'utf8'),'# Original constraint\n');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test('forged, duplicated and over-limit abandon records are refused when the session is reopened',{timeout:20000},async t=>{
|
|
119
|
+
const f=fixture(t);let bad=1;
|
|
120
|
+
let c=await client(t,f,message=>message.kind==='init_analyze'&&bad-->0?{status:'analyzed'}:reply(message));
|
|
121
|
+
await c.request('start');const {callId,requestDigest}=(await c.request('status')).result.recovery.call;
|
|
122
|
+
await c.request('resume',{resolution:{callId,requestDigest,discard:true,evidence:'missing fields'}});await c.close();
|
|
123
|
+
const good=fs.readFileSync(f.file,'utf8'),state=JSON.parse(good),record=state.abandonedCalls[0];
|
|
124
|
+
assert.equal(state.checkpoint.stage,'analysis_ready');
|
|
125
|
+
const variants={
|
|
126
|
+
duplicate:{...state,abandonedCalls:[record,record]},
|
|
127
|
+
overLimit:{...state,abandonedCalls:[1,2,3].map(n=>({...record,callId:`${record.callId}-${n}`}))},
|
|
128
|
+
forgedKind:{...state,abandonedCalls:[{...record,kind:'init_write'}]},
|
|
129
|
+
forgedShape:{...state,abandonedCalls:[{...record,evidence:'raw text'}]},
|
|
130
|
+
missingResult:{...state,abandonedCalls:[{...record,resultDigest:null}]},
|
|
131
|
+
};
|
|
132
|
+
for(const [name,value] of Object.entries(variants)){
|
|
133
|
+
fs.writeFileSync(f.file,JSON.stringify(value),{mode:0o600});
|
|
134
|
+
await assert.rejects(()=>client(t,f,()=>assert.fail(name)),/idea_session_abandon_record_invalid/,name);
|
|
135
|
+
}
|
|
136
|
+
// The untouched file still opens and keeps its record.
|
|
137
|
+
fs.writeFileSync(f.file,good,{mode:0o600});
|
|
138
|
+
const session=openDraftSession(f.file,state.binding,'cm-init');assert.equal(session.abandonedCalls.length,1);session.close();
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test('an old session file without abandonedCalls replays unchanged',{timeout:20000},async t=>{
|
|
142
|
+
const f=fixture(t);let c=await client(t,f,reply);await c.request('start');await c.request('advance');await c.close();
|
|
143
|
+
const before=fs.readFileSync(f.file,'utf8');assert.equal(Object.hasOwn(JSON.parse(before),'abandonedCalls'),false);
|
|
144
|
+
c=await client(t,f,()=>assert.fail('status and resume of a finished operation never call the host'));
|
|
145
|
+
const status=(await c.request('status')).result;assert.equal(status.stage,'draft_generated');assert.equal(status.recovery,null);
|
|
146
|
+
assert.equal((await c.request('resume',{resolution:null})).result.stage,'draft_generated');await c.close();
|
|
147
|
+
assert.equal(fs.readFileSync(f.file,'utf8'),before);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('memory mode: a failed step is re-sent twice in the same process, then init_retry_limit',{timeout:20000},async t=>{
|
|
151
|
+
const f=fixture(t);let bad=3;
|
|
152
|
+
const c=await client(t,f,message=>message.kind==='init_analyze'&&bad-->0?{status:'analyzed'}:reply(message),{memory:true});
|
|
153
|
+
assert.ok((await c.request('start')).error);
|
|
154
|
+
let status=(await c.request('status')).result;assert.equal(status.stage,'failed');assert.equal(status.retry.remaining,2);
|
|
155
|
+
assert.match(status.guidance.nextStep,/--session-file/);
|
|
156
|
+
assert.ok((await c.request('advance')).error,'a different operation does not reuse the failed step');
|
|
157
|
+
assert.ok((await c.request('start')).error);assert.ok((await c.request('start')).error);
|
|
158
|
+
status=(await c.request('status')).result;assert.equal(status.retry.remaining,0);
|
|
159
|
+
assert.ok((await c.request('start')).error);await c.stderrMatch(/init_retry_limit/);
|
|
160
|
+
assert.equal(c.requests.filter(item=>item.kind==='init_analyze').length,3);await c.close();
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test('unknown write stays on archived-draft recovery; a conflict lists every file for a person',{timeout:30000},async t=>{
|
|
164
|
+
const f=fixture(t);fs.writeFileSync(path.join(f.project,'AGENTS.md'),'# Original constraint\n');
|
|
165
|
+
const respond=message=>message.kind==='init_verify'?{...checks('verified'),constraintChanges:['AGENTS.md']}:reply(message);
|
|
166
|
+
let c=await client(t,f,respond);await c.request('start');await c.request('advance');await c.request('advance');
|
|
167
|
+
await c.request('advance');await c.request('advance');await c.close();
|
|
168
|
+
c=await client(t,f,(message,child)=>{
|
|
169
|
+
assert.equal(message.kind,'init_write');
|
|
170
|
+
for(const document of message.payload.documents.slice(0,1))fs.writeFileSync(path.join(f.project,document.path),document.content);
|
|
171
|
+
setImmediate(()=>child.kill('SIGKILL'));},{allowWrite:true});
|
|
172
|
+
await c.request('advance');
|
|
173
|
+
c=await client(t,f,()=>assert.fail('unknown write never redispatches'),{allowWrite:true});
|
|
174
|
+
const status=(await c.request('status')).result,digest=fs.readdirSync(path.join(f.project,'.reviews'))[0].slice('cm-init-'.length,-3);
|
|
175
|
+
assert.equal(status.recovery.writing,true);assert.match(status.guidance.nextStep,new RegExp(`--resume-draft ${digest}`));
|
|
176
|
+
assert.ok((await c.request('resume',{resolution:null})).error);
|
|
177
|
+
assert.ok((await c.request('resume',{resolution:{...status.recovery.call,discard:true,evidence:'x'}})).error);await c.close();
|
|
178
|
+
await c.stderrMatch(/idea_save_outcome_unknown/);
|
|
179
|
+
const driver=spawnSync(process.execPath,[path.join(root,'scripts/cm-init-drive.mjs'),'--plan',(()=>{const plan=path.join(f.dir,'plan.json');
|
|
180
|
+
fs.writeFileSync(plan,JSON.stringify({project:f.project,sessionFile:f.file,mode:'resume',hostContext:'author-a',originalHostContext:'author-a',resolution:null}));return plan;})(),'resume'],{encoding:'utf8'});
|
|
181
|
+
assert.equal(driver.status,2);assert.match(driver.stderr,new RegExp(`--resume-draft ${digest}`));
|
|
182
|
+
fs.writeFileSync(path.join(f.project,'AGENTS.md'),'# Someone else edited this\n');
|
|
183
|
+
const error=await client(t,f,()=>assert.fail('conflict never starts'),{resumeDraft:digest}).then(()=>null,cause=>cause);
|
|
184
|
+
assert.ok(error);const lines=error.stderr.trim().split('\n').map(line=>JSON.parse(line));
|
|
185
|
+
const diagnostic=lines.find(line=>line.diagnostic==='init_recovery_conflict');
|
|
186
|
+
assert.deepEqual(diagnostic.files.find(file=>file.path==='AGENTS.md').status,'conflict');assert.match(diagnostic.guidance,/保留用户改动/);
|
|
187
|
+
assert.equal(lines.at(-1).error.code,'init_recovery_conflict');
|
|
188
|
+
assert.equal(fs.readFileSync(path.join(f.project,'AGENTS.md'),'utf8'),'# Someone else edited this\n');
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test('notify classifies the new cm-init and cm-idea blocks as stuck',async()=>{
|
|
192
|
+
const {classifyDriveResult}=await import('../runtime/js/notify.mjs');
|
|
193
|
+
for(const [workflow,result] of [
|
|
194
|
+
['cm-init',{stage:'draft_generated',recovery:{operation:'advance',writing:false,call:{kind:'init_verify',status:'recorded'}}}],
|
|
195
|
+
['cm-init',{stage:'failed',retry:{operation:'start',kind:'init_analyze',remaining:1}}],
|
|
196
|
+
['cm-init',{stage:'reviewed_draft',recovery:{operation:'advance',writing:true,call:{kind:'init_write',status:'unknown'}}}],
|
|
197
|
+
['cm-idea',{stage:'draft_ready',recovery:{operation:'finish',writing:true,expected:{length:1},call:{kind:'idea_confirm_save',status:'recorded'}}}],
|
|
198
|
+
['cm-idea',{stage:'awaiting_user',recovery:{operation:'advance',writing:false,call:{kind:'idea_interview',status:'recorded'}}}],
|
|
199
|
+
['cm-idea',{stage:'save_blocked'}],['cm-idea',{stage:'failed',retry:{operation:'start',remaining:0}}]])
|
|
200
|
+
assert.equal(classifyDriveResult(workflow,{result}),'stuck',JSON.stringify(result));
|
|
201
|
+
assert.equal(classifyDriveResult('cm-idea',{result:{stage:'saved',saved:{source:'recovered_write_readback'}}}),'done');
|
|
202
|
+
assert.equal(classifyDriveResult('cm-init',{error:{code:'host_request_failed'}}),'stuck');
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
async function lostConfirm(t,f){
|
|
206
|
+
fs.writeFileSync(path.join(f.project,'AGENTS.md'),'# Original constraint\n');
|
|
207
|
+
const respond=message=>message.kind==='init_verify'?{...checks('verified'),constraintChanges:['AGENTS.md']}:reply(message);
|
|
208
|
+
let c=await client(t,f,respond);await c.request('start');await c.request('advance');await c.request('advance');await c.close();
|
|
209
|
+
c=await client(t,f,(message,child)=>{setImmediate(()=>child.kill('SIGKILL'));});await c.request('advance');
|
|
210
|
+
const call=saved(f).pending.call;assert.equal(call.kind,'init_confirm');return call;
|
|
211
|
+
}
|
|
212
|
+
function initDriver(f,resolution){
|
|
213
|
+
const answers=path.join(f.dir,'answers');fs.mkdirSync(answers,{recursive:true});
|
|
214
|
+
fs.writeFileSync(path.join(answers,'confirm.json'),JSON.stringify({decision:'approved'}));
|
|
215
|
+
const drive=(value=resolution)=>{const plan=path.join(f.dir,'plan.json');
|
|
216
|
+
fs.writeFileSync(plan,JSON.stringify({project:f.project,sessionFile:f.file,mode:'resume',hostContext:'author-a',originalHostContext:'author-a',
|
|
217
|
+
answers:'answers',resolution:value}));
|
|
218
|
+
return spawnSync(process.execPath,[path.join(root,'scripts/cm-init-drive.mjs'),'--plan',plan,'resume'],{encoding:'utf8',timeout:60000});};
|
|
219
|
+
return {answers,reask:path.join(answers,'confirm-reask.json'),drive};
|
|
220
|
+
}
|
|
221
|
+
// After the stop: only a decision bound to the newly registered call is used.
|
|
222
|
+
function answerRegisteredInit(f,d,old){
|
|
223
|
+
const call=saved(f).pending.call;assert.equal(call.kind,'init_confirm');assert.equal(Object.hasOwn(call,'result'),false);
|
|
224
|
+
assert.notEqual(call.callId,old.callId);
|
|
225
|
+
if(fs.existsSync(d.reask)){const stale=d.drive(null);assert.equal(stale.status,2);assert.match(stale.stderr,/confirm_reask_decision_stale/);fs.rmSync(d.reask);}
|
|
226
|
+
let run=d.drive(null);assert.equal(run.status,2);assert.match(run.stderr,/confirm_reask_decision_required/);assert.match(run.stderr,new RegExp(call.callId));
|
|
227
|
+
for(const stale of [{decision:'approved',replaces:old.callId},{callId:old.callId,requestDigest:old.requestDigest,decision:'approved'},
|
|
228
|
+
{callId:call.callId,requestDigest:'0'.repeat(64),decision:'approved'}]){
|
|
229
|
+
fs.writeFileSync(d.reask,JSON.stringify(stale));run=d.drive(null);assert.equal(run.status,2);assert.match(run.stderr,/confirm_reask_decision_stale/);
|
|
230
|
+
assert.equal(Object.hasOwn(saved(f).pending.call,'result'),false);
|
|
231
|
+
}
|
|
232
|
+
fs.writeFileSync(d.reask,JSON.stringify({callId:call.callId,requestDigest:call.requestDigest,decision:'rejected'}));
|
|
233
|
+
run=d.drive(null);assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.stage,'confirmation_rejected');
|
|
234
|
+
}
|
|
235
|
+
test('driver V7: a re-asked init_confirm is registered first; confirm.json and decisions bound to other calls are never used',{timeout:60000},async t=>{
|
|
236
|
+
const f=fixture(t),call=await lostConfirm(t,f),d=initDriver(f,null);
|
|
237
|
+
const run=d.drive({callId:call.callId,requestDigest:call.requestDigest,abandon:true,evidence:'confirmation lost'});
|
|
238
|
+
assert.equal(run.status,2);assert.match(run.stderr,/confirm_reask_decision_required/);
|
|
239
|
+
answerRegisteredInit(f,d,call);
|
|
240
|
+
});
|
|
241
|
+
// Round-2 narrow review: a decision bound to an earlier (historical) confirmation is
|
|
242
|
+
// on disk when a later confirmation is re-issued after a crash; it is never reused.
|
|
243
|
+
test('driver V7 cross-request: after a crash before registration, a stale decision of an earlier call is refused',{timeout:60000},async t=>{
|
|
244
|
+
const f=fixture(t),call=await lostConfirm(t,f),state=saved(f);
|
|
245
|
+
const {createHash}=await import('node:crypto');const evidence='confirmation lost';
|
|
246
|
+
state.abandonedCalls=[{kind:call.kind,callId:call.callId,requestDigest:call.requestDigest,operation:state.pending.request.operation,
|
|
247
|
+
reason:'answer_missing',resultDigest:null,evidence:{sha256:createHash('sha256').update(JSON.stringify(evidence)).digest('hex'),length:evidence.length},
|
|
248
|
+
at:new Date().toISOString()}];
|
|
249
|
+
state.pending={...state.pending,call:null};fs.writeFileSync(f.file,JSON.stringify(state),{mode:0o600});
|
|
250
|
+
const d=initDriver(f,null);
|
|
251
|
+
// The earlier call's approval, in both the old and the new decision-file shapes.
|
|
252
|
+
for(const stale of [{decision:'approved',replaces:call.callId},{callId:call.callId,requestDigest:call.requestDigest,decision:'approved'}]){
|
|
253
|
+
fs.writeFileSync(d.reask,JSON.stringify(stale));
|
|
254
|
+
const run=d.drive(null);assert.equal(run.status,2,run.stdout);
|
|
255
|
+
assert.match(run.stderr,/confirm_reask_decision_(required|stale)/);assert.notEqual(saved(f).checkpoint.stage,'review_required');
|
|
256
|
+
}
|
|
257
|
+
answerRegisteredInit(f,d,call);
|
|
258
|
+
});
|
|
@@ -16,7 +16,7 @@ import {inspectCmInitAdmission} from './cm-init-entry.mjs';
|
|
|
16
16
|
import {validateCmInitSelection,cmInitRuleTargets} from '../runtime/js/cm-init/draft-generation.mjs';
|
|
17
17
|
import {inspectCmInitDraft,readCmInitSource} from '../runtime/js/cm-init/draft-inspection.mjs';
|
|
18
18
|
import {reviewResultForPaths} from '../runtime/js/cm-ai/review-runner.mjs';
|
|
19
|
-
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
19
|
+
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,deliberatelyUnanswered} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
20
20
|
|
|
21
21
|
const HOST=fileURLToPath(new URL('./cm-init-host.mjs',import.meta.url));
|
|
22
22
|
const KNOWN=new Set(['start','advance','status','cancel','final_review_package','prepare_revision','resume']);
|
|
@@ -92,7 +92,7 @@ function validate(kind,value,{project,selection,checkpoint,answers,hostContext})
|
|
|
92
92
|
}
|
|
93
93
|
function main(){
|
|
94
94
|
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
95
|
-
process.stdout.write('用法: cm-init-drive.mjs --plan PLAN.json <operation>\nPLAN: project, sessionFile, mode:create|resume, hostContext, resume 时 originalHostContext
|
|
95
|
+
process.stdout.write('用法: cm-init-drive.mjs --plan PLAN.json <operation>\nPLAN: project, sessionFile, mode:create|resume, hostContext, resume 时 originalHostContext(resolution 可为 null、原回执,或 {callId,requestDigest,discard|abandon:true,evidence} 作废后重问);advance 首轮填 selection;answers 存人工分析、草稿、核验、决定和审查。allowWrite:true 时按审查草稿实际写文件。\n');return;
|
|
96
96
|
}
|
|
97
97
|
const {plan,operation,base}=loadPlanFile({name:'cm-init-drive.mjs',known:KNOWN});
|
|
98
98
|
requireFields(plan,['project','sessionFile','mode','hostContext']);
|
|
@@ -116,13 +116,37 @@ function main(){
|
|
|
116
116
|
stop(2,`advance 当前阶段不能继续: ${stage}`);
|
|
117
117
|
if(['status','final_review_package'].includes(operation)&&plan.mode!=='resume')stop(2,`${operation} 需要已有会话`);
|
|
118
118
|
if(state?.pending&&operation!=='resume')stop(2,'恢复存档存在 pending;必须用 resume 和原调用回执,不能重派');
|
|
119
|
+
let boundDecision=null;
|
|
119
120
|
if(operation==='resume'){
|
|
120
121
|
if(plan.mode!=='resume')stop(2,'resume 需要已有存档');
|
|
121
|
-
if(state.pending?.writing)
|
|
122
|
+
if(state.pending?.writing){const digest=checkpoint?.reviewPackage?.packageDigest??'<packageDigest>';
|
|
123
|
+
stop(2,`写入结果未知,不能自动恢复,也不重发 init_write。先运行 cm-init-entry.mjs --inspect-recovery ${digest} 逐文件比对,再去掉 --session-file、在宿主启动参数末尾加 --resume-draft ${digest} 续写(冲突报 init_recovery_conflict 交人)`);}
|
|
122
124
|
const call=state.pending?.call,resolution=plan.resolution??null;
|
|
123
|
-
|
|
125
|
+
// discard(已记录被拒)/abandon(结果未知):作废后在原请求下重问,答案文件按同一步骤预检。
|
|
126
|
+
const reask=obj(resolution)&&(resolution.discard===true||resolution.abandon===true);
|
|
127
|
+
if(reask){
|
|
128
|
+
valid(call&&resolution.callId===call.callId&&resolution.requestDigest===call.requestDigest&&nonempty(resolution.evidence)
|
|
129
|
+
&&!Object.hasOwn(resolution,'result')&&(resolution.discard===true)!==(resolution.abandon===true)
|
|
130
|
+
&&(resolution.discard===true?Object.hasOwn(call,'result'):!Object.hasOwn(call,'result'))
|
|
131
|
+
&&Object.keys(resolution).every(key=>['callId','requestDigest','discard','abandon','evidence'].includes(key)),
|
|
132
|
+
'resume 作废需要 {callId,requestDigest,discard:true|abandon:true,evidence}:discard 只针对已记录被拒的应答,abandon 只针对结果未知的调用');
|
|
133
|
+
const used=(state.abandonedCalls??[]).filter(item=>item.kind===call.kind).length;
|
|
134
|
+
if(used>=2)stop(2,`${call.kind} 本会话已作废 2 次,宿主会报 idea_session_abandon_limit;交人处理`);
|
|
135
|
+
}else if(call&&!Object.hasOwn(call,'result')&&call.kind==='init_confirm'&&resolution===null){
|
|
136
|
+
// V7: a registered, unanswered confirmation takes only the current user's
|
|
137
|
+
// decision bound to this exact callId and request digest; never a stale file.
|
|
138
|
+
const file=path.join(plan.answers?path.resolve(base,plan.answers):base,'confirm-reask.json');
|
|
139
|
+
const expected=`{"callId":"${call.callId}","requestDigest":"${call.requestDigest}","decision":"approved|rejected"}`;
|
|
140
|
+
const value=readJson(file,'init_confirm');
|
|
141
|
+
if(value===undefined)stop(2,`confirm_reask_decision_required:约束确认已由宿主登记(callId ${call.callId}、requestDigest ${call.requestDigest})、尚未作答;请当前用户核对后写 ${file}:${expected},再 resume;旧的确认文件不会沿用`);
|
|
142
|
+
if(!obj(value)||value.callId!==call.callId||value.requestDigest!==call.requestDigest)
|
|
143
|
+
stop(2,`confirm_reask_decision_stale:${file} 绑定的是 callId ${obj(value)?value.callId:'无效内容'},不是当前登记的 ${call.callId}(requestDigest ${call.requestDigest});不会使用,请按 ${expected} 重写`);
|
|
144
|
+
valid(Object.keys(value).sort().join(',')==='callId,decision,requestDigest'&&['approved','rejected'].includes(value.decision),`${file} 须为 ${expected}`);
|
|
145
|
+
boundDecision={callId:call.callId,requestDigest:call.requestDigest,result:{decision:value.decision},
|
|
146
|
+
evidence:`当前用户对已登记确认 ${call.callId} 的新决定(confirm-reask.json)`};
|
|
147
|
+
}else if(call&&!Object.hasOwn(call,'result')){
|
|
124
148
|
valid(obj(resolution)&&resolution.callId===call.callId&&resolution.requestDigest===call.requestDigest
|
|
125
|
-
&&nonempty(resolution.evidence)&&Object.hasOwn(resolution,'result'),'resume
|
|
149
|
+
&&nonempty(resolution.evidence)&&Object.hasOwn(resolution,'result'),'resume 缺少原调用的真实回执;找不到时可用 abandon:true 作废后重问');
|
|
126
150
|
}else valid(resolution===null,'resume 不应提供新回执');
|
|
127
151
|
}
|
|
128
152
|
let selection=checkpoint.selection;
|
|
@@ -150,7 +174,12 @@ function main(){
|
|
|
150
174
|
}
|
|
151
175
|
}
|
|
152
176
|
const answers=plan.answers?path.resolve(base,plan.answers):null;
|
|
153
|
-
|
|
177
|
+
// V7: the driver never pre-answers a constraint confirmation asked during resume
|
|
178
|
+
// (a re-ask after an abandon, or a call re-issued after a crash): the host registers
|
|
179
|
+
// it first, the driver stops naming the new callId and request digest, and the
|
|
180
|
+
// next resume takes only a decision bound to that call (boundDecision above).
|
|
181
|
+
const reasking=operation==='resume';
|
|
182
|
+
const answer=preflightAnswers(kind&&names[kind]&&!(reasking&&kind==='init_confirm')?[kind]:[],key=>{
|
|
154
183
|
const file=path.join(answers??base,names[key]),value=readJson(file,key);
|
|
155
184
|
if(value===undefined)stop(2,`步骤 ${operation} 会反问 ${key},但答案文件不存在: ${file}`);
|
|
156
185
|
return validate(key,value,{project,selection,checkpoint,answers,hostContext:plan.hostContext});
|
|
@@ -159,7 +188,7 @@ function main(){
|
|
|
159
188
|
...(plan.allowWrite===true?['--allow-write']:[]),'--session-file',sessionFile],cwd:project,operation,
|
|
160
189
|
request:{...(operation==='advance'&&stage==='ready'?{selection}:{}),
|
|
161
190
|
...(operation==='prepare_revision'?{documents:plan.documents}:{}),
|
|
162
|
-
...(operation==='resume'?{resolution:plan.resolution??null}:{})},answers:answer,
|
|
191
|
+
...(operation==='resume'?{resolution:boundDecision??plan.resolution??null}:{})},answers:answer,
|
|
163
192
|
answerFor:row=>{
|
|
164
193
|
if(row.kind==='init_review'){
|
|
165
194
|
const value=answer.init_review,pkg=row.payload.package;
|
|
@@ -185,6 +214,11 @@ function main(){
|
|
|
185
214
|
}
|
|
186
215
|
return {status:'written'};
|
|
187
216
|
}
|
|
217
|
+
if(row.kind==='init_confirm'&&reasking){
|
|
218
|
+
const recovery=row.payload?.recovery??{};
|
|
219
|
+
throw deliberatelyUnanswered(`confirm_reask_decision_required:宿主已登记新的约束确认(callId ${recovery.callId}、requestDigest ${recovery.requestDigest}),驾驶员不预先作答;`
|
|
220
|
+
+`请当前用户核对后写 ${path.join(answers??base,'confirm-reask.json')}:{"callId":"${recovery.callId}","requestDigest":"${recovery.requestDigest}","decision":"approved|rejected"},再 resume;旧的确认文件与绑定其他调用的决定都不会使用`);
|
|
221
|
+
}
|
|
188
222
|
return answer[row.kind]??null;
|
|
189
223
|
}});
|
|
190
224
|
}
|