@aibyzero/cm-workflow 0.11.0 → 0.13.2
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/AGENTS.md +3 -0
- package/CHANGELOG.md +64 -3
- package/README.md +45 -3
- package/VERSION +1 -1
- package/compat/claude-commands/cm-runtime.md +3 -0
- package/compat/claude-commands/cm-security.md +3 -0
- package/docs/architecture.md +22 -0
- package/docs/installation.md +56 -2
- package/docs/js-workflow-control.md +63 -6
- package/docs/runtime-failover.md +97 -0
- package/docs/user-guide.md +60 -3
- package/install-codex.sh +5 -0
- package/install.ps1 +10 -2
- package/install.sh +5 -0
- package/package.json +3 -1
- package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
- package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
- package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
- package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
- package/runtime/js/cm-ai/codex-config.mjs +6 -0
- package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
- package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
- package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
- package/runtime/js/cm-ai/effect-contract.mjs +10 -1
- package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
- package/runtime/js/cm-ai/host-documentation.mjs +4 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
- package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
- package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
- package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
- package/runtime/js/cm-ai/host.mjs +1 -1
- package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
- package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
- package/runtime/js/cm-ai/review-package.mjs +76 -18
- package/runtime/js/cm-ai/review-runner.mjs +15 -3
- package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
- package/runtime/js/cm-ai/specification-material.mjs +98 -0
- package/runtime/js/cm-ai/task-runner.mjs +57 -20
- package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
- package/runtime/js/cm-ai/worker-claude.mjs +18 -5
- package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
- package/runtime/js/cm-ai/worker-codex.mjs +8 -12
- package/runtime/js/cm-init/draft-generation.mjs +24 -4
- package/runtime/js/cm-init/draft-inspection.mjs +29 -1
- package/runtime/js/cm-prd/session.mjs +19 -2
- package/runtime/js/cm-prd/summary.mjs +46 -20
- package/runtime/js/cm-security/scan.mjs +263 -0
- package/runtime/js/cm-test/branch-impact.mjs +8 -2
- package/runtime/review.md +11 -1
- package/runtime/workflow-config.md +39 -2
- package/runtime/workflow-routing.md +6 -1
- package/scripts/cm-ai-admission.test.mjs +99 -0
- package/scripts/cm-ai-batch-host.test.mjs +4 -1
- package/scripts/cm-ai-batch-run.test.mjs +7 -1
- package/scripts/cm-ai-bootstrap.test.mjs +2 -1
- package/scripts/cm-ai-fix-integration.test.mjs +2 -1
- package/scripts/cm-ai-host.mjs +81 -12
- package/scripts/cm-ai-host.test.mjs +520 -5
- package/scripts/cm-ai-multi-root.test.mjs +9 -3
- package/scripts/cm-ai-nested-execution.test.mjs +11 -4
- package/scripts/cm-ai-review-timeout.test.mjs +226 -0
- package/scripts/cm-ai-run.mjs +40 -13
- package/scripts/cm-ai-run.test.mjs +45 -9
- package/scripts/cm-check-host.test.mjs +1 -1
- package/scripts/cm-check-runtime.sh +56 -1
- package/scripts/cm-check-update.mjs +200 -0
- package/scripts/cm-check-update.test.mjs +186 -0
- package/scripts/cm-claude-developer-worker.test.mjs +236 -0
- package/scripts/cm-claude-probe.test.mjs +64 -1
- package/scripts/cm-claude-review-stream.test.mjs +236 -1
- package/scripts/cm-claude-worker.test.mjs +110 -1
- package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
- package/scripts/cm-codex-developer-worker.test.mjs +84 -1
- package/scripts/cm-codex-review-progress.test.mjs +34 -6
- package/scripts/cm-failover.mjs +288 -0
- package/scripts/cm-failover.test.mjs +184 -0
- package/scripts/cm-host-qa-executor.test.mjs +277 -0
- package/scripts/cm-host-tool-bridge.test.mjs +31 -0
- package/scripts/cm-init-draft-generation.test.mjs +62 -0
- package/scripts/cm-init-draft-inspection.test.mjs +76 -0
- package/scripts/cm-init-host.mjs +4 -4
- package/scripts/cm-init-host.test.mjs +12 -7
- package/scripts/cm-init-session.test.mjs +50 -0
- package/scripts/cm-log-event.mjs +34 -5
- package/scripts/cm-prd-completion.test.mjs +2 -2
- package/scripts/cm-prd-host.mjs +39 -3
- package/scripts/cm-prd-host.test.mjs +52 -0
- package/scripts/cm-prd-review-gate.mjs +11 -2
- package/scripts/cm-prd-review-gate.test.mjs +62 -0
- package/scripts/cm-prd-session-recovery.test.mjs +167 -0
- package/scripts/cm-prd-summary.test.mjs +147 -0
- package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
- package/scripts/cm-review-inventory.test.mjs +189 -0
- package/scripts/cm-review-schema.test.mjs +35 -1
- package/scripts/cm-review-scope-recovery.test.mjs +63 -0
- package/scripts/cm-runtime-edit.mjs +104 -0
- package/scripts/cm-runtime-failover.test.mjs +130 -0
- package/scripts/cm-runtime-install.mjs +42 -0
- package/scripts/cm-runtime.mjs +113 -0
- package/scripts/cm-runtime.test.mjs +117 -0
- package/scripts/cm-security.mjs +32 -0
- package/scripts/cm-security.test.mjs +203 -0
- package/scripts/cm-spec-manifest.mjs +24 -21
- package/scripts/cm-spec-manifest.test.mjs +19 -0
- package/scripts/cm-workflow-config.mjs +113 -5
- package/scripts/cm-workflow-config.test.mjs +124 -1
- package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
- package/scripts/test-cm-prd-review-gate.py +30 -0
- package/scripts/test-shell-compat.sh +34 -0
- package/scripts/validate-public-repo.py +7 -1
- package/skills/cm-ai/references/N4-review.md +5 -4
- package/skills/cm-ai/references/js-host.md +36 -2
- package/skills/cm-check/SKILL.md +49 -8
- package/skills/cm-check/references/js-host.md +4 -1
- package/skills/cm-init/SKILL.md +4 -0
- package/skills/cm-init/references/js-host.md +2 -0
- package/skills/cm-init/references/runtime-declaration.md +26 -0
- package/skills/cm-prd/SKILL.md +3 -3
- package/skills/cm-prd/references/js-change-recovery.md +24 -3
- package/skills/cm-prd/references/summary-card.md +7 -0
- package/skills/cm-runtime/SKILL.md +32 -0
- package/skills/cm-security/SKILL.md +55 -0
- package/skills/cm-security/references/scan-contract.md +43 -0
- package/templates/auto-update/cm-update.sh +1 -1
- package/templates/cm-workflow.yml +16 -0
|
@@ -6,8 +6,8 @@ import {digest,json,need,shape} from './effect-contract.mjs';
|
|
|
6
6
|
export function createHostToolBridge({responseLimit=64*1024}={}){
|
|
7
7
|
need(Number.isSafeInteger(responseLimit)&&responseLimit>=64*1024&&responseLimit<=4*1024*1024,'host_response_limit_invalid');
|
|
8
8
|
const sessionId=randomUUID();let send=null,pending=null,closed=false;
|
|
9
|
-
const stop=code=>{
|
|
10
|
-
|
|
9
|
+
const stop=(code,call=pending)=>{
|
|
10
|
+
if(!call||pending!==call)return;pending=null;clearTimeout(call.timer);
|
|
11
11
|
call.signal.removeEventListener('abort',call.abort);
|
|
12
12
|
call.reject(Object.assign(new Error(code),{code}));
|
|
13
13
|
};
|
|
@@ -16,22 +16,25 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
|
|
|
16
16
|
need(send===null&&typeof sender==='function'&&!closed,'host_bridge_unavailable');send=sender;
|
|
17
17
|
Promise.resolve(send({type:'host_ready',sessionId})).catch(()=>{closed=true;stop('host_disconnected');});
|
|
18
18
|
},
|
|
19
|
-
call(kind,payload,signal){
|
|
19
|
+
call(kind,payload,signal,{timeoutMs=null}={}){
|
|
20
20
|
need(send!==null&&!closed,'host_bridge_unavailable');need(pending===null,'host_bridge_busy');
|
|
21
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']
|
|
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};
|
|
25
|
+
need(timeoutMs===null||Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=3600000,'host_request_timeout_invalid');
|
|
25
26
|
return new Promise((resolve,reject)=>{
|
|
26
27
|
const abort=()=>{
|
|
27
|
-
stop('cancelled');
|
|
28
|
+
stop('cancelled',call);
|
|
28
29
|
Promise.resolve(send({type:'host_call_cancelled',sessionId,callId:request.callId})).catch(()=>{});
|
|
29
30
|
};
|
|
30
|
-
|
|
31
|
+
const call={request,signal,abort,resolve,reject,timer:null};pending=call;
|
|
32
|
+
if(timeoutMs!==null)call.timer=setTimeout(()=>stop('host_request_timeout',call),timeoutMs);
|
|
33
|
+
signal.addEventListener('abort',abort,{once:true});
|
|
31
34
|
if(signal.aborted){abort();return;}
|
|
32
35
|
Promise.resolve().then(()=>{
|
|
33
36
|
if(pending?.request===request&&!closed&&!signal.aborted)return send(request);
|
|
34
|
-
}).catch(()=>stop('host_disconnected'));
|
|
37
|
+
}).catch(()=>stop('host_disconnected',call));
|
|
35
38
|
});
|
|
36
39
|
},
|
|
37
40
|
accept(raw){
|
|
@@ -45,7 +48,7 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
|
|
|
45
48
|
need(reply.type==='host_result'&&pending!==null&&!closed,'host_response_mismatch');
|
|
46
49
|
for(const key of ['sessionId','callId','requestDigest'])need(reply[key]===pending.request[key],'host_response_mismatch');
|
|
47
50
|
}catch{return {accepted:false,code:'host_response_mismatch'};}
|
|
48
|
-
const call=pending;pending=null;call.signal.removeEventListener('abort',call.abort);
|
|
51
|
+
const call=pending;pending=null;clearTimeout(call.timer);call.signal.removeEventListener('abort',call.abort);
|
|
49
52
|
call.resolve(reply.result);return {accepted:true,callId:reply.callId};
|
|
50
53
|
},
|
|
51
54
|
close(){closed=true;stop('host_disconnected');},
|
|
@@ -16,7 +16,11 @@ export function validateHostWorkflowConfiguration(raw){
|
|
|
16
16
|
shape(config,['qa','documentationPaths','applicableAgentFiles']);
|
|
17
17
|
for(const key of ['documentationPaths','applicableAgentFiles'])
|
|
18
18
|
need(Array.isArray(config[key])&&config[key].length<=256&&config[key].every(item=>typeof item==='string'),'invalid_workflow_config');
|
|
19
|
-
if(config.qa!==null)
|
|
19
|
+
if(config.qa!==null){
|
|
20
|
+
shape(config.qa,['commands','environment',...(Object.hasOwn(config.qa,'timeoutMs')?['timeoutMs']:[])]);
|
|
21
|
+
if(Object.hasOwn(config.qa,'timeoutMs'))need(Number.isSafeInteger(config.qa.timeoutMs)
|
|
22
|
+
&&config.qa.timeoutMs>0&&config.qa.timeoutMs<=60000,'invalid_workflow_config');
|
|
23
|
+
}
|
|
20
24
|
return config;
|
|
21
25
|
}
|
|
22
26
|
|
|
@@ -31,15 +35,16 @@ export function createHostWorkflowCapabilities({definition,configuration,bridge,
|
|
|
31
35
|
if(configuration.qa!==null){
|
|
32
36
|
need(allowQa===true,'qa_authorization_required');
|
|
33
37
|
result.qaLogHome=logHome;
|
|
38
|
+
const requestTimeout={timeoutMs:configuration.qa.timeoutMs??60000};
|
|
34
39
|
result.qaDecisionProvider=createHostQaDecisionProvider({timeoutMs:60000,
|
|
35
|
-
assess:(request,signal)=>bridge.call('qa_assess',request,signal)});
|
|
40
|
+
assess:(request,signal)=>bridge.call('qa_assess',request,signal,requestTimeout)});
|
|
36
41
|
result.qaExecutor=createHostQaExecutor({specsDir,codeProject,feature,requirements,runtime,
|
|
37
42
|
...(definition.codeProjects?{codeProjects:definition.codeProjects}:{}),
|
|
38
43
|
...(bootstrap?{bootstrap:{requirements:bootstrap.configuration.bootstrapRequirements,scope:definition.scope}}:{}),
|
|
39
44
|
...configuration.qa,timeoutMs:1800000,logHome,
|
|
40
45
|
...(protectedExecution?{specsRoot:specsDir}:{}),
|
|
41
|
-
logic:(request,signal)=>bridge.call('qa_logic',request,signal),
|
|
42
|
-
browser:(request,signal)=>bridge.call('qa_browser',request,signal)});
|
|
46
|
+
logic:(request,signal)=>bridge.call('qa_logic',request,signal,requestTimeout),
|
|
47
|
+
browser:(request,signal)=>bridge.call('qa_browser',request,signal,requestTimeout)});
|
|
43
48
|
}
|
|
44
49
|
return result;
|
|
45
50
|
}
|
|
@@ -16,5 +16,5 @@ export function createCmAiHost(options) {
|
|
|
16
16
|
...(qaExecutor===undefined?{}:{qaExecutor}),
|
|
17
17
|
...(documentationProvider===undefined?{}:{documentationProvider}),
|
|
18
18
|
...(qaDecisionProvider===undefined?{}:{qaDecisionProvider})});
|
|
19
|
-
return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix});
|
|
19
|
+
return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa});
|
|
20
20
|
}
|
|
@@ -26,7 +26,7 @@ function expectation(v,cause=false) {
|
|
|
26
26
|
}
|
|
27
27
|
function eventStream(events,excluded) {
|
|
28
28
|
need(Array.isArray(events)&&events.length<=64);
|
|
29
|
-
let stage=0,thread=null,terminal=null,close=null;
|
|
29
|
+
let stage=0,thread=null,terminal=null,close=null,hasResult=false;
|
|
30
30
|
for(const e of events) {
|
|
31
31
|
need(close===null);
|
|
32
32
|
if(e?.event==='process_closed') {
|
|
@@ -42,13 +42,16 @@ function eventStream(events,excluded) {
|
|
|
42
42
|
}else {
|
|
43
43
|
shape(e,['event','item_type']);
|
|
44
44
|
if(e.event==='turn.started'){need(stage===1&&e.item_type===null);stage=2;}
|
|
45
|
-
else if(e.event==='item.completed'){need(stage===2&&e.item_type==='agent_message');stage=3;}
|
|
45
|
+
else if(e.event==='item.completed'){need(stage===2&&e.item_type==='agent_message');stage=3;hasResult=true;}
|
|
46
46
|
else if(e.event==='turn.completed'){need(stage===3&&e.item_type===null);terminal=e.event;}
|
|
47
47
|
else {need(['error','turn.failed'].includes(e.event)&&e.item_type===null);terminal=e.event;}
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
|
-
return {thread,terminal,close};
|
|
50
|
+
return {thread,terminal,close,hasResult};
|
|
51
51
|
}
|
|
52
|
+
// Reuse the validated normalized stream; a final message counts even if its
|
|
53
|
+
// value was truncated or the process never reached turn.completed.
|
|
54
|
+
export const hasProviderReviewResult=events=>eventStream(events,new Set()).hasResult;
|
|
52
55
|
export function inspectProviderReview(observationText,expectationText) {
|
|
53
56
|
need(arguments.length===2);
|
|
54
57
|
return inspect(observationText,expectationText,false);
|
|
@@ -79,7 +82,8 @@ function inspect(observationText,expectationText,cause) {
|
|
|
79
82
|
observationStatus,code,review,completionEligible:false});
|
|
80
83
|
}catch(error){
|
|
81
84
|
const allowed=['limit_exceeded','observation_binding','observation_context','invalid_package',
|
|
82
|
-
'review_package_mismatch','missing_material','contradictory_verdict'
|
|
85
|
+
'review_package_mismatch','missing_material','contradictory_verdict',
|
|
86
|
+
'invalid_finding_path','invalid_finding_id','invalid_finding_severity','invalid_finding_shape'];
|
|
83
87
|
const code=allowed.includes(error?.code)?error.code:'observation_invalid';
|
|
84
88
|
throw Object.assign(new Error(code),{code});
|
|
85
89
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// A one-time extension of a completed run, never a replacement store identity.
|
|
2
|
+
import {json,shape,need,hex,id} from './effect-contract.mjs';
|
|
3
|
+
|
|
4
|
+
export function readQaAttachment(raw){
|
|
5
|
+
const record=json(raw);
|
|
6
|
+
shape(record,['version','qaFingerprint','attachedAt','hostContextId']);
|
|
7
|
+
need(record.version===1,'qa_attachment_invalid');hex(record.qaFingerprint);id(record.hostContextId);
|
|
8
|
+
need(typeof record.attachedAt==='string'&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(record.attachedAt)
|
|
9
|
+
&&Number.isFinite(Date.parse(record.attachedAt)),'qa_attachment_invalid');
|
|
10
|
+
return record;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Reconstruct only supported pre-QA configurations. All unrelated fields remain
|
|
14
|
+
// byte-for-byte digest inputs, including definition, host, protection and review.
|
|
15
|
+
export function preQaConfigurations(material){
|
|
16
|
+
if(!material?.execution)return [];
|
|
17
|
+
const wrapped=Object.hasOwn(material.execution.workflow??{},'configuration');
|
|
18
|
+
const workflow=wrapped?material.execution.workflow.configuration:material.execution.workflow;
|
|
19
|
+
if(!workflow?.qa||!material.qaExecutor||!material.qaDecisionProvider)return [];
|
|
20
|
+
const withoutQa=structuredClone(json(material));
|
|
21
|
+
delete withoutQa.qaExecutor;delete withoutQa.qaDecisionProvider;delete withoutQa.qaTimeoutMs;
|
|
22
|
+
const priorWorkflow=wrapped?withoutQa.execution.workflow.configuration:withoutQa.execution.workflow;
|
|
23
|
+
priorWorkflow.qa=null;
|
|
24
|
+
const withoutWorkflow=structuredClone(withoutQa);
|
|
25
|
+
delete withoutWorkflow.execution.workflow;
|
|
26
|
+
delete withoutWorkflow.documentationProvider;delete withoutWorkflow.documentationSync;
|
|
27
|
+
if(withoutWorkflow.execution.kind==='cm-current-conversation-v1')withoutWorkflow.applicableAgentFiles=[];
|
|
28
|
+
else delete withoutWorkflow.applicableAgentFiles;
|
|
29
|
+
return [withoutQa,withoutWorkflow];
|
|
30
|
+
}
|
|
@@ -4,6 +4,7 @@ import fs from 'node:fs';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
6
6
|
import { digest } from './contracts.mjs';
|
|
7
|
+
import {captureSpecificationMaterial,readSpecificationMaterial,verifySpecificationMaterial} from './specification-material.mjs';
|
|
7
8
|
import {resolveCodeProjects,validateCodeProjectPaths,
|
|
8
9
|
codeProjectInstructionPaths,assertCodeProjectSelections} from './code-projects.mjs';
|
|
9
10
|
|
|
@@ -70,7 +71,7 @@ function rootPath(root) {
|
|
|
70
71
|
catch(error) { if(error.code==='unsupported_file')throw error; fail('read_failed'); }
|
|
71
72
|
}
|
|
72
73
|
const statKey = s => [s.dev,s.ino,s.mode,s.nlink,s.size,s.mtimeNs,s.ctimeNs].join(':');
|
|
73
|
-
function readFile(root,p,includeContent=true,limit=FILE_LIMIT) {
|
|
74
|
+
function readFile(root,p,includeContent=true,limit=FILE_LIMIT,contentLimit=limit) {
|
|
74
75
|
let fd;
|
|
75
76
|
try {
|
|
76
77
|
const abs=path.join(root,p),before=fs.lstatSync(abs,{bigint:true});
|
|
@@ -85,7 +86,7 @@ function readFile(root,p,includeContent=true,limit=FILE_LIMIT) {
|
|
|
85
86
|
const count=fs.readSync(fd,buf,0,Math.min(buf.length,Number(before.size)+1-offset),null);
|
|
86
87
|
if(!count)break;
|
|
87
88
|
hash.update(buf.subarray(0,count));
|
|
88
|
-
if(includeContent)chunks.push(Buffer.from(buf.subarray(0,count)));
|
|
89
|
+
if(includeContent&&offset<contentLimit)chunks.push(Buffer.from(buf.subarray(0,Math.min(count,contentLimit-offset))));
|
|
89
90
|
offset+=count;
|
|
90
91
|
}
|
|
91
92
|
const after=fs.fstatSync(fd,{bigint:true}),last=fs.lstatSync(abs,{bigint:true});
|
|
@@ -167,7 +168,7 @@ const sealed = (data,key) => {
|
|
|
167
168
|
};
|
|
168
169
|
export function captureReviewBaseline(options) {
|
|
169
170
|
const v=plain(options); keys(v,['root','identity','scope','requirements',
|
|
170
|
-
...['specsRoot','codeProjectPaths','bootstrapRequirements','version'].filter(key=>Object.hasOwn(v,key))]); identityCheck(v.identity);
|
|
171
|
+
...['specsRoot','codeProjectPaths','bootstrapRequirements','specification','version'].filter(key=>Object.hasOwn(v,key))]); identityCheck(v.identity);
|
|
171
172
|
const version=v.version??2;need([1,2].includes(version));
|
|
172
173
|
const bootstrap=Object.hasOwn(v,'bootstrapRequirements')?v.bootstrapRequirements:null;
|
|
173
174
|
if(bootstrap!==null){
|
|
@@ -175,7 +176,13 @@ export function captureReviewBaseline(options) {
|
|
|
175
176
|
need(Object.hasOwn(v,'specsRoot')&&bootstrap.specsRoot===v.specsRoot,'bootstrap_requirements_mismatch');
|
|
176
177
|
currentBootstrapRequirements(bootstrap);
|
|
177
178
|
}
|
|
178
|
-
|
|
179
|
+
let specification=null;
|
|
180
|
+
if(Object.hasOwn(v,'specification')){
|
|
181
|
+
keys(v.specification,['specsRoot','feature']);
|
|
182
|
+
need(v.specification.specsRoot===v.specsRoot,'spec_drift');
|
|
183
|
+
specification=captureSpecificationMaterial({...v.specification,taskId:v.identity.taskId});
|
|
184
|
+
}
|
|
185
|
+
const scope=paths(v.scope), requirements=requirementPaths(v.requirements,bootstrap!==null||specification!==null),root=rootPath(v.root);
|
|
179
186
|
need(![...scope,...requirements].some(inDependencyDirectory),'excluded_snapshot_path');
|
|
180
187
|
const projectPaths=Object.hasOwn(v,'codeProjectPaths')?validateCodeProjectPaths(v.codeProjectPaths):null;
|
|
181
188
|
if(projectPaths!==null)resolveCodeProjects(v.root,projectPaths.map(prefix=>path.join(root,prefix)));
|
|
@@ -194,23 +201,37 @@ export function captureReviewBaseline(options) {
|
|
|
194
201
|
return sealed({version,kind:'cm-review-baseline',identity:v.identity,rootDigest:sha(root),
|
|
195
202
|
scope,requirements,files,...(specsPath===null?{}:{specsPath}),
|
|
196
203
|
...(projectPaths===null?{}:{codeProjectPaths:projectPaths}),
|
|
197
|
-
...(bootstrap===null?{}:{bootstrapRequirements:bootstrap})
|
|
204
|
+
...(bootstrap===null?{}:{bootstrapRequirements:bootstrap}),
|
|
205
|
+
...(specification===null?{}:{specification,specificationRoot:v.specification.specsRoot})},'baselineDigest');
|
|
198
206
|
}
|
|
199
207
|
|
|
200
208
|
// Bounded selected-file material for pre-implementation reviews; no whole-tree scan.
|
|
201
209
|
export function readReviewSourceFiles(root,selected){
|
|
202
210
|
let total=0;
|
|
203
211
|
const real=rootPath(root),files=paths(selected).map(p=>{
|
|
204
|
-
|
|
205
|
-
for(const part of parts.slice(0,-1)){
|
|
206
|
-
parent=path.join(parent,part);
|
|
207
|
-
const stat=fs.lstatSync(parent);
|
|
208
|
-
need(stat.isDirectory()&&!stat.isSymbolicLink()&&fs.realpathSync(parent)===parent,'unsupported_path');
|
|
209
|
-
}
|
|
212
|
+
sourceParent(real,p);
|
|
210
213
|
const file=readFile(real,p);total+=file.size;need(total<=SNAPSHOT_LIMIT,'limit_exceeded');return file;
|
|
211
214
|
});
|
|
212
215
|
return freeze(files);
|
|
213
216
|
}
|
|
217
|
+
function sourceParent(root,p){
|
|
218
|
+
let parent=root;
|
|
219
|
+
for(const part of p.split('/').slice(0,-1)){
|
|
220
|
+
parent=path.join(parent,part);
|
|
221
|
+
const stat=fs.lstatSync(parent);
|
|
222
|
+
need(stat.isDirectory()&&!stat.isSymbolicLink()&&fs.realpathSync(parent)===parent,'unsupported_path');
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// Retain only a UTF-8 prefix while hashing the entire design, including files
|
|
226
|
+
// larger than the ordinary 1 MiB review-body budget. Never publish a partial file record.
|
|
227
|
+
export function readReviewSourceExcerpt(root,selected,maxBytes){
|
|
228
|
+
need(Number.isSafeInteger(maxBytes)&&maxBytes>0&&maxBytes<=64*1024);
|
|
229
|
+
const real=rootPath(root),p=filePath(selected);sourceParent(real,p);
|
|
230
|
+
const file=readFile(real,p,true,INVENTORY_LIMIT,maxBytes+1);
|
|
231
|
+
const bytes=Buffer.from(file.contentBase64,'base64');let end=Math.min(bytes.length,maxBytes);
|
|
232
|
+
if(file.size>maxBytes)while((bytes[end]&0xc0)===0x80)end--;
|
|
233
|
+
return freeze({path:p,sha256:file.sha256,excerpt:bytes.subarray(0,end).toString('utf8'),truncated:file.size>maxBytes});
|
|
234
|
+
}
|
|
214
235
|
function validateSpecsSelection(specsPath,selections) {
|
|
215
236
|
filePath(specsPath);
|
|
216
237
|
const boundary=specsPath.toLowerCase();
|
|
@@ -247,7 +268,10 @@ function inventoryList(b) {
|
|
|
247
268
|
need(Array.isArray(files)&&files.length<=INVENTORY_COUNT);
|
|
248
269
|
const material=[];let total=0,previous=null;const aliases=new Set();
|
|
249
270
|
for(const f of files){
|
|
250
|
-
|
|
271
|
+
// Legacy dependency records retain their original full bytes and drift checks.
|
|
272
|
+
// Ordinary sparse inventory entries still reject unsolicited bodies.
|
|
273
|
+
const legacyDependency=!Object.hasOwn(b,'specification')&&inDependencyDirectory(f.path)&&Object.hasOwn(f,'contentBase64');
|
|
274
|
+
if(materialPath(f.path,selected)||legacyDependency){fileRecord(f);material.push(f);}
|
|
251
275
|
else{
|
|
252
276
|
keys(f,['path','type','mode','size','sha256']);filePath(f.path);
|
|
253
277
|
need(f.type==='file'&&Number.isInteger(f.mode)&&f.mode>=0&&f.mode<=0o7777);
|
|
@@ -283,10 +307,16 @@ export function readReviewSourceRecords(raw){
|
|
|
283
307
|
function validBaseline(b) {
|
|
284
308
|
try {
|
|
285
309
|
keys(b,['version','kind','identity','rootDigest','scope','requirements','files','baselineDigest',
|
|
286
|
-
...['specsPath','codeProjectPaths','bootstrapRequirements'].filter(key=>Object.hasOwn(b,key))]);
|
|
310
|
+
...['specsPath','codeProjectPaths','bootstrapRequirements','specification','specificationRoot'].filter(key=>Object.hasOwn(b,key))]);
|
|
287
311
|
need([1,2].includes(b.version) && b.kind==='cm-review-baseline'); identityCheck(b.identity); hex(b.rootDigest);
|
|
312
|
+
need(Object.hasOwn(b,'specification')===Object.hasOwn(b,'specificationRoot'));
|
|
313
|
+
if(Object.hasOwn(b,'specification')){
|
|
314
|
+
readSpecificationMaterial(b.specification,b.identity.taskId);
|
|
315
|
+
need(typeof b.specificationRoot==='string'&&path.isAbsolute(b.specificationRoot)
|
|
316
|
+
&&path.resolve(b.specificationRoot)===b.specificationRoot&&!b.specificationRoot.includes('\0'));
|
|
317
|
+
}
|
|
288
318
|
const bootstrap=Object.hasOwn(b,'bootstrapRequirements');if(bootstrap)validBootstrapRequirements(b.bootstrapRequirements);
|
|
289
|
-
need(digest(b.scope)===digest(paths(b.scope)) && digest(b.requirements)===digest(requirementPaths(b.requirements,bootstrap)));
|
|
319
|
+
need(digest(b.scope)===digest(paths(b.scope)) && digest(b.requirements)===digest(requirementPaths(b.requirements,bootstrap||Object.hasOwn(b,'specification'))));
|
|
290
320
|
if(b.version===2)inventoryList(b);
|
|
291
321
|
else if(!bootstrap||b.files.length)fileList(b.files);else need(Array.isArray(b.files));
|
|
292
322
|
need(b.requirements.every(p=>b.files.some(f=>f.path===p)));
|
|
@@ -330,10 +360,13 @@ function validChecks(checks) {
|
|
|
330
360
|
export function createReviewPackage(options) {
|
|
331
361
|
const v=plain(options); keys(v,['root','baseline','checks',...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]); const b=v.baseline;
|
|
332
362
|
validBaseline(b); validChecks(v.checks);
|
|
363
|
+
const specification=Object.hasOwn(b,'specification')?verifySpecificationMaterial(b):null;
|
|
333
364
|
const root=rootPath(v.root); need(sha(root)===b.rootDigest,'invalid_baseline');
|
|
334
365
|
const bootstrap=Object.hasOwn(b,'bootstrapRequirements')?currentBootstrapRequirements(b.bootstrapRequirements):null;
|
|
335
366
|
if(bootstrap!==null)need(reviewSpecsPath(root,b.bootstrapRequirements.specsRoot)===(b.specsPath??null),'bootstrap_requirements_mismatch');
|
|
336
|
-
const
|
|
367
|
+
const selected=b.version===1?null:new Set([...b.scope,...b.requirements,
|
|
368
|
+
...b.files.filter(f=>Object.hasOwn(f,'contentBase64')).map(f=>f.path)]);
|
|
369
|
+
const files=snapshot(root,b.specsPath??null,b.codeProjectPaths??null,b.files.map(f=>f.path),selected),before=new Map(b.files.map(f=>[f.path,f])),after=new Map(files.map(f=>[f.path,f]));
|
|
337
370
|
const changes=[];
|
|
338
371
|
for(const p of [...new Set([...before.keys(),...after.keys()])].sort()) {
|
|
339
372
|
const old=before.get(p)??null,current=after.get(p)??null;
|
|
@@ -341,12 +374,16 @@ export function createReviewPackage(options) {
|
|
|
341
374
|
need(b.scope.includes(p),'out_of_scope'); changes.push({path:p,before:old,after:current});
|
|
342
375
|
}
|
|
343
376
|
need(changes.length>0,'empty_changes');
|
|
377
|
+
const changedPaths=new Set(changes.map(change=>change.path));
|
|
378
|
+
const unchangedScope=b.scope.filter(p=>!changedPaths.has(p)&&after.has(p))
|
|
379
|
+
.map(p=>({path:p,sha256:after.get(p).sha256}));
|
|
344
380
|
const requirements=b.requirements.map(p=>{ need(after.has(p),'read_failed'); return after.get(p); });
|
|
345
381
|
const pkg=sealed({version:1,kind:'cm-review-package',identity:b.identity,rootDigest:b.rootDigest,
|
|
346
|
-
baseIdentity:b.baselineDigest,scope:b.scope,changes,requirements,checks:v.checks,
|
|
382
|
+
baseIdentity:b.baselineDigest,scope:b.scope,changes,unchangedScope,requirements,checks:v.checks,
|
|
347
383
|
...(Object.hasOwn(b,'codeProjectPaths')?{codeProjectPaths:b.codeProjectPaths,
|
|
348
384
|
instructions:files.filter(file=>file.path.split('/').at(-1)==='AGENTS.md')}:{}),
|
|
349
385
|
...(bootstrap===null?{}:{bootstrapRequirements:bootstrap}),
|
|
386
|
+
...(specification===null?{}:{specification}),
|
|
350
387
|
...(Object.hasOwn(v,'handoffPath')?{handoff:readHandoffSnapshot(v.handoffPath)}:{}),
|
|
351
388
|
artifactDigest:digest(changes),requirementsDigest:digest(requirements),checksDigest:digest(v.checks)},'packageDigest');
|
|
352
389
|
need(Buffer.byteLength(JSON.stringify(pkg))<=8*1024*1024,'limit_exceeded');
|
|
@@ -356,6 +393,8 @@ function validPackage(p) {
|
|
|
356
393
|
try {
|
|
357
394
|
keys(p,['version','kind','identity','rootDigest','baseIdentity','scope','changes','requirements',
|
|
358
395
|
'checks','artifactDigest','requirementsDigest','checksDigest','packageDigest',
|
|
396
|
+
...(Object.hasOwn(p,'unchangedScope')?['unchangedScope']:[]),
|
|
397
|
+
...(Object.hasOwn(p,'specification')?['specification']:[]),
|
|
359
398
|
...(Object.hasOwn(p,'handoff')?['handoff']:[]),
|
|
360
399
|
...(Object.hasOwn(p,'codeProjectPaths')?['codeProjectPaths','instructions']:[]),
|
|
361
400
|
...(Object.hasOwn(p,'bootstrapRequirements')?['bootstrapRequirements']:[])]);
|
|
@@ -363,6 +402,7 @@ function validPackage(p) {
|
|
|
363
402
|
fileRecord(p.handoff);need(!p.handoff.path.includes('/')&&p.handoff.size<=256*1024);
|
|
364
403
|
}
|
|
365
404
|
need(p.version===1 && p.kind==='cm-review-package'); identityCheck(p.identity);
|
|
405
|
+
if(Object.hasOwn(p,'specification'))readSpecificationMaterial(p.specification,p.identity.taskId);
|
|
366
406
|
[p.rootDigest,p.baseIdentity,p.artifactDigest,p.requirementsDigest,p.checksDigest,p.packageDigest].forEach(hex);
|
|
367
407
|
need(digest(p.scope)===digest(paths(p.scope)));
|
|
368
408
|
need(Array.isArray(p.changes) && p.changes.length>0 && p.changes.length<=FILE_COUNT);
|
|
@@ -377,7 +417,19 @@ function validPackage(p) {
|
|
|
377
417
|
if(Object.hasOwn(p,'bootstrapRequirements')){
|
|
378
418
|
validBootstrapRequirements(p.bootstrapRequirements,true);
|
|
379
419
|
if(p.requirements.length)fileList(p.requirements);else need(Array.isArray(p.requirements));
|
|
380
|
-
}else fileList(p.requirements);
|
|
420
|
+
}else if(p.requirements.length||!Object.hasOwn(p,'specification'))fileList(p.requirements);
|
|
421
|
+
else need(Array.isArray(p.requirements));
|
|
422
|
+
if(Object.hasOwn(p,'unchangedScope')){
|
|
423
|
+
need(Array.isArray(p.unchangedScope)&&p.unchangedScope.length<=FILE_COUNT);
|
|
424
|
+
for(const file of p.unchangedScope){
|
|
425
|
+
keys(file,['path','sha256']);filePath(file.path);hex(file.sha256);
|
|
426
|
+
need(p.scope.includes(file.path)&&!names.includes(file.path));
|
|
427
|
+
for(const material of [...p.requirements,...(p.instructions??[])])
|
|
428
|
+
if(material.path===file.path)need(material.sha256===file.sha256);
|
|
429
|
+
}
|
|
430
|
+
const unchangedNames=p.unchangedScope.map(file=>file.path);
|
|
431
|
+
if(unchangedNames.length)need(digest(unchangedNames)===digest(paths(unchangedNames)));
|
|
432
|
+
}
|
|
381
433
|
validChecks(p.checks);
|
|
382
434
|
if(Object.hasOwn(p,'codeProjectPaths')){
|
|
383
435
|
need(digest(p.codeProjectPaths)===digest(validateCodeProjectPaths(p.codeProjectPaths)));
|
|
@@ -401,9 +453,15 @@ export function verifyReviewPackage(options) {
|
|
|
401
453
|
...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]);
|
|
402
454
|
hex(v.expectedDigest); validBaseline(v.baseline); validPackage(v.reviewPackage);
|
|
403
455
|
need(v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
|
|
456
|
+
need(Object.hasOwn(v.reviewPackage,'specification')===Object.hasOwn(v.baseline,'specification'),'package_mismatch');
|
|
404
457
|
need(Object.hasOwn(v.reviewPackage,'handoff')===Object.hasOwn(v,'handoffPath'),'package_mismatch');
|
|
405
|
-
|
|
458
|
+
let current=createReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,
|
|
406
459
|
...(Object.hasOwn(v,'handoffPath')?{handoffPath:v.handoffPath}:{})});
|
|
460
|
+
// Rebuild the historical representation for legacy receipts, without rewriting them.
|
|
461
|
+
if(!Object.hasOwn(v.reviewPackage,'unchangedScope')){
|
|
462
|
+
const {unchangedScope,packageDigest,...legacy}=current;
|
|
463
|
+
current=sealed(legacy,'packageDigest');
|
|
464
|
+
}
|
|
407
465
|
need(current.packageDigest===v.expectedDigest,'package_mismatch');
|
|
408
466
|
return freeze({outcome:'matched',packageDigest:current.packageDigest});
|
|
409
467
|
}
|
|
@@ -2,9 +2,13 @@
|
|
|
2
2
|
import { digest,need,shape,id,text,json,freeze } from './effect-contract.mjs';
|
|
3
3
|
export function reviewPaths(pkg) {
|
|
4
4
|
return [...new Set([...pkg.changes.map(c=>c.path),...pkg.requirements.map(f=>f.path),
|
|
5
|
+
...(pkg.unchangedScope??[]).map(file=>file.path),
|
|
5
6
|
...(pkg.instructions??[]).map(file=>file.path),
|
|
6
7
|
...(pkg.bootstrapRequirements?.files??[]).map(file=>'specs:'+file.path)])].sort();
|
|
7
8
|
}
|
|
9
|
+
export function allowedFindingPaths(pkg,paths=reviewPaths(pkg)) {
|
|
10
|
+
return [...paths,pkg.handoff?.path].filter(Boolean);
|
|
11
|
+
}
|
|
8
12
|
export function reviewResult(raw,pkg) {
|
|
9
13
|
return reviewResultForPaths(raw,pkg,reviewPaths(pkg));
|
|
10
14
|
}
|
|
@@ -13,10 +17,18 @@ export function reviewResultForPaths(raw,pkg,paths) {
|
|
|
13
17
|
need(['approved','changes_requested','blocked'].includes(r.verdict));text(r.summary);
|
|
14
18
|
need(r.packageDigest===pkg.packageDigest,'review_package_mismatch');
|
|
15
19
|
need(digest(r.examinedPaths)===digest(paths),'missing_material');
|
|
16
|
-
need(Array.isArray(r.findings) && r.findings.length<=100);
|
|
20
|
+
need(Array.isArray(r.findings) && r.findings.length<=100,'invalid_finding_shape');
|
|
21
|
+
const ids=new Set(),findingPaths=allowedFindingPaths(pkg,paths);
|
|
17
22
|
for(const f of r.findings) {
|
|
18
|
-
shape(f,['id','severity','path','message','evidence']);
|
|
19
|
-
need(
|
|
23
|
+
try {shape(f,['id','severity','path','message','evidence']);}
|
|
24
|
+
catch {need(false,'invalid_finding_shape');}
|
|
25
|
+
try {id(f.id);}
|
|
26
|
+
catch {need(false,'invalid_finding_id');}
|
|
27
|
+
need(!ids.has(f.id),'invalid_finding_shape');ids.add(f.id);
|
|
28
|
+
need(['P0','P1','P2','P3'].includes(f.severity),'invalid_finding_severity');
|
|
29
|
+
need(findingPaths.includes(f.path),'invalid_finding_path');
|
|
30
|
+
try {text(f.message);text(f.evidence);}
|
|
31
|
+
catch {need(false,'invalid_finding_shape');}
|
|
20
32
|
}
|
|
21
33
|
const blocking=r.findings.filter(f=>f.severity!=='P3').length;
|
|
22
34
|
need(r.verdict!=='approved'||blocking===0,'contradictory_verdict');
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Startup runtime selection for CM role failover. This module chooses which
|
|
2
|
+
// runtime a role starts on; it never changes an in-flight task, never edits
|
|
3
|
+
// task state, and never marks a probe-resolvable CLI as quota-available.
|
|
4
|
+
export class RuntimeFailoverError extends Error {
|
|
5
|
+
constructor(message,code){super(message);this.name='RuntimeFailoverError';this.code=code;}
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const RUNTIMES=['codex','claude'];
|
|
9
|
+
|
|
10
|
+
// Role-based primary/standby. Development runs on the large-quota runtime;
|
|
11
|
+
// review keeps the other one primary so N4 stays cross-model against the
|
|
12
|
+
// implementation. Both roles fall back to the opposite runtime.
|
|
13
|
+
export const ROLE_ROUTING=Object.freeze({
|
|
14
|
+
developer:Object.freeze({primary:'codex',standby:'claude'}),
|
|
15
|
+
reviewer:Object.freeze({primary:'claude',standby:'codex'}),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export function isRuntime(value){return RUNTIMES.includes(value);}
|
|
19
|
+
|
|
20
|
+
function requireRole(role){
|
|
21
|
+
if(!Object.hasOwn(ROLE_ROUTING,role))
|
|
22
|
+
throw new RuntimeFailoverError(`unknown failover role: ${role}`,'unknown_role');
|
|
23
|
+
return ROLE_ROUTING[role];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// `probe(runtime)` must report reachability only. A true result means the CLI
|
|
27
|
+
// resolves, never that its quota or authentication will accept the next call.
|
|
28
|
+
function checkProbe(probe){
|
|
29
|
+
if(typeof probe!=='function')
|
|
30
|
+
throw new RuntimeFailoverError('probe must be a function','invalid_probe');
|
|
31
|
+
return (runtime)=>{
|
|
32
|
+
const result=probe(runtime);
|
|
33
|
+
if(typeof result!=='boolean')
|
|
34
|
+
throw new RuntimeFailoverError(`probe must return a boolean for ${runtime}`,'invalid_probe');
|
|
35
|
+
return result;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Ordered candidates: an explicit request wins the first slot, otherwise the
|
|
40
|
+
// role's primary leads. The opposite runtime always trails as the standby.
|
|
41
|
+
export function candidateOrder(role,requested=null){
|
|
42
|
+
const {primary,standby}=requireRole(role);
|
|
43
|
+
if(requested===null)return [primary,standby];
|
|
44
|
+
if(!isRuntime(requested))
|
|
45
|
+
throw new RuntimeFailoverError(`unsupported runtime: ${requested}`,'invalid_runtime');
|
|
46
|
+
return [requested,requested===primary?standby:primary];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Resolve one role to a runtime. Returns the decision plus every rejected
|
|
50
|
+
// candidate and why, so the caller can print the switch instead of hiding it.
|
|
51
|
+
export function selectRuntime({role,requested=null,allowed=RUNTIMES,probe}){
|
|
52
|
+
requireRole(role);
|
|
53
|
+
const test=checkProbe(probe);
|
|
54
|
+
if(!Array.isArray(allowed)||allowed.length===0||!allowed.every(isRuntime))
|
|
55
|
+
throw new RuntimeFailoverError('allowed must be a non-empty list of known runtimes','invalid_allowed');
|
|
56
|
+
const order=candidateOrder(role,requested),rejected=[];
|
|
57
|
+
for(const candidate of order){
|
|
58
|
+
if(!allowed.includes(candidate)){rejected.push({runtime:candidate,reason:'not_allowed'});continue;}
|
|
59
|
+
if(!test(candidate)){rejected.push({runtime:candidate,reason:'unreachable'});continue;}
|
|
60
|
+
const from=requested??order[0];
|
|
61
|
+
return Object.freeze({role,runtime:candidate,switched:candidate!==from,
|
|
62
|
+
from,rejected:Object.freeze(rejected),
|
|
63
|
+
reason:candidate===from?null:`${from} ${rejected.find(r=>r.runtime===from)?.reason??'unavailable'}`});
|
|
64
|
+
}
|
|
65
|
+
throw new RuntimeFailoverError(
|
|
66
|
+
`no runtime available for ${role}: ${rejected.map(r=>`${r.runtime}=${r.reason}`).join(', ')}`,
|
|
67
|
+
'no_runtime_available');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// One human-readable line per switch. Callers must surface this; a silent
|
|
71
|
+
// switch would hide that the work moved to a different model.
|
|
72
|
+
export function describeSelection(selection){
|
|
73
|
+
if(!selection.switched)return `${selection.role}: ${selection.runtime}(未切换)`;
|
|
74
|
+
return `${selection.role}: ${selection.from} → ${selection.runtime}(原因: ${selection.reason})`;
|
|
75
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Host-owned approved specification data. Never a write scope or authority.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {buildManifest,verifyManifest,normalizeRuntimeMarks} from '../../../scripts/cm-spec-manifest.mjs';
|
|
6
|
+
import {parseFeatureTaskText,declaredAcceptanceIds} from './cm-ai-admission.mjs';
|
|
7
|
+
import {readReviewSourceFiles,readReviewSourceExcerpt} from './review-package.mjs';
|
|
8
|
+
import {json,need,shape,hex,freeze,digest} from './effect-contract.mjs';
|
|
9
|
+
|
|
10
|
+
const DESIGN_LIMIT=64*1024;
|
|
11
|
+
const filenames=['requirements.md','design.md','tasks.md','test-cases.json'];
|
|
12
|
+
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
13
|
+
const featureName=value=>need(typeof value==='string'&&/^\d+\.[^/\\\x00-\x1f]+$/.test(value));
|
|
14
|
+
|
|
15
|
+
export function readSpecificationMaterial(raw,taskId){
|
|
16
|
+
const v=json(raw,2*1024*1024);
|
|
17
|
+
shape(v,['feature','task','acceptanceCriteria','designExcerpt','testCases','sources',
|
|
18
|
+
...(Object.hasOwn(v,'truncated')?['truncated']:[])]);
|
|
19
|
+
featureName(v.feature);
|
|
20
|
+
shape(v.task,['id','description',...(Object.hasOwn(v.task,'verification')?['verification']:[])]);
|
|
21
|
+
need(v.task.id===taskId&&/^T-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(taskId));
|
|
22
|
+
need(typeof v.task.description==='string'&&v.task.description.trim().length>0);
|
|
23
|
+
if(Object.hasOwn(v.task,'verification'))need(typeof v.task.verification==='string'&&v.task.verification.length>0);
|
|
24
|
+
need(Array.isArray(v.acceptanceCriteria));
|
|
25
|
+
const ids=new Set();
|
|
26
|
+
for(const ac of v.acceptanceCriteria){
|
|
27
|
+
shape(ac,['id','text']);need(/^AC-\d{3,}$/.test(ac.id)&&!ids.has(ac.id));ids.add(ac.id);
|
|
28
|
+
need(typeof ac.text==='string'&&ac.text.length>0);
|
|
29
|
+
}
|
|
30
|
+
need(typeof v.designExcerpt==='string'&&Buffer.byteLength(v.designExcerpt)<=DESIGN_LIMIT);
|
|
31
|
+
if(Object.hasOwn(v,'truncated'))need(v.truncated===true);
|
|
32
|
+
need(Array.isArray(v.testCases)&&v.testCases.every(item=>item&&Array.isArray(item.taskIds)&&item.taskIds.includes(taskId)));
|
|
33
|
+
need(Array.isArray(v.sources)&&[3,4].includes(v.sources.length));
|
|
34
|
+
const expected=filenames.slice(0,v.sources.length).map(name=>`${v.feature}/${name}`).sort();
|
|
35
|
+
need(JSON.stringify(v.sources.map(item=>item.path))===JSON.stringify(expected));
|
|
36
|
+
for(const item of v.sources){shape(item,['path','sha256']);hex(item.sha256);}
|
|
37
|
+
if(v.sources.length===3)need(v.testCases.length===0);
|
|
38
|
+
return freeze(v);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function verificationFor(source,taskId){
|
|
42
|
+
let level=null;const lines=[];
|
|
43
|
+
for(const line of source.split(/\r?\n/)){
|
|
44
|
+
const heading=/^\s*(#{1,6})\s+(.+)$/.exec(line);
|
|
45
|
+
if(heading){
|
|
46
|
+
if(level!==null&&heading[1].length<=level)level=null;
|
|
47
|
+
if(heading[2].includes('验证要求'))level=heading[1].length;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if(level!==null&&line.split(/[^A-Za-z0-9._-]+/).includes(taskId))lines.push(line.trim());
|
|
51
|
+
}
|
|
52
|
+
return lines.join('\n');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function captureSpecificationMaterial({specsRoot,feature,taskId}){
|
|
56
|
+
try{
|
|
57
|
+
featureName(feature);
|
|
58
|
+
need(path.isAbsolute(specsRoot)&&fs.realpathSync(specsRoot)===specsRoot);
|
|
59
|
+
const statusPath=path.join(specsRoot,'.cm-specs-status');
|
|
60
|
+
const statusRecord=readReviewSourceFiles(specsRoot,['.cm-specs-status'])[0];
|
|
61
|
+
const status=JSON.parse(Buffer.from(statusRecord.contentBase64,'base64').toString('utf8'));
|
|
62
|
+
need(status.status==='approved'&&Array.isArray(status.features)&&status.features.includes(feature));
|
|
63
|
+
const manifest=buildManifest(specsRoot);verifyManifest(manifest,statusPath);
|
|
64
|
+
need(JSON.stringify([...status.features].sort())===JSON.stringify([...new Set(manifest.map(row=>row.path.split('/')[0]))].sort()));
|
|
65
|
+
const sources=manifest.filter(row=>row.path.startsWith(feature+'/'));
|
|
66
|
+
const designPath=feature+'/design.md';
|
|
67
|
+
const records=readReviewSourceFiles(specsRoot,sources.map(row=>row.path).filter(p=>p!==designPath)),texts={};
|
|
68
|
+
const design=readReviewSourceExcerpt(specsRoot,designPath,DESIGN_LIMIT);
|
|
69
|
+
need(design.sha256===sources.find(row=>row.path===designPath)?.sha256);
|
|
70
|
+
for(const record of records){
|
|
71
|
+
const name=path.basename(record.path),bytes=Buffer.from(record.contentBase64,'base64');
|
|
72
|
+
// Hash the very bytes that supply the material, using the existing runtime-mark contract.
|
|
73
|
+
const normalized=Buffer.from(normalizeRuntimeMarks(bytes.toString('latin1'),name),'latin1');
|
|
74
|
+
need(hash(normalized)===sources.find(row=>row.path===record.path)?.sha256);
|
|
75
|
+
texts[name]=normalizeRuntimeMarks(bytes.toString('utf8'),name);
|
|
76
|
+
}
|
|
77
|
+
need(readReviewSourceFiles(specsRoot,['.cm-specs-status'])[0].sha256===statusRecord.sha256);
|
|
78
|
+
verifyManifest(buildManifest(specsRoot),statusPath);
|
|
79
|
+
const parsed=parseFeatureTaskText(texts['tasks.md'],{allowDependencyPunctuation:true});
|
|
80
|
+
need(!parsed.error);
|
|
81
|
+
const selected=parsed.tasks.find(task=>task.id===taskId&&!task.dropped);need(selected);
|
|
82
|
+
const verification=verificationFor(texts['tasks.md'],taskId);
|
|
83
|
+
const task={id:taskId,description:selected.description,...(verification?{verification}:{})};
|
|
84
|
+
const acceptanceCriteria=texts['requirements.md'].split(/\r?\n/).flatMap(line=>
|
|
85
|
+
[...declaredAcceptanceIds(line)].map(id=>({id,text:line.trim()})));
|
|
86
|
+
const cases=texts['test-cases.json']===undefined?[]:JSON.parse(texts['test-cases.json']).cases;
|
|
87
|
+
need(Array.isArray(cases)&&cases.every(item=>item&&Array.isArray(item.taskIds)));
|
|
88
|
+
return readSpecificationMaterial({feature,task,acceptanceCriteria,designExcerpt:design.excerpt,
|
|
89
|
+
...(design.truncated?{truncated:true}:{}),testCases:cases.filter(item=>item.taskIds.includes(taskId)),sources},taskId);
|
|
90
|
+
}catch{throw Object.assign(new Error('spec_drift'),{code:'spec_drift'});}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function verifySpecificationMaterial(baseline){
|
|
94
|
+
const current=captureSpecificationMaterial({specsRoot:baseline.specificationRoot,
|
|
95
|
+
feature:baseline.specification.feature,taskId:baseline.identity.taskId});
|
|
96
|
+
need(digest(current)===digest(baseline.specification),'spec_drift');
|
|
97
|
+
return baseline.specification;
|
|
98
|
+
}
|