@aibyzero/cm-workflow 0.12.0 → 0.13.3
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 +1 -0
- package/CHANGELOG.md +60 -1
- package/README.md +36 -3
- package/VERSION +1 -1
- package/compat/claude-commands/cm-runtime.md +3 -0
- package/docs/installation.md +58 -1
- package/docs/js-workflow-control.md +63 -6
- package/docs/runtime-failover.md +97 -0
- package/docs/user-guide.md +50 -1
- package/install-codex.sh +5 -0
- package/install.ps1 +10 -2
- package/install.sh +5 -0
- package/package.json +2 -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/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 +9 -2
- 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 +527 -6
- package/scripts/cm-ai-multi-root.test.mjs +16 -4
- package/scripts/cm-ai-nested-execution.test.mjs +18 -5
- 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 +8 -2
- package/scripts/cm-check-runtime.sh +51 -1
- 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-fix-host-review.test.mjs +7 -1
- 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 +9 -3
- 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-i18n.mjs +32 -0
- package/scripts/cm-runtime-install.mjs +68 -0
- package/scripts/cm-runtime.mjs +141 -0
- package/scripts/cm-runtime.test.mjs +218 -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 +5 -0
- 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 +7 -3
- 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 +53 -0
- package/templates/auto-update/cm-update.sh +1 -1
- package/templates/cm-workflow.yml +16 -0
|
@@ -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
|
+
}
|
|
@@ -1,17 +1,19 @@
|
|
|
1
|
+
import {readQaAttachment} from './qa-attachment.mjs';
|
|
1
2
|
// Trusted synthetic fixture host; explicit V2 supports isolated task-file writes.
|
|
2
3
|
import { randomUUID } from 'node:crypto';
|
|
3
4
|
import { types } from 'node:util';
|
|
4
5
|
import fs from 'node:fs';
|
|
5
6
|
import path from 'node:path';
|
|
6
7
|
import {createRequire} from 'node:module';
|
|
8
|
+
import {verifySpecificationMaterial} from './specification-material.mjs';
|
|
7
9
|
import { captureReviewBaseline, createReviewPackage, verifyReviewPackage } from './review-package.mjs';
|
|
8
10
|
import { digest,need,shape,id,text,json,freeze,arrayItems,validIdentity,validTaskLearningInput,validCallTimeout,requestFor,terminalFor,failureCode } from './effect-contract.mjs';
|
|
9
11
|
import { reviewResult,reviewReceipt } from './review-runner.mjs';
|
|
10
12
|
import { checkCompletion } from './gate-bridge.mjs';
|
|
11
13
|
import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
|
|
12
|
-
controlledState,validateReviewDispatchGrant,validateTaskLearningReviewPackage } from './durable-runner-state.mjs';
|
|
14
|
+
controlledState,stageAllowed,completedEffectCount,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage } from './durable-runner-state.mjs';
|
|
13
15
|
import {commitRunnerFixture} from './task-commit.mjs';
|
|
14
|
-
import {inspectProviderReview} from './provider-review-observation.mjs';
|
|
16
|
+
import {inspectProviderReview,hasProviderReviewResult} from './provider-review-observation.mjs';
|
|
15
17
|
import {attachCmAiTaskLearningApplicationEvidence,attachCmAiTaskLearningEvidence,
|
|
16
18
|
readCmAiTaskLearningApplication} from './cm-ai-context-refresh.mjs';
|
|
17
19
|
import {readCmAiProjectLearningWriteback,writeCmAiProjectLearning} from './cm-ai-learning-writer.mjs';
|
|
@@ -87,6 +89,7 @@ export function createTaskRunner(options) {
|
|
|
87
89
|
if(options && Object.hasOwn(options,'timeoutMs'))optionKeys.push('timeoutMs');
|
|
88
90
|
if(options && Object.hasOwn(options,'persistence'))optionKeys.push('persistence');
|
|
89
91
|
if(options && Object.hasOwn(options,'taskLearning'))optionKeys.push('taskLearning');
|
|
92
|
+
if(options && Object.hasOwn(options,'specification'))optionKeys.push('specification');
|
|
90
93
|
if(options && Object.hasOwn(options,'bootstrap'))optionKeys.push('bootstrap');
|
|
91
94
|
if(options && Object.hasOwn(options,'codeProjectPaths'))optionKeys.push('codeProjectPaths');
|
|
92
95
|
if(invocationMode)optionKeys.push('reviewInvocation');
|
|
@@ -170,13 +173,22 @@ export function createTaskRunner(options) {
|
|
|
170
173
|
if(options.persistence.mode==='resume')restored=readRunnerHistory(journal,metadata,version);
|
|
171
174
|
else need(journal.length===0,'runner_exists');
|
|
172
175
|
}
|
|
173
|
-
const
|
|
176
|
+
const specificationSelection=options.specification??null;
|
|
177
|
+
if(specificationSelection!==null){
|
|
178
|
+
shape(specificationSelection,['specsRoot','feature']);
|
|
179
|
+
need(completion&&specificationSelection.specsRoot===completion.owner.specsRoot
|
|
180
|
+
&&specificationSelection.feature===taskLearning?.feature,'spec_drift');
|
|
181
|
+
}
|
|
182
|
+
const baselineOptions=()=>({...configToBaseline(metadata),
|
|
183
|
+
...(specificationSelection===null?{}:{specification:specificationSelection})});
|
|
184
|
+
const original=restored?.original??captureReviewBaseline(baselineOptions());
|
|
174
185
|
const controller=new AbortController(),calls=[],cache=new Map(),session=restored?.session??randomUUID(),registered=new Map(),receipts=[];
|
|
175
186
|
let state=reviewers.some(r=>r.allowed&&r.available)?'ready':'pending_review',code=null,attempt=1;
|
|
176
187
|
let busy=false,pending=null,sequence=0,base=original,reviewPackage=null,currentChecks=null,workflowRunning=false;
|
|
177
188
|
let receipt=null,priorReview=null,cancelAfterCommit=false,workflowError=null,cancellationRequested=false,reviewInvocation=null;
|
|
178
189
|
let learningResult=null;
|
|
179
190
|
const acceptedFixes=structuredClone(restored?.acceptedFixes??[]);
|
|
191
|
+
let qaAttachment=restored?.qaAttachment??null;
|
|
180
192
|
const handoffBinding=(pkg=reviewPackage)=>pkg&&Object.hasOwn(pkg,'handoff')
|
|
181
193
|
?{handoffPath:completion.handoffs[pkg.identity.attempt-1]}:{};
|
|
182
194
|
function publishRegisteredReview(inspectOnly=false){
|
|
@@ -235,7 +247,7 @@ export function createTaskRunner(options) {
|
|
|
235
247
|
kind:{init:'result','effect-intent':'intent','effect-checkpoint':'result',control:'cancel',
|
|
236
248
|
'task-commit-intent':'commit-intent','task-commit-result':'commit-result',
|
|
237
249
|
'review-invocation-registered':'intent','review-invocation-started':'result','review-invocation-result':'result',
|
|
238
|
-
'qa-fix-accepted':'result'}[type],
|
|
250
|
+
'qa-fix-accepted':'result','qa-attached':'result'}[type],
|
|
239
251
|
payload:version===3?runnerPayloadV3(type,fields):runnerPayload(type,fields,version)};
|
|
240
252
|
const body={version:1,seq:journal.length+1,...basic,previousDigest:journal.at(-1)?.digest??null};
|
|
241
253
|
const record={...body,digest:digest(body)};boundRunnerRecord(record,body.seq);
|
|
@@ -359,6 +371,7 @@ export function createTaskRunner(options) {
|
|
|
359
371
|
try {
|
|
360
372
|
const response=terminalFor(await bounded(adapter.run,request),request);active();
|
|
361
373
|
call.terminal=response.status;call.effectiveModel=response.effectiveModel;call.resultDigest=digest(response.result);
|
|
374
|
+
if(role==='developer'&&response.status==='failed'&&response.result!==null)call.failureResult=response.result;
|
|
362
375
|
if(Object.hasOwn(response,'providerThreadId'))call.providerThreadId=response.providerThreadId;
|
|
363
376
|
return {request,response,call};
|
|
364
377
|
} catch(error){call.terminal=state==='cancelled'?'cancelled':'unknown';throw error;}
|
|
@@ -492,8 +505,12 @@ export function createTaskRunner(options) {
|
|
|
492
505
|
sealed=true;
|
|
493
506
|
let fields;
|
|
494
507
|
if(invalid){fields=invalidFields();}
|
|
495
|
-
else if(timedOut){
|
|
496
|
-
observation
|
|
508
|
+
else if(timedOut){
|
|
509
|
+
const recorded=observation({status:'failed',code:'timeout'});
|
|
510
|
+
fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'timed_out',
|
|
511
|
+
observation:recorded,inspection:inspectProviderReview(JSON.stringify(recorded),JSON.stringify(expectation)),
|
|
512
|
+
reconciliationRequired:hasProviderReviewResult(recorded.events)};
|
|
513
|
+
}
|
|
497
514
|
else if(state==='cancelled'){fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'cancelled',
|
|
498
515
|
observation:observation({status:'cancelled',code:'cancelled'}),inspection:null,reconciliationRequired:true};}
|
|
499
516
|
else {
|
|
@@ -501,9 +518,11 @@ export function createTaskRunner(options) {
|
|
|
501
518
|
fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'unknown',observation:recorded,inspection,reconciliationRequired:true};
|
|
502
519
|
}
|
|
503
520
|
persist('review-invocation-result',fields);const result=resultView(fields);
|
|
504
|
-
|
|
521
|
+
const retry=reviewTimeoutTransition(result,[...cache.values()],attempt);
|
|
522
|
+
Object.assign(call,{terminal:fields.outcome==='cancelled'?'cancelled':retry?'failed':'unknown',resultDigest:digest(result)});
|
|
505
523
|
reviewInvocation=json({registration,started,result});
|
|
506
524
|
if(fields.outcome==='cancelled')halt('cancelled','cancelled');
|
|
525
|
+
else if(retry)halt(retry.state,retry.code);
|
|
507
526
|
else halt('unknown',fields.reason??fields.inspection?.code??'reconciliation_required');return;
|
|
508
527
|
}
|
|
509
528
|
sealed=true;
|
|
@@ -528,12 +547,15 @@ export function createTaskRunner(options) {
|
|
|
528
547
|
halt('unknown','observation_invalid');return;
|
|
529
548
|
}
|
|
530
549
|
const observed=inspection.observationStatus==='completed';
|
|
531
|
-
const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:observed?'observed':'unknown',
|
|
532
|
-
observation:recorded,inspection,reconciliationRequired:!observed
|
|
550
|
+
const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:observed?'observed':inspection.code==='transport_timeout'?'timed_out':'unknown',
|
|
551
|
+
observation:recorded,inspection,reconciliationRequired:!observed
|
|
552
|
+
&&(inspection.code!=='transport_timeout'||hasProviderReviewResult(recorded.events))};
|
|
533
553
|
persist('review-invocation-result',fields);const result=resultView(fields);
|
|
534
|
-
|
|
554
|
+
const retry=reviewTimeoutTransition(result,[...cache.values()],attempt);
|
|
555
|
+
Object.assign(call,{terminal:observed?'succeeded':retry?'failed':'unknown',resultDigest:digest(observed?inspection.review:result)});
|
|
535
556
|
reviewInvocation=json({registration,started,result});
|
|
536
557
|
if(observed)acceptReview(request,call,inspection.review);
|
|
558
|
+
else if(retry)halt(retry.state,retry.code);
|
|
537
559
|
else halt('unknown',inspection.code??'reconciliation_required');
|
|
538
560
|
}finally{sealed=true;clearTimeout(timer);controller.signal.removeEventListener('abort',abort);
|
|
539
561
|
if(cancelReject)controller.signal.removeEventListener('abort',cancelReject);}
|
|
@@ -541,7 +563,7 @@ export function createTaskRunner(options) {
|
|
|
541
563
|
async function collectChecks(){return json(await bounded(check,json({identity:{...config.identity,attempt}})));}
|
|
542
564
|
async function perform(v) {
|
|
543
565
|
if(v.kind==='develop') {
|
|
544
|
-
need(
|
|
566
|
+
need(stageAllowed('develop',state,code),'stage_mismatch');state='developing';code=null;receipt=null;
|
|
545
567
|
const previousBootstrap=learningResult?.bootstrap??null;
|
|
546
568
|
const previousWriteback=learningResult?.writeback??null;
|
|
547
569
|
if(taskLearning!==null)learningResult=null;
|
|
@@ -549,8 +571,15 @@ export function createTaskRunner(options) {
|
|
|
549
571
|
bootstrap.run(request,control,developer.run,{previous:previousBootstrap,previousWriteback,baseline:original})};
|
|
550
572
|
const result=await invoke(adapter,'developer',developer.contextId,{scope:config.scope,
|
|
551
573
|
requirements:original.files.filter(f=>config.requirements.includes(f.path)),priorReview,
|
|
574
|
+
...(Object.hasOwn(original,'specification')?{specification:verifySpecificationMaterial(original)}:{}),
|
|
552
575
|
...(Object.hasOwn(v,'learningInput')?{learningInput:v.learningInput}:{})});
|
|
553
|
-
if(
|
|
576
|
+
if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
|
|
577
|
+
if(result.response.status!=='succeeded'){
|
|
578
|
+
const failure=result.response.result?.code;
|
|
579
|
+
halt(result.response.status==='unknown'?'unknown':'blocked',
|
|
580
|
+
failure==='invalid_result'&&result.response.result.retryable===true?'developer_result_invalid':
|
|
581
|
+
failure==='protected_edit_stale'?failure:result.response.status);return;
|
|
582
|
+
}
|
|
554
583
|
if(taskLearning===null)shape(result.response.result,['outcome']);
|
|
555
584
|
else {
|
|
556
585
|
const instructionBootstrap=metadata.bootstrap?.mode==='instructions';
|
|
@@ -651,24 +680,25 @@ export function createTaskRunner(options) {
|
|
|
651
680
|
if(old){need(old.digest===digest(v),'intent_conflict');return Promise.resolve(old.result);}
|
|
652
681
|
if(restored?.pending?.id===v.id){need(digest(restored.pending)===digest(v),'intent_conflict');return Promise.resolve(status());}
|
|
653
682
|
need(!busy,'busy');need(v.identity.attempt===attempt,'attempt_mismatch');
|
|
654
|
-
|
|
655
|
-
|
|
683
|
+
need(stageAllowed(v.kind,state,code),'stage_mismatch');need(completedEffectCount([...cache.values()])<6,'limit_exceeded');
|
|
684
|
+
if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
|
|
656
685
|
if(v.kind==='develop'&&bootstrap!==null)bootstrap.assertWriteAuthorized();
|
|
657
686
|
} catch(error){return Promise.resolve(freeze({outcome:'rejected',code:error.code??'invalid_input'}));}
|
|
658
687
|
if(store) {
|
|
659
688
|
try {
|
|
660
|
-
if(state==='ready')need(digest(captureReviewBaseline({...configToBaseline(metadata),version:original.version
|
|
661
|
-
|
|
689
|
+
if(state==='ready')need(digest(captureReviewBaseline({...configToBaseline(metadata),version:original.version,
|
|
690
|
+
...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})}))===digest(original),'package_mismatch');
|
|
691
|
+
else if(!(v.kind==='develop'&&state==='blocked'&&code==='developer_result_invalid'))verifyReviewPackage({root:config.root,baseline:state==='changes_requested'?attemptBaseline(original,attempt-1):base,
|
|
662
692
|
checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
|
|
663
693
|
} catch {return Promise.resolve(freeze({outcome:'rejected',code:'package_mismatch'}));}
|
|
664
694
|
try{const record=persist('effect-intent',{effect:v});
|
|
665
695
|
if(taskMode&&v.kind==='complete')completeEffect={effect:v,digest:record.digest};
|
|
666
696
|
}catch{return Promise.resolve(poison());}
|
|
667
697
|
}
|
|
668
|
-
busy=true;code=null;
|
|
698
|
+
busy=true;if(v.kind!=='develop')code=null;
|
|
669
699
|
pending=(async()=>{
|
|
670
700
|
try {await perform(v);}
|
|
671
|
-
catch(error){if(state!=='cancelled')halt('unknown',failureCode(error));}
|
|
701
|
+
catch(error){if(state!=='cancelled')halt(error.code==='spec_drift'?'blocked':'unknown',failureCode(error));}
|
|
672
702
|
if(poisoned)return status();
|
|
673
703
|
const result=privateStatus();cache.set(v.id,{effect:v,digest:digest(v),result});
|
|
674
704
|
try{persist('effect-checkpoint',{effectId:v.id,checkpoint:frame()});publication=result;return result;}
|
|
@@ -693,7 +723,7 @@ export function createTaskRunner(options) {
|
|
|
693
723
|
function currentLearningInput() {
|
|
694
724
|
const currentIdentity={...config.identity,attempt};
|
|
695
725
|
const develop=[...cache.values()].filter(entry=>entry.effect.kind==='develop'
|
|
696
|
-
&&digest(entry.effect.identity)===digest(currentIdentity));
|
|
726
|
+
&&digest(entry.effect.identity)===digest(currentIdentity)&&entry.result.state==='awaiting_review');
|
|
697
727
|
need(develop.length===1&&Object.hasOwn(develop[0].effect,'learningInput'),'runner_learning');
|
|
698
728
|
return develop[0].effect.learningInput;
|
|
699
729
|
}
|
|
@@ -752,7 +782,14 @@ export function createTaskRunner(options) {
|
|
|
752
782
|
persist('qa-fix-accepted',{record});acceptedFixes.push(record);
|
|
753
783
|
return json(record,12*1024*1024);
|
|
754
784
|
};
|
|
755
|
-
const
|
|
785
|
+
const attachQa=raw=>{
|
|
786
|
+
need(invocationMode&&store&&!busy&&!poisoned,'qa_attach_unavailable');
|
|
787
|
+
const record=readQaAttachment(raw);
|
|
788
|
+
if(qaAttachment){need(digest(record)===digest(qaAttachment),'fingerprint_mismatch');return json(qaAttachment);}
|
|
789
|
+
need(state==='fixture_completed','qa_attach_not_completed');
|
|
790
|
+
persist('qa-attached',{record});qaAttachment=record;return json(record);
|
|
791
|
+
};
|
|
792
|
+
const api={executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa};
|
|
756
793
|
if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
|
|
757
794
|
if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
|
|
758
795
|
return Object.freeze(api);
|