@aibyzero/cm-workflow 0.15.5 → 0.16.1
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 +45 -0
- package/README.md +2 -2
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +174 -3
- package/package.json +1 -1
- package/runtime/js/cm-ai/checklist-coverage.mjs +70 -0
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +12 -2
- package/runtime/js/cm-ai/durable-runner-state.mjs +12 -1
- package/runtime/js/cm-ai/effect-contract.mjs +31 -4
- package/runtime/js/cm-ai/host-conversation-execution.mjs +91 -3
- package/runtime/js/cm-ai/host-handoff.mjs +59 -1
- package/runtime/js/cm-ai/host-session.mjs +21 -2
- package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -1
- package/runtime/js/cm-ai/review-package.mjs +29 -3
- package/runtime/js/cm-ai/task-runner.mjs +44 -3
- package/runtime/js/cm-fix/cause-invocation.mjs +17 -4
- package/runtime/js/cm-fix/execution.mjs +30 -22
- package/runtime/js/cm-fix/final-review.mjs +18 -11
- package/runtime/js/cm-fix/finish.mjs +14 -1
- package/runtime/js/cm-security/scan.mjs +7 -1
- package/scripts/cm-ai-batch-host.mjs +18 -6
- package/scripts/cm-ai-batch-run.mjs +12 -4
- package/scripts/cm-ai-checklist-coverage.test.mjs +116 -0
- package/scripts/cm-ai-execution-diagnostic.test.mjs +68 -0
- package/scripts/cm-ai-host.mjs +7 -2
- package/scripts/cm-ai-qa-recovery-args.test.mjs +80 -0
- package/scripts/cm-ai-review-timeout-config.test.mjs +53 -0
- package/scripts/cm-ai-run.mjs +2 -1
- package/scripts/cm-ai-verification-gate.test.mjs +116 -0
- package/scripts/cm-fix-cross-session-host.test.mjs +100 -0
- package/scripts/cm-fix-execution.test.mjs +33 -0
- package/scripts/cm-fix-host.mjs +11 -5
- package/scripts/cm-fix-repair-owner.test.mjs +22 -18
- package/scripts/cm-host-handoff.test.mjs +116 -1
- package/scripts/cm-host-session-diagnostic.test.mjs +82 -0
- package/scripts/cm-review-dependency-snapshot.test.mjs +85 -0
- package/scripts/cm-review-inventory.test.mjs +42 -0
- package/scripts/cm-security.test.mjs +24 -0
- package/skills/cm-ai/references/N3-execute-task.md +10 -0
- package/skills/cm-fix/references/js-host.md +18 -1
- package/templates/auto-update/cm-update.sh +51 -0
|
@@ -17,6 +17,7 @@ import {codexWorker,preflightMatches} from './worker-codex.mjs';
|
|
|
17
17
|
import {createHostReviewAuthority} from './host-review-authority.mjs';
|
|
18
18
|
import {createHostWorkflowCapabilities} from './host-workflow-capabilities.mjs';
|
|
19
19
|
import {resolveHostRole} from './host-role-routing.mjs';
|
|
20
|
+
import {checklistGaps} from './checklist-coverage.mjs';
|
|
20
21
|
import {specsPermissionArgs} from './codex-config.mjs';
|
|
21
22
|
import {createProjectExecution} from './host-project-execution.mjs';
|
|
22
23
|
import {codeProjectPaths,codeProjectInstructionPaths,resolveCodeProjects} from './code-projects.mjs';
|
|
@@ -25,16 +26,75 @@ import {validateDocumentationPaths} from './host-documentation.mjs';
|
|
|
25
26
|
import {verifySpecificationMaterial} from './specification-material.mjs';
|
|
26
27
|
import {isFinalCmAiTask} from './cm-ai-admission.mjs';
|
|
27
28
|
import {createHostBootstrap} from './host-bootstrap.mjs';
|
|
28
|
-
import {digest,id,hex,json,need,shape,freeze} from './effect-contract.mjs';
|
|
29
|
+
import {digest,id,hex,json,need,shape,freeze,arrayItems} from './effect-contract.mjs';
|
|
29
30
|
export const protectedTextInstructions='\nProtected current-host mode: do not write files or run commands. Return {status,value,edits} on success; '
|
|
30
31
|
+'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content}], complete UTF-8 text or null for deletion. '
|
|
31
32
|
+'Only the supplied scope and expected hashes are allowed. The fixed sandbox applies these edits. On failure return {status,code} without edits. '
|
|
32
33
|
+'status must be exactly "succeeded" on success (with value and edits) or "failed" (with code). Return the object through the structured output schema; never wrap it in markdown fences.';
|
|
33
34
|
const protectedConversations=new WeakMap();
|
|
34
35
|
export const conversationProtection=execution=>protectedConversations.get(execution)??null;
|
|
36
|
+
// An explicit reviewer budget wins over the protected-mode budget: it is the
|
|
37
|
+
// narrower knob, and raising it must not require switching development mode.
|
|
38
|
+
// Absent both, the worker default applies. Returns a spread-ready fragment so
|
|
39
|
+
// an unset budget never plants an undefined timeoutMs on the worker options.
|
|
40
|
+
// Between the task's own checks and the independent review. It may only block:
|
|
41
|
+
// passing it is not an approval, produces no receipt and consumes no review
|
|
42
|
+
// round. A satisfied gate still leaves the full independent review ahead.
|
|
43
|
+
//
|
|
44
|
+
// One deliberate limit, stated rather than papered over: a task's verification
|
|
45
|
+
// is free text, so JS cannot prove every requirement in it was enumerated. What
|
|
46
|
+
// is enforced mechanically is the shape, that each returned requirement cites a
|
|
47
|
+
// nonempty evidence location, and that the gate passes only when every returned
|
|
48
|
+
// requirement is satisfied. Mechanical shape is not semantic coverage.
|
|
49
|
+
export function readVerificationPrecheck(raw){
|
|
50
|
+
const value=json(raw,256*1024);shape(value,['items']);
|
|
51
|
+
const items=arrayItems(value.items);
|
|
52
|
+
need(items.length>0&&items.length<=64,'verification_precheck_invalid');
|
|
53
|
+
for(const item of items){
|
|
54
|
+
shape(item,['requirement','satisfied','evidence']);
|
|
55
|
+
need(typeof item.satisfied==='boolean','verification_precheck_invalid');
|
|
56
|
+
for(const field of ['requirement','evidence']){
|
|
57
|
+
const text=item[field];
|
|
58
|
+
need(typeof text==='string'&&text.trim().length>0&&Buffer.byteLength(text,'utf8')<=2000
|
|
59
|
+
&&!/[\x00-\x08\x0b-\x1f]/.test(text),'verification_precheck_invalid');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return freeze({satisfied:items.every(item=>item.satisfied===true),
|
|
63
|
+
unsatisfied:items.filter(item=>item.satisfied!==true).map(item=>item.requirement),
|
|
64
|
+
evidence:items.map(item=>item.evidence).join('\n')});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The delivered evidence usually lives in the scope files (a walkthrough
|
|
68
|
+
// document, a baseline note), not in the gate answers, so the coverage
|
|
69
|
+
// reminder reads both. Unreadable, oversized, symlinked or binary entries are
|
|
70
|
+
// skipped: a file this reminder cannot read is the review's problem, not its
|
|
71
|
+
// own, and it must never turn a readable delivery into a failure.
|
|
72
|
+
const COVERAGE_FILE_LIMIT=256*1024;
|
|
73
|
+
export function deliveredText(codeProject,scope){
|
|
74
|
+
if(typeof codeProject!=='string'||!Array.isArray(scope))return '';
|
|
75
|
+
const parts=[];
|
|
76
|
+
for(const entry of scope.slice(0,64)){
|
|
77
|
+
if(typeof entry!=='string'||entry.length===0)continue;
|
|
78
|
+
try{
|
|
79
|
+
const file=path.join(codeProject,entry);
|
|
80
|
+
const info=fs.lstatSync(file);
|
|
81
|
+
if(!info.isFile()||info.isSymbolicLink()||info.size>COVERAGE_FILE_LIMIT)continue;
|
|
82
|
+
const body=fs.readFileSync(file,'utf8');
|
|
83
|
+
if(!body.includes('\u0000'))parts.push(body);
|
|
84
|
+
}catch{/* a file the reminder cannot read simply contributes nothing */}
|
|
85
|
+
}
|
|
86
|
+
return parts.join('\n');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function resolveReviewTimeout(review,protection){
|
|
90
|
+
if(review?.timeoutMs!=null)return {timeoutMs:review.timeoutMs};
|
|
91
|
+
if(protection)return {timeoutMs:protection.timeoutMs};
|
|
92
|
+
return {};
|
|
93
|
+
}
|
|
35
94
|
export function createConversationExecution(definition,hostContextId,bridge,review=null,allowedAttempt=null,workflow=null,allowQa=false,runtime='codex',options={}){
|
|
36
95
|
definition=json(definition);workflow=workflow===null?null:json(workflow);options=json(options);
|
|
37
|
-
shape(options,[...['protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember'].filter(key=>Object.hasOwn(options,key))]);
|
|
96
|
+
shape(options,[...['protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
|
|
97
|
+
need(!Object.hasOwn(options,'verificationPrecheck')||typeof options.verificationPrecheck==='boolean','invalid_input');
|
|
38
98
|
const parallelMember=options.parallelMember??false;need(typeof parallelMember==='boolean','invalid_input');
|
|
39
99
|
const provider=options.providerDevelopment??null;
|
|
40
100
|
if(provider){
|
|
@@ -77,7 +137,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
77
137
|
...(workflow?{workflow}: {})};
|
|
78
138
|
const reviewOptions={cwd:definition.codeProject,model:review?.model??'unconfigured',preflight:review?.preflight??null,
|
|
79
139
|
disabledSkills:review?.disabledSkills??[],
|
|
80
|
-
...(protection
|
|
140
|
+
...resolveReviewTimeout(review,protection),
|
|
81
141
|
promptTransport:'stdin',schemaPath:fileURLToPath(new URL('./review-result.schema.json',import.meta.url))};
|
|
82
142
|
need(!allowedAttempts.length||review!==null,'review_configuration_required');
|
|
83
143
|
if(allowedAttempts.length||provider)need((reviewerRuntime==='codex'?preflightMatches:claudePreflightMatches)(reviewOptions.preflight,reviewOptions),'tool_preflight_missing');
|
|
@@ -102,7 +162,35 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
102
162
|
};
|
|
103
163
|
};
|
|
104
164
|
const used=new Set();
|
|
165
|
+
// The gate is opt-in: without it the flow is byte-for-byte what it was.
|
|
166
|
+
// The runner contract is exactly {satisfied}. Which requirements failed is
|
|
167
|
+
// what the operator needs to act on, so it goes to this process's stderr the
|
|
168
|
+
// same way other host diagnostics do, not into the runner state.
|
|
169
|
+
const verificationGate=options.verificationPrecheck===true?async(request,control)=>{
|
|
170
|
+
const verdict=readVerificationPrecheck(await bridge.call('verification_precheck',
|
|
171
|
+
{...request,codeProject:definition.codeProject,feature:definition.feature,
|
|
172
|
+
scope:definition.scope},control.signal));
|
|
173
|
+
if(!verdict.satisfied)try{
|
|
174
|
+
process.stderr.write(JSON.stringify({diagnostic:'verification_precheck_failed',
|
|
175
|
+
task:request.identity.taskId,attempt:request.identity.attempt,
|
|
176
|
+
unsatisfied:verdict.unsatisfied})+'\n');
|
|
177
|
+
}catch{/* diagnostics never change the verdict */}
|
|
178
|
+
// Advisory only. An enumerated list in the task text whose entries are not
|
|
179
|
+
// all present in the delivery is the cheapest rejection to catch, but
|
|
180
|
+
// wording differs legitimately ("列表为空" vs "空列表"), so this reports and
|
|
181
|
+
// never rejects: the verdict below is the gate's, untouched.
|
|
182
|
+
try{
|
|
183
|
+
const gaps=checklistGaps([request.description,request.verification]
|
|
184
|
+
.filter(text=>typeof text==='string').join('\n'),
|
|
185
|
+
[verdict.evidence,deliveredText(definition.codeProject,definition.scope)].join('\n'));
|
|
186
|
+
if(gaps.length>0)process.stderr.write(JSON.stringify({diagnostic:'checklist_coverage',
|
|
187
|
+
task:request.identity.taskId,attempt:request.identity.attempt,advisory:true,
|
|
188
|
+
gaps:gaps.map(gap=>({total:gap.total,missing:gap.missing}))})+'\n');
|
|
189
|
+
}catch{/* diagnostics never change the verdict */}
|
|
190
|
+
return {satisfied:verdict.satisfied};
|
|
191
|
+
}:null;
|
|
105
192
|
const execution={configuration,timeoutMs:provider?protection.timeoutMs:1800000,excludedContexts:[hostContextId],hostDecision:null,applicableAgentFiles:[],
|
|
193
|
+
...(verificationGate?{verificationGate}:{}),
|
|
106
194
|
...(bootstrap?{bootstrap}:{}),
|
|
107
195
|
...(provider?{developmentAttempt:provider.attempt}:{}),
|
|
108
196
|
...(workflow?createHostWorkflowCapabilities({definition,configuration:workflow,bridge,allowQa,runtime,protectedExecution:protection!==null,bootstrap,parallelMember}):{}),
|
|
@@ -47,6 +47,64 @@ export function verifyHostHandoff(raw){
|
|
|
47
47
|
return {outcome:'matched',handoffSha256:bound.handoff.sha256,packageDigest:reviewPackage.packageDigest};
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
// A handoff a review already consumed is approval evidence and is never replaced.
|
|
51
|
+
// One left by a run that died before review is not: it must not block every retry
|
|
52
|
+
// of the same task forever. The receipt names the handoff it reviewed, so the two
|
|
53
|
+
// cases are distinguishable without guessing from timestamps or run identity.
|
|
54
|
+
function reviewConsumedHandoff(parent,name,attempt){
|
|
55
|
+
const suffix=`-a${attempt}-handoff.json`;
|
|
56
|
+
if(!name.endsWith(suffix))return true;
|
|
57
|
+
const receipt=path.join(parent,`${name.slice(0,-suffix.length)}-r${attempt}.md`);
|
|
58
|
+
let body;
|
|
59
|
+
try{
|
|
60
|
+
const info=fs.lstatSync(receipt);
|
|
61
|
+
// Receipts are written under a 256 KiB cap. Anything larger is not one, and
|
|
62
|
+
// guessing about it must not license replacing approval evidence.
|
|
63
|
+
if(!info.isFile()||info.isSymbolicLink()||info.size>256*1024)return true;
|
|
64
|
+
body=fs.readFileSync(receipt,'utf8');
|
|
65
|
+
}catch(error){
|
|
66
|
+
if(error.code==='ENOENT')return false;
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
// Search the real front matter rather than a fixed line count: the scope list
|
|
70
|
+
// after handoff: is as long as the task's changed file list, so any reordering
|
|
71
|
+
// of these fields would silently push handoff: out of a fixed window and turn
|
|
72
|
+
// reviewed evidence into a supersedable leftover. Unterminated or unrecognised
|
|
73
|
+
// front matter fails closed.
|
|
74
|
+
const lines=body.split('\n');
|
|
75
|
+
if(lines[0]?.trim()!=='---')return true;
|
|
76
|
+
const end=lines.findIndex((line,index)=>index>0&&line.trim()==='---');
|
|
77
|
+
if(end===-1)return true;
|
|
78
|
+
return lines.slice(1,end).some(line=>line.trim()===`handoff: ${name}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Archive by link-then-unlink so the bytes survive a crash between the two steps.
|
|
82
|
+
function supersedeHandoff(parent,handoffPath,existing){
|
|
83
|
+
const archive=path.join(parent,'.superseded');
|
|
84
|
+
fs.mkdirSync(archive,{recursive:true,mode:0o700});
|
|
85
|
+
const stamp=createHash('sha256').update(existing).digest('hex').slice(0,16);
|
|
86
|
+
const target=path.join(archive,`${path.basename(handoffPath)}.${stamp}`);
|
|
87
|
+
try{fs.linkSync(handoffPath,target);}catch(error){if(error.code!=='EEXIST')throw error;}
|
|
88
|
+
fs.unlinkSync(handoffPath);
|
|
89
|
+
const dir=fs.openSync(archive,fs.constants.O_RDONLY);
|
|
90
|
+
try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Publish with no-replace semantics, resolving only the collisions that are
|
|
94
|
+
// provably safe to resolve. Returns nothing; throws on a conflict it may not touch.
|
|
95
|
+
function publishHandoff(parent,handoffPath,temp,bytes,attempt){
|
|
96
|
+
try{fs.linkSync(temp,handoffPath);return;}
|
|
97
|
+
catch(error){if(error.code!=='EEXIST')throw error;}
|
|
98
|
+
const info=fs.lstatSync(handoffPath);
|
|
99
|
+
need(info.isFile()&&!info.isSymbolicLink(),'handoff_exists');
|
|
100
|
+
const existing=fs.readFileSync(handoffPath);
|
|
101
|
+
// Republishing identical bytes is the crash-after-link case, already published.
|
|
102
|
+
if(existing.equals(bytes))return;
|
|
103
|
+
need(!reviewConsumedHandoff(parent,path.basename(handoffPath),attempt),'handoff_exists');
|
|
104
|
+
supersedeHandoff(parent,handoffPath,existing);
|
|
105
|
+
fs.linkSync(temp,handoffPath);
|
|
106
|
+
}
|
|
107
|
+
|
|
50
108
|
export function createHostHandoff(raw){
|
|
51
109
|
const {root,baseline,checks,handoffPath,parent,reviewPackage,changedFiles,payload,bytes}=prepareHostHandoff(raw);
|
|
52
110
|
const temp=path.join(parent,`.cm-initial-handoff-${randomUUID()}`);
|
|
@@ -58,7 +116,7 @@ export function createHostHandoff(raw){
|
|
|
58
116
|
verifyReviewPackage({root,baseline,checks,reviewPackage,expectedDigest:reviewPackage.packageDigest});
|
|
59
117
|
need(payload.implementation_sha256===implementationSha256(root,changedFiles),'snapshot_changed');
|
|
60
118
|
// Atomic no-replace publication, unlike rename which could overwrite approval.
|
|
61
|
-
|
|
119
|
+
publishHandoff(parent,handoffPath,temp,bytes,baseline.identity.attempt);
|
|
62
120
|
fs.unlinkSync(temp);
|
|
63
121
|
const dir=fs.openSync(parent,fs.constants.O_RDONLY);
|
|
64
122
|
try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
|
|
@@ -1,10 +1,26 @@
|
|
|
1
1
|
// JSONL transport only. The existing host/runner owns decisions and durable state.
|
|
2
|
+
import {executionDiagnostic} from './effect-contract.mjs';
|
|
2
3
|
|
|
3
4
|
const LIMIT=64*1024;
|
|
4
5
|
const operationNames=new Set(['recover_final_review','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
|
|
5
6
|
'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
// Which contract codes may reach the peer is a deliberate boundary: the host
|
|
9
|
+
// exposes chosen ones as a blocked result with a reason and redacts the rest to
|
|
10
|
+
// host_request_failed. That boundary is kept exactly as is. What was missing is
|
|
11
|
+
// that the redacted ones vanished entirely, leaving the operator with no way to
|
|
12
|
+
// tell a missing field from a wrong one. The real code now goes to this
|
|
13
|
+
// process's own stderr and nowhere else: not to the peer, not to any log or
|
|
14
|
+
// state. Named fields only, never error.message.
|
|
15
|
+
function reportRequestFailure(errorOutput,operation,error){
|
|
16
|
+
try{
|
|
17
|
+
const detail=executionDiagnostic(error);
|
|
18
|
+
errorOutput.write(JSON.stringify({diagnostic:'host_request_failed',operation,
|
|
19
|
+
...(detail??{detail:'unavailable'})})+'\n');
|
|
20
|
+
}catch{/* diagnostics never change the reply */}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimit=LIMIT,errorOutput=process.stderr}){
|
|
8
24
|
if(!Number.isSafeInteger(inputLimit)||inputLimit<LIMIT||inputLimit>4*1024*1024)throw Error('input_limit_invalid');
|
|
9
25
|
let pending=null,buffer=Buffer.alloc(0),failure=null,closeRequested=false;
|
|
10
26
|
let writing=Promise.resolve();
|
|
@@ -47,7 +63,10 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
|
|
|
47
63
|
const requestId=request.requestId;
|
|
48
64
|
const invoke=async()=>{
|
|
49
65
|
try{await reply({requestId,result:await host.handle(request)});}
|
|
50
|
-
catch
|
|
66
|
+
catch(error){
|
|
67
|
+
reportRequestFailure(errorOutput,request.operation,error);
|
|
68
|
+
await reply({requestId,error:{code:'host_request_failed'}});
|
|
69
|
+
}
|
|
51
70
|
};
|
|
52
71
|
// Never queue cancel/status behind a long developer or reviewer call.
|
|
53
72
|
if(request.operation==='status'||request.operation==='cancel'){
|
|
@@ -18,7 +18,7 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
|
|
|
18
18
|
},
|
|
19
19
|
call(kind,payload,signal,{timeoutMs=null}={}){
|
|
20
20
|
need(send!==null&&!closed,'host_bridge_unavailable');need(pending===null,'host_bridge_busy');
|
|
21
|
-
need(['develop','check','check_runtime','check_semantic','qa_assess','qa_logic','qa_browser','change_impact','test_cases','refactor_analyze','refactor_confirm','refactor_apply','refactor_review','refactor_batch','refactor_prepare_tests','refactor_retrospective','refactor_recover','documentation_sync','documentation_inspect','fix_diagnose','fix_learning','fix_test_author','fix_repair','fix_retrospective','init_analyze','init_generate','init_verify','init_confirm','init_review','init_write','idea_interview','idea_confirm_save','prd_analyze','prd_materials','prd_generate','prd_self_check','prd_review','prd_correct','prd_summary']
|
|
21
|
+
need(['develop','check','verification_precheck','check_runtime','check_semantic','qa_assess','qa_logic','qa_browser','change_impact','test_cases','refactor_analyze','refactor_confirm','refactor_apply','refactor_review','refactor_batch','refactor_prepare_tests','refactor_retrospective','refactor_recover','documentation_sync','documentation_inspect','fix_diagnose','fix_learning','fix_test_author','fix_repair','fix_retrospective','init_analyze','init_generate','init_verify','init_confirm','init_review','init_write','idea_interview','idea_confirm_save','prd_analyze','prd_materials','prd_generate','prd_self_check','prd_review','prd_correct','prd_summary']
|
|
22
22
|
.includes(kind),'host_operation_invalid');need(!signal.aborted,'cancelled');
|
|
23
23
|
const data=json({kind,payload},12*1024*1024);
|
|
24
24
|
const request={type:'host_request',sessionId,callId:randomUUID(),requestDigest:digest(data),...data};
|
|
@@ -46,8 +46,11 @@ export function validateHostWorkflowConfiguration(raw){
|
|
|
46
46
|
need(Array.isArray(config[key])&&config[key].length<=256&&config[key].every(item=>typeof item==='string'),'invalid_workflow_config');
|
|
47
47
|
if(config.qa!==null){
|
|
48
48
|
shape(config.qa,['commands','environment',...(Object.hasOwn(config.qa,'timeoutMs')?['timeoutMs']:[])]);
|
|
49
|
+
// A real browser walkthrough of one blocking case runs for minutes, so this
|
|
50
|
+
// follows the shared call-timeout range rather than a fixed minute. The
|
|
51
|
+
// default below is unchanged; only an explicit configuration may raise it.
|
|
49
52
|
if(Object.hasOwn(config.qa,'timeoutMs'))need(Number.isSafeInteger(config.qa.timeoutMs)
|
|
50
|
-
&&config.qa.timeoutMs>0&&config.qa.timeoutMs<=
|
|
53
|
+
&&config.qa.timeoutMs>0&&config.qa.timeoutMs<=3600000,'invalid_workflow_config');
|
|
51
54
|
}
|
|
52
55
|
return config;
|
|
53
56
|
}
|
|
@@ -16,6 +16,28 @@ const materialPath=(p,selected)=>selected.has(p)||p.split('/').at(-1)==='AGENTS.
|
|
|
16
16
|
// Keep this narrower than the discovery scanner: dist/build may be authored files.
|
|
17
17
|
const dependencyDirectories=new Set(['.venv','node_modules','__pycache__','.pytest_cache','.ruff_cache']);
|
|
18
18
|
const inDependencyDirectory=p=>p.split('/').slice(0,-1).some(part=>dependencyDirectories.has(part.toLowerCase()));
|
|
19
|
+
// CocoaPods installs ios/Pods as a generated tree whose headers are symlinks.
|
|
20
|
+
// It is a dependency root like node_modules, but every other dependency root
|
|
21
|
+
// here is a fixed name, while this one is recognised from the filesystem. That
|
|
22
|
+
// makes the predicate itself a security boundary: whatever it accepts leaves
|
|
23
|
+
// the snapshot silently, so both the traversal and the scope guard must ask
|
|
24
|
+
// exactly this one function, and it must be expensive to satisfy by accident
|
|
25
|
+
// or on purpose. Four independent CocoaPods artefacts are required — the name,
|
|
26
|
+
// the two generated entries inside, and the Podfile.lock beside it — so an
|
|
27
|
+
// authored directory called pods/ still enters the snapshot and its symlinks
|
|
28
|
+
// still fail closed.
|
|
29
|
+
function isCocoaPodsRoot(absolute) {
|
|
30
|
+
if(path.basename(absolute).toLowerCase()!=='pods')return false;
|
|
31
|
+
try {
|
|
32
|
+
return fs.lstatSync(path.join(absolute,'Manifest.lock')).isFile()
|
|
33
|
+
&& fs.lstatSync(path.join(absolute,'Pods.xcodeproj')).isDirectory()
|
|
34
|
+
&& fs.lstatSync(path.join(path.dirname(absolute),'Podfile.lock')).isFile();
|
|
35
|
+
} catch { return false; }
|
|
36
|
+
}
|
|
37
|
+
const inCocoaPodsTree=(root,p)=>{
|
|
38
|
+
const parts=p.split('/');
|
|
39
|
+
return parts.slice(0,-1).some((part,index)=>isCocoaPodsRoot(path.join(root,...parts.slice(0,index+1))));
|
|
40
|
+
};
|
|
19
41
|
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
20
42
|
const fail = code => { const error=new Error(code); error.code=code; throw error; };
|
|
21
43
|
const need = (condition,code='invalid_input') => { if(!condition) fail(code); };
|
|
@@ -55,8 +77,12 @@ function filePath(p) {
|
|
|
55
77
|
&& p.normalize('NFC')===p,'unsupported_path');
|
|
56
78
|
const parts=p.split('/');
|
|
57
79
|
need(parts.every(s=>s && s!=='.' && s!=='..'),'unsupported_path');
|
|
80
|
+
// Committed placeholder files are ordinary source: .env.example and friends
|
|
81
|
+
// exist to be copied, and a repository that contains one must still be able to
|
|
82
|
+
// capture a baseline at all. Only these four explicit suffixes are allowed, so
|
|
83
|
+
// .env, .env.local and even .env.example.bak stay rejected as before.
|
|
58
84
|
need(parts.every(s=>!['.git','.ssh','.aws','.gnupg'].includes(s.toLowerCase())
|
|
59
|
-
&& !/^\.env(?:\.|$)/i.test(s)),'unsupported_path');
|
|
85
|
+
&& (!/^\.env(?:\.|$)/i.test(s) || /^\.env\.(?:example|sample|template|dist)$/i.test(s))),'unsupported_path');
|
|
60
86
|
return p;
|
|
61
87
|
}
|
|
62
88
|
function paths(input) {
|
|
@@ -141,7 +167,7 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
|
|
|
141
167
|
if(p===specsPath){need(s.isDirectory()&&!s.isSymbolicLink(),'unsupported_path');continue;}
|
|
142
168
|
// Never follow a dependency-root symlink. Old baselines that captured
|
|
143
169
|
// these files still verify their original material instead of dropping it.
|
|
144
|
-
if(s.isDirectory()&&dependencyDirectories.has(name)
|
|
170
|
+
if(s.isDirectory()&&(dependencyDirectories.has(name.toLowerCase())||isCocoaPodsRoot(path.join(root,p)))
|
|
145
171
|
&&!retainedPaths.some(file=>file.startsWith(p+'/')))continue;
|
|
146
172
|
if(s.isDirectory()) walk(p,depth+1,codeRoot);
|
|
147
173
|
else add(p,s);
|
|
@@ -183,7 +209,7 @@ export function captureReviewBaseline(options) {
|
|
|
183
209
|
specification=captureSpecificationMaterial({...v.specification,taskId:v.identity.taskId});
|
|
184
210
|
}
|
|
185
211
|
const scope=paths(v.scope), requirements=requirementPaths(v.requirements,bootstrap!==null||specification!==null),root=rootPath(v.root);
|
|
186
|
-
need(![...scope,...requirements].some(inDependencyDirectory),'excluded_snapshot_path');
|
|
212
|
+
need(![...scope,...requirements].some(p=>inDependencyDirectory(p)||inCocoaPodsTree(root,p)),'excluded_snapshot_path');
|
|
187
213
|
const projectPaths=Object.hasOwn(v,'codeProjectPaths')?validateCodeProjectPaths(v.codeProjectPaths):null;
|
|
188
214
|
if(projectPaths!==null)resolveCodeProjects(v.root,projectPaths.map(prefix=>path.join(root,prefix)));
|
|
189
215
|
const specsPath=Object.hasOwn(v,'specsRoot')?reviewSpecsPath(root,v.specsRoot):null;
|
|
@@ -92,9 +92,14 @@ export function createTaskRunner(options) {
|
|
|
92
92
|
if(options && Object.hasOwn(options,'specification'))optionKeys.push('specification');
|
|
93
93
|
if(options && Object.hasOwn(options,'bootstrap'))optionKeys.push('bootstrap');
|
|
94
94
|
if(options && Object.hasOwn(options,'codeProjectPaths'))optionKeys.push('codeProjectPaths');
|
|
95
|
+
if(options && Object.hasOwn(options,'verificationGate'))optionKeys.push('verificationGate');
|
|
95
96
|
if(invocationMode)optionKeys.push('reviewInvocation');
|
|
96
97
|
shape(options,optionKeys);
|
|
97
98
|
const {check,commit}=options;need(typeof check==='function' && (taskMode||typeof commit==='function'));
|
|
99
|
+
// Opt-in gate between the task's own checks and the independent review. It may
|
|
100
|
+
// only block: passing it grants nothing and never substitutes for that review.
|
|
101
|
+
const verificationGate=options.verificationGate??null;
|
|
102
|
+
need(verificationGate===null||typeof verificationGate==='function');
|
|
98
103
|
if(taskMode)need(Object.hasOwn(options,'persistence'),'runner_completion');
|
|
99
104
|
const config=json({root:options.root,identity:options.identity,scope:options.scope,requirements:options.requirements,
|
|
100
105
|
...(Object.hasOwn(options,'codeProjectPaths')?{codeProjectPaths:validateCodeProjectPaths(options.codeProjectPaths)}:{}),
|
|
@@ -198,6 +203,12 @@ export function createTaskRunner(options) {
|
|
|
198
203
|
...handoffBinding(),reviewPackage,receipt,registered:registered.get(receipt.id),
|
|
199
204
|
at:reviewInvocation.registration.registeredAt});
|
|
200
205
|
}
|
|
206
|
+
// A develop effect the host gate blocked keeps its audit entry like any other,
|
|
207
|
+
// so the next corrected delivery needs a new effect id or it would just read
|
|
208
|
+
// the blocked result back out of the cache. Counting them here keeps that
|
|
209
|
+
// derivation in one place, next to the cache it is derived from.
|
|
210
|
+
const verificationBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='develop'
|
|
211
|
+
&&entry.result?.state==='blocked'&&entry.result?.code==='verification_precheck_failed').length;
|
|
201
212
|
const privateStatus=()=>json({state,code,identity:{...config.identity,attempt},packageDigest:reviewPackage?.packageDigest??null,
|
|
202
213
|
receipt,receipts,calls,cancelAfterCommit,workflowError,...(store?{cancellationRequested}:{}),...(taskMode?{taskCommit}:{}),
|
|
203
214
|
...(invocationMode?{reviewInvocation}:{}),...(taskLearning!==null?{learningWriteback:learningResult?.writeback??null}:{})},16*1024*1024);
|
|
@@ -562,6 +573,27 @@ export function createTaskRunner(options) {
|
|
|
562
573
|
if(cancelReject)controller.signal.removeEventListener('abort',cancelReject);}
|
|
563
574
|
}
|
|
564
575
|
async function collectChecks(){return json(await bounded(check,json({identity:{...config.identity,attempt}})));}
|
|
576
|
+
// Runs on the checks just collected, before any handoff or review package is
|
|
577
|
+
// built, so a deliverable that does not satisfy the task's own written
|
|
578
|
+
// verification never spends an independent review round.
|
|
579
|
+
async function verificationSatisfied(checks) {
|
|
580
|
+
if(verificationGate===null)return true;
|
|
581
|
+
// The description carries hard requirements too ("also confirm X/Y/Z do not
|
|
582
|
+
// regress", "do not modify A"), and a gate that reads only the verification
|
|
583
|
+
// section lets exactly those through to the independent review. Both are
|
|
584
|
+
// sent; neither is required to exist.
|
|
585
|
+
const specification=Object.hasOwn(original,'specification')?verifySpecificationMaterial(original):null;
|
|
586
|
+
const verification=specification?.task?.verification??null;
|
|
587
|
+
const description=specification?.task?.description??null;
|
|
588
|
+
const written=value=>typeof value==='string'&&value.trim().length>0;
|
|
589
|
+
if(!written(verification)&&!written(description))return true;
|
|
590
|
+
const verdict=json(await bounded(verificationGate,
|
|
591
|
+
json({identity:{...config.identity,attempt},
|
|
592
|
+
...(written(description)?{description}:{}),
|
|
593
|
+
...(written(verification)?{verification}:{}),checks})));
|
|
594
|
+
shape(verdict,['satisfied']);need(typeof verdict.satisfied==='boolean','invalid_result');
|
|
595
|
+
return verdict.satisfied;
|
|
596
|
+
}
|
|
565
597
|
async function perform(v) {
|
|
566
598
|
if(v.kind==='develop') {
|
|
567
599
|
need(stageAllowed('develop',state,code),'stage_mismatch');state='developing';code=null;receipt=null;
|
|
@@ -601,6 +633,8 @@ export function createTaskRunner(options) {
|
|
|
601
633
|
if(writeback.outcome==='writeback_pending'){halt('blocked','learning_writeback_pending');return;}
|
|
602
634
|
if(taskLearning.hostHandoff===true){
|
|
603
635
|
currentChecks=await collectChecks();active();
|
|
636
|
+
if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return;}
|
|
637
|
+
active();
|
|
604
638
|
createHostHandoff({root:config.root,baseline:base,checks:currentChecks,
|
|
605
639
|
handoffPath:completion.handoffs[attempt-1]});
|
|
606
640
|
}
|
|
@@ -608,7 +642,11 @@ export function createTaskRunner(options) {
|
|
|
608
642
|
identity:{...config.identity,attempt},learningInput:v.learningInput,application,retrospective,writeback});
|
|
609
643
|
}
|
|
610
644
|
need(result.response.result.outcome==='implemented','invalid_result');
|
|
611
|
-
if(taskLearning?.hostHandoff!==true)
|
|
645
|
+
if(taskLearning?.hostHandoff!==true){
|
|
646
|
+
currentChecks=await collectChecks();active();
|
|
647
|
+
if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return;}
|
|
648
|
+
}
|
|
649
|
+
active();
|
|
612
650
|
const nextPackage=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,
|
|
613
651
|
...(taskLearning?.hostHandoff===true?{handoffPath:completion.handoffs[attempt-1]}:{})});
|
|
614
652
|
if(taskLearning!==null)validateTaskLearningReviewPackage(nextPackage,learningResult.writeback,v.learningInput,
|
|
@@ -689,7 +727,10 @@ export function createTaskRunner(options) {
|
|
|
689
727
|
try {
|
|
690
728
|
if(state==='ready')need(digest(captureReviewBaseline({...configToBaseline(metadata),version:original.version,
|
|
691
729
|
...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})}))===digest(original),'package_mismatch');
|
|
692
|
-
|
|
730
|
+
// A develop restarted from a locally rejected delivery has no review package
|
|
731
|
+
// to verify yet: the invalid result never built one, and the host gate blocks
|
|
732
|
+
// before one is built.
|
|
733
|
+
else if(!(v.kind==='develop'&&stageAllowed('develop',state,code)))verifyReviewPackage({root:config.root,baseline:state==='changes_requested'?attemptBaseline(original,attempt-1):base,
|
|
693
734
|
checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
|
|
694
735
|
} catch {return Promise.resolve(freeze({outcome:'rejected',code:'package_mismatch'}));}
|
|
695
736
|
try{const record=persist('effect-intent',{effect:v});
|
|
@@ -790,7 +831,7 @@ export function createTaskRunner(options) {
|
|
|
790
831
|
need(state==='fixture_completed','qa_attach_not_completed');
|
|
791
832
|
persist('qa-attached',{record});qaAttachment=record;return json(record);
|
|
792
833
|
};
|
|
793
|
-
const api={executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa};
|
|
834
|
+
const api={executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks};
|
|
794
835
|
if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
|
|
795
836
|
if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
|
|
796
837
|
return Object.freeze(api);
|
|
@@ -3,7 +3,19 @@ import {validateReviewDispatchGrant} from '../cm-ai/durable-runner-state.mjs';
|
|
|
3
3
|
import {inspectProviderCauseReview} from '../cm-ai/provider-review-observation.mjs';
|
|
4
4
|
import {digest,id,json,need,shape,text,hex} from '../cm-ai/effect-contract.mjs';
|
|
5
5
|
|
|
6
|
+
// A run outlives the session that created it. Its durable configuration keeps the
|
|
7
|
+
// original hostContextId, so stored records and fingerprints stay byte-identical;
|
|
8
|
+
// a resumed session declares its own next to it. Both are host identities: a grant
|
|
9
|
+
// may carry either, and the reviewer stays independent of both.
|
|
10
|
+
export function fixHostContexts(configuration){
|
|
11
|
+
const hosts=configuration.hostContextIds??[configuration.hostContextId];
|
|
12
|
+
need(Array.isArray(hosts)&&hosts.length>=1&&hosts.length<=2&&new Set(hosts).size===hosts.length
|
|
13
|
+
&&hosts[0]===configuration.hostContextId,'invalid_host_context');
|
|
14
|
+
hosts.forEach(id);return hosts;
|
|
15
|
+
}
|
|
6
16
|
export function validateCauseReviewer(raw,hostContextId,maxExclusions=32){
|
|
17
|
+
const hosts=Array.isArray(hostContextId)?hostContextId:[hostContextId];
|
|
18
|
+
need(hosts.length>=1&&hosts.length<=2,'invalid_cause_reviewer');hosts.forEach(id);
|
|
7
19
|
need([32,33,34].includes(maxExclusions),'invalid_cause_reviewer');
|
|
8
20
|
const value=json(raw);shape(value,['reviewerId','adapterId','provider','requestedModel','contextId','excludedThreadIds',
|
|
9
21
|
...(Object.hasOwn(value,'workerConfigurationDigest')?['workerConfigurationDigest']:[])]);
|
|
@@ -11,12 +23,13 @@ export function validateCauseReviewer(raw,hostContextId,maxExclusions=32){
|
|
|
11
23
|
for(const key of ['reviewerId','adapterId','contextId'])id(value[key]);text(value.requestedModel);
|
|
12
24
|
need(['codex','claude'].includes(value.provider),'invalid_cause_reviewer');
|
|
13
25
|
need(Array.isArray(value.excludedThreadIds)&&value.excludedThreadIds.length<=maxExclusions,'invalid_cause_reviewer');
|
|
14
|
-
value.excludedThreadIds.forEach(id);need(value.contextId
|
|
26
|
+
value.excludedThreadIds.forEach(id);need(!hosts.includes(value.contextId)&&!value.excludedThreadIds.includes(value.contextId),'invalid_cause_reviewer');
|
|
15
27
|
return value;
|
|
16
28
|
}
|
|
17
29
|
export function causeExpectation(request,configuration){
|
|
18
|
-
|
|
19
|
-
|
|
30
|
+
const hosts=fixHostContexts(configuration);
|
|
31
|
+
return {request,developerThreadId:hosts[0],
|
|
32
|
+
excludedThreadIds:[...configuration.causeReview.excludedThreadIds,...hosts.slice(1),request.contextId,
|
|
20
33
|
...(request.payload.reviewPackage.correction?.finalReview?[request.payload.reviewPackage.correction.finalReview.providerThreadId]:[])]};
|
|
21
34
|
}
|
|
22
35
|
export function inspectCauseRegistration(raw,configuration){
|
|
@@ -24,7 +37,7 @@ export function inspectCauseRegistration(raw,configuration){
|
|
|
24
37
|
const r=configuration.causeReview,request=value.request;
|
|
25
38
|
need(request.provider===r.provider&&request.requestedModel===r.requestedModel&&request.contextId===r.contextId,'cause_registration_mismatch');
|
|
26
39
|
validateReviewDispatchGrant(value.grant,{request,reviewerId:r.reviewerId,adapterId:r.adapterId,
|
|
27
|
-
packageDigest:request.payload.reviewPackage.packageDigest,hostContextIds:
|
|
40
|
+
packageDigest:request.payload.reviewPackage.packageDigest,hostContextIds:fixHostContexts(configuration),
|
|
28
41
|
authorizationAt:value.authorizationAt,registeredAt:value.registeredAt});
|
|
29
42
|
inspectProviderCauseReview(JSON.stringify({version:1,kind:'cm-provider-review-observation',
|
|
30
43
|
requestDigest:request.requestDigest,events:[],result:{status:'failed',code:'in_progress'}}),
|