@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
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {buildManifest} from './cm-spec-manifest.mjs';
|
|
1
2
|
import test from 'node:test';
|
|
2
3
|
import assert from 'node:assert/strict';
|
|
3
4
|
import fs from 'node:fs';
|
|
@@ -141,14 +142,15 @@ test('a selected root may contain protected specs but specs cannot be a selected
|
|
|
141
142
|
assert.throws(()=>captureReviewBaseline({...options,specsRoot,codeProjectPaths:['apps/api/specs']}),{code:'protected_specs'});
|
|
142
143
|
});
|
|
143
144
|
|
|
144
|
-
test('
|
|
145
|
+
test('single-root baseline stays unchanged and new package binds an empty unchanged scope',t=>{
|
|
145
146
|
const {root}=fixture(t),single=path.join(root,'apps/api');
|
|
146
147
|
const baseline=captureReviewBaseline({root:single,identity,scope:['source.mjs'],requirements:['requirement.md']});
|
|
147
148
|
assert.deepEqual(Object.keys(baseline).sort(),['version','kind','identity','rootDigest','scope','requirements','files','baselineDigest'].sort());
|
|
148
149
|
assert.deepEqual(baseline,resign(baseline,'baselineDigest'));
|
|
149
150
|
write(single,'source.mjs','changed\n');const pkg=createReviewPackage({root:single,baseline,checks});
|
|
150
|
-
assert.deepEqual(Object.keys(pkg).sort(),['version','kind','identity','rootDigest','baseIdentity','scope','changes','requirements','checks',
|
|
151
|
+
assert.deepEqual(Object.keys(pkg).sort(),['version','kind','identity','rootDigest','baseIdentity','scope','changes','unchangedScope','requirements','checks',
|
|
151
152
|
'artifactDigest','requirementsDigest','checksDigest','packageDigest'].sort());
|
|
153
|
+
assert.deepEqual(pkg.unchangedScope,[]);
|
|
152
154
|
assert.equal(verifyReviewPackage({root:single,baseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
|
|
153
155
|
});
|
|
154
156
|
|
|
@@ -206,7 +208,7 @@ test('integrated original multi-root conversation completes one task and resumes
|
|
|
206
208
|
{skip:process.platform!=='darwin'||Number(process.versions.node.split('.')[0])<24,timeout:45000},t=>{
|
|
207
209
|
const {root,codeProjects,options}=fixture(t),specsDir=options.specsRoot;
|
|
208
210
|
for(const name of ['requirements.md','design.md'])write(specsDir,`1.feature/${name}`,'# Approved synthetic two-root task\n');
|
|
209
|
-
write(specsDir,'.cm-specs-status',JSON.stringify({status:'approved',features:['1.feature']}));
|
|
211
|
+
write(specsDir,'.cm-specs-status',JSON.stringify({status:'approved',features:['1.feature'],specFiles:buildManifest(specsDir)}));
|
|
210
212
|
write(root,'.cm-workflow.json',JSON.stringify({version:1,policies:{delivery:'diff'}}));
|
|
211
213
|
const selected=resolveCodeProjects(root,codeProjects),definition={version:1,specsDir,codeProject:root,
|
|
212
214
|
codeProjects:selected,feature:'1.feature',identity,scope:options.scope,requirements:options.requirements};
|
|
@@ -230,6 +232,8 @@ test('integrated original multi-root conversation completes one task and resumes
|
|
|
230
232
|
const bridge={async call(kind,payload){calls.push(kind);
|
|
231
233
|
if(kind==='develop'){
|
|
232
234
|
assert.equal(mode,'create');assert.deepEqual(payload.request.identity,definition.identity);
|
|
235
|
+
assert.equal(payload.request.payload.specification.feature,definition.feature);
|
|
236
|
+
assert.equal(payload.request.payload.specification.task.id,definition.identity.taskId);
|
|
233
237
|
assert.equal(payload.codeProject,definition.codeProject);assert.deepEqual(payload.codeProjects,definition.codeProjects);
|
|
234
238
|
assert.deepEqual(payload.request.payload.scope,definition.scope);assert.equal(payload.editMode,'protected-text-v1');
|
|
235
239
|
assert.deepEqual(payload.projectInstructions.map(row=>row.codeProject),definition.codeProjects);
|
|
@@ -266,6 +270,8 @@ test('integrated original multi-root conversation completes one task and resumes
|
|
|
266
270
|
};
|
|
267
271
|
const initialPackages=packages(state());assert(initialPackages.length>0);
|
|
268
272
|
const pkg=initialPackages.at(-1);
|
|
273
|
+
assert.equal(pkg.specification.task.id,identity.taskId);
|
|
274
|
+
assert.deepEqual(pkg.specification.sources,buildManifest(specsDir));
|
|
269
275
|
assert.deepEqual(pkg.identity,identity);assert.deepEqual(pkg.codeProjectPaths,['apps/api','apps/web']);
|
|
270
276
|
assert.deepEqual(pkg.changes.map(row=>row.path),options.scope);assert.equal(pkg.checks.length,2);
|
|
271
277
|
for(const [index,codeProject] of selected.entries())assert(pkg.checks[index].evidence.includes(`cwd=${codeProject};`));
|
|
@@ -8,6 +8,8 @@ import {fileURLToPath} from 'node:url';
|
|
|
8
8
|
import {createCodexExecution,openControlRun} from './cm-ai-run.mjs';
|
|
9
9
|
import {createConversationExecution,conversationProtection} from './cm-ai-host.mjs';
|
|
10
10
|
import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
|
|
11
|
+
import {buildManifest} from './cm-spec-manifest.mjs';
|
|
12
|
+
import {loadConfig,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
|
|
11
13
|
|
|
12
14
|
const supported=process.platform==='darwin'&&Number(process.versions.node.split('.')[0])>=24;
|
|
13
15
|
const identity={repositoryId:'fixture',runId:'nested-run',taskId:'T-001',attempt:1};
|
|
@@ -54,10 +56,11 @@ async function fixture(fn){
|
|
|
54
56
|
fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
|
|
55
57
|
fs.writeFileSync(path.join(codeProject,'a.js'),'old\n');
|
|
56
58
|
fs.writeFileSync(path.join(codeProject,'requirements.md'),'Synthetic requirement\n');
|
|
59
|
+
fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,runtimes:{available:'codex'}}));
|
|
57
60
|
fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'# Requirements\n');
|
|
58
61
|
fs.writeFileSync(path.join(specsDir,feature,'design.md'),'# Design\n');
|
|
59
62
|
fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement\n');
|
|
60
|
-
fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature]}));
|
|
63
|
+
fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
|
|
61
64
|
const definition={version:1,codeProject,specsDir,feature,identity,scope:['a.js'],requirements:['requirements.md']};
|
|
62
65
|
const config={codeProject,specsRoot:specsDir,developerModel:'synthetic',reviewerModel:'synthetic',hostContextId:'host',
|
|
63
66
|
developerContextId:'author',timeoutMs:5000,
|
|
@@ -127,7 +130,7 @@ for(const launch of ['factory','host','revision','workflow'])test(`${launch}: sy
|
|
|
127
130
|
{skip:!supported},()=>fixture(async({root,definition,config,authority})=>{
|
|
128
131
|
if(launch==='workflow'){
|
|
129
132
|
definition.scope.push('README.md');fs.writeFileSync(path.join(definition.codeProject,'README.md'),'# Old\n');
|
|
130
|
-
fs.writeFileSync(path.join(definition.codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
|
|
133
|
+
fs.writeFileSync(path.join(definition.codeProject,'.cm-workflow.json'),JSON.stringify({version:1,runtimes:{available:'codex'},policies:{delivery:'diff'}}));
|
|
131
134
|
}
|
|
132
135
|
// Never execute real `codex exec`: the shim emits synthetic provider events.
|
|
133
136
|
// It forwards only sandbox commands to the installed native sandbox.
|
|
@@ -172,7 +175,7 @@ let input='';process.stdin.on('data',chunk=>input+=chunk);process.stdin.on('end'
|
|
|
172
175
|
emit({type:'turn.completed'});return;
|
|
173
176
|
}
|
|
174
177
|
a(input.includes('<cm-developer-data-json>'));fs.appendFileSync(${JSON.stringify(calls)},'developer\n');
|
|
175
|
-
if(${launch==='workflow'}){a(input.includes('
|
|
178
|
+
if(${launch==='workflow'}){a(input.includes('Synchronize approved documentation inside this invocation:'));a(input.includes('["README.md"]'));}
|
|
176
179
|
const run=cp.spawnSync(real,['sandbox','-P','cm-specs','--include-managed-config','-C',process.cwd(),...profile,'--',${JSON.stringify(process.execPath)},'-e',${JSON.stringify(code)}],{encoding:'utf8'});
|
|
177
180
|
if(run.status!==0){process.stderr.write(run.stderr??'');process.exit(1);}
|
|
178
181
|
emit({type:'thread.started',thread_id:'synthetic-protected-author'});emit({type:'turn.started'});
|
|
@@ -297,10 +300,14 @@ test('ordinary protected entry rejects missing authority and unsupported combina
|
|
|
297
300
|
fs.writeFileSync(protectedFile,JSON.stringify({model:config.developerModel,checkCommands:config.checkCommands,timeoutMs:config.timeoutMs}));
|
|
298
301
|
fs.writeFileSync(reviewFile,JSON.stringify({model:config.reviewerModel,preflight:config.reviewerPreflight}));
|
|
299
302
|
const protectedArgs=['--protected-config',protectedFile],authorization=['--allow-provider-development-attempt','1'];
|
|
303
|
+
// Claude hosts are supported; this fixture's Codex-only declaration rejects
|
|
304
|
+
// a current-ai Claude coder. The CLI intentionally sanitizes ConfigError.
|
|
305
|
+
assert.throws(()=>resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),'claude'),
|
|
306
|
+
{message:'runtime_not_declared'});
|
|
300
307
|
const unsafeFix=path.join(root,'unsafe-fix.json');fs.writeFileSync(unsafeFix,JSON.stringify({configuration:{}}));
|
|
301
308
|
for(const [flags,code] of [[protectedArgs,'provider_development_authorization_required'],
|
|
302
309
|
[authorization,'protected_configuration_required'],
|
|
303
|
-
[[...protectedArgs,...authorization,'--runtime','claude'],'
|
|
310
|
+
[[...protectedArgs,...authorization,'--runtime','claude'],'host_launch_failed'],
|
|
304
311
|
[[...protectedArgs,'--allow-provider-development-attempt','2'],'invalid_development_attempt'],
|
|
305
312
|
[[...protectedArgs,...authorization,'--qa-fix-owner-config',unsafeFix],'protected_fix_required'],
|
|
306
313
|
[[], 'nested_specs_protection_required']]){
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {createTaskRunner} from '../runtime/js/cm-ai/task-runner.mjs';
|
|
7
|
+
import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
|
|
8
|
+
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
9
|
+
import {readRunnerHistory,runnerStatus,completedEffectCount} from '../runtime/js/cm-ai/durable-runner-state.mjs';
|
|
10
|
+
import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
const checks=[{id:'check',command:['synthetic'],outcome:'passed',exitCode:0,evidence:'fixture'}];
|
|
16
|
+
const grantFor=(request,authorizationAt,change=grant=>grant)=>{
|
|
17
|
+
const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${request.invocationId}`,adapterId:`${request.provider}-review-adapter`,
|
|
18
|
+
invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,
|
|
19
|
+
reviewerId:'reviewer',logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,
|
|
20
|
+
hostContextId:'actual-main',decisionId:'decision-1',decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
|
|
21
|
+
change(body);return {...body,grantDigest:digest(body)};
|
|
22
|
+
};
|
|
23
|
+
const events=(onEvent,thread='actual-review')=>{
|
|
24
|
+
onEvent({event:'thread.started',provider_thread:thread});
|
|
25
|
+
onEvent({event:'turn.started',item_type:null});
|
|
26
|
+
onEvent({event:'item.completed',item_type:'agent_message'});
|
|
27
|
+
onEvent({event:'turn.completed',item_type:null});
|
|
28
|
+
onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
async function fixture(fn,{reviewRun,authorize,times,timeoutMs=1000,provider='codex'}={}) {
|
|
32
|
+
const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-v3-')));
|
|
33
|
+
const root=path.join(temp,'code'),specsRoot=path.join(temp,'specs'),reviewsDir=path.join(specsRoot,'.reviews');
|
|
34
|
+
fs.mkdirSync(root);fs.mkdirSync(reviewsDir,{recursive:true});
|
|
35
|
+
const tasksPath=path.join(specsRoot,'tasks.md');fs.writeFileSync(tasksPath,'- [ ] T-001: fixture\n');
|
|
36
|
+
fs.writeFileSync(path.join(root,'code.js'),'old\n');fs.writeFileSync(path.join(root,'requirements.md'),'fixture\n');
|
|
37
|
+
const identity={repositoryId:'fixture',runId:'review-v3',taskId:'T-001',attempt:1};
|
|
38
|
+
const owner={tasksPath,feature:'feature',specsRoot,identity:{repositoryId:identity.repositoryId,runId:identity.runId},
|
|
39
|
+
fingerprints:{workflow:digest('review-v3'),config:digest('fixture'),inputs:digest('original')},create:true};
|
|
40
|
+
let dispatches=0,lateEvent=null,store=openTaskExecutionStore(owner);
|
|
41
|
+
const defaultRun=(request,{onEvent})=>{events(onEvent);
|
|
42
|
+
return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
|
|
43
|
+
examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};};
|
|
44
|
+
const options={root,identity,scope:['code.js'],requirements:['requirements.md'],excludedContexts:['main'],timeoutMs,
|
|
45
|
+
developer:{provider,requestedModel:'fixture',contextId:'developer-logical',run:request=>{
|
|
46
|
+
fs.writeFileSync(path.join(root,'code.js'),'new\n');return {version:1,invocationId:request.invocationId,
|
|
47
|
+
contextId:request.contextId,provider:request.provider,effectiveModel:'fixture',status:'succeeded',accepted:true,
|
|
48
|
+
result:{outcome:'implemented'}};}},
|
|
49
|
+
reviewers:[{id:'reviewer',adapterId:`${provider}-review-adapter`,provider,requestedModel:'fixture',allowed:true,
|
|
50
|
+
available:true,contexts:['review-logical-1','review-logical-2'],run:(request,control)=>{
|
|
51
|
+
dispatches++;lateEvent=control.onEvent;return (reviewRun??defaultRun)(request,control);
|
|
52
|
+
}}],check:()=>checks,
|
|
53
|
+
taskCompletion:{reviewsDir,handoffs:[path.join(reviewsDir,'a1.json'),path.join(reviewsDir,'a2.json')]},
|
|
54
|
+
reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main'],
|
|
55
|
+
authorize:authorize??((request,{authorizationAt})=>grantFor(request,authorizationAt))}};
|
|
56
|
+
const make=mode=>{
|
|
57
|
+
const old=Date.now,values=times?[...times]:null;if(values)Date.now=()=>values.length>1?values.shift():values[0];
|
|
58
|
+
try{return createTaskRunner({...options,persistence:{store,mode,version:3}});}finally{Date.now=old;}
|
|
59
|
+
};
|
|
60
|
+
const reopen=()=>{store.close();store=openTaskExecutionStore({...owner,create:false});return make('resume');};
|
|
61
|
+
const resumePrefix=type=>{
|
|
62
|
+
const current=store.snapshot(),at=current.records.findIndex(record=>record.payload.type===type);assert(at>=0);store.close();
|
|
63
|
+
const statePath=path.join(specsRoot,'.reviews','.execution',identity.runId,'state.json');
|
|
64
|
+
const body={version:current.version,identity:current.identity,fingerprints:current.fingerprints,records:current.records.slice(0,at+1)};
|
|
65
|
+
fs.writeFileSync(statePath,JSON.stringify({...body,revision:digest(body)})+'\n',{mode:0o600});
|
|
66
|
+
store=openTaskExecutionStore({...owner,create:false});return make('resume');
|
|
67
|
+
};
|
|
68
|
+
const effect=(kind,attempt=1)=>({version:1,id:`${kind}-${attempt}`,identity:{...identity,attempt},kind});
|
|
69
|
+
try{return await fn({root,tasksPath,options,effect,make:()=>make('create'),reopen,resumePrefix,getStore:()=>store,
|
|
70
|
+
dispatches:()=>dispatches,lateEvent:()=>lateEvent});}
|
|
71
|
+
finally{store.close();fs.rmSync(temp,{recursive:true,force:true});}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const timeoutRun=(request,{onEvent})=>{
|
|
75
|
+
onEvent({event:'thread.started',provider_thread:`thread-${request.invocationId}`});
|
|
76
|
+
onEvent({event:'turn.started',item_type:null});
|
|
77
|
+
onEvent({event:'process_closed',exit_code:143,signal:null,timed_out:true});
|
|
78
|
+
return {status:'failed',code:'timeout'};
|
|
79
|
+
};
|
|
80
|
+
const retryEffect=(f,attempt=1)=>({...f.effect('review',attempt),id:`review-${attempt}-retry-1`});
|
|
81
|
+
|
|
82
|
+
test('runner timer without a result shares pending/blocked timeout transitions and replay',()=>fixture(async f=>{
|
|
83
|
+
const runner=f.make();await runner.executeEffect(f.effect('develop'));
|
|
84
|
+
const end=await runner.executeEffect(f.effect('review'));
|
|
85
|
+
assert.equal(end.state,'pending_review');assert.equal(end.code,'review_transport_timeout');
|
|
86
|
+
assert.equal(end.calls.at(-1).terminal,'failed');assert.equal(end.reviewInvocation.result.outcome,'timed_out');
|
|
87
|
+
assert.equal(end.reviewInvocation.result.inspection.code,'transport_timeout');
|
|
88
|
+
assert.equal(end.reviewInvocation.result.reconciliationRequired,false);
|
|
89
|
+
const before=f.getStore().snapshot();assert.equal(f.lateEvent()({event:'item.completed',item_type:'agent_message'}),false);
|
|
90
|
+
assert.deepEqual(f.getStore().snapshot(),before);
|
|
91
|
+
const resumed=f.reopen();assert.deepEqual(resumed.status(),end);
|
|
92
|
+
assert.deepEqual(await resumed.executeEffect(f.effect('review')),end);assert.equal(f.dispatches(),1);
|
|
93
|
+
const blocked=await resumed.executeEffect(retryEffect(f));assert.equal(blocked.state,'blocked');
|
|
94
|
+
assert.equal(blocked.code,'review_transport_timeout');assert.deepEqual(f.reopen().status(),blocked);
|
|
95
|
+
assert.equal((await f.reopen().executeEffect({...retryEffect(f),id:'review-1-retry-2'})).code,'stage_mismatch');
|
|
96
|
+
assert.equal(f.dispatches(),2);
|
|
97
|
+
},{timeoutMs:20,reviewRun:(request,{onEvent})=>{
|
|
98
|
+
onEvent({event:'thread.started',provider_thread:`thread-${request.invocationId}`});return new Promise(()=>{});
|
|
99
|
+
}}));
|
|
100
|
+
|
|
101
|
+
test('each attempt gets one retry without consuming the six-effect budget or reusing grants',()=>fixture(async f=>{
|
|
102
|
+
const attempts=new Map();
|
|
103
|
+
f.options.reviewers[0].run=(request,control)=>{
|
|
104
|
+
const attempt=request.identity.attempt,count=(attempts.get(attempt)??0)+1;attempts.set(attempt,count);
|
|
105
|
+
if(count===1)return timeoutRun(request,control);
|
|
106
|
+
events(control.onEvent,`thread-${request.invocationId}`);
|
|
107
|
+
return {status:'succeeded',value:{verdict:attempt===1?'changes_requested':'approved',
|
|
108
|
+
packageDigest:request.payload.reviewPackage.packageDigest,examinedPaths:reviewPaths(request.payload.reviewPackage),
|
|
109
|
+
findings:attempt===1?[{id:'F1',severity:'P2',path:'code.js',message:'Repair',evidence:'Synthetic'}]:[],summary:'Synthetic'}};
|
|
110
|
+
};
|
|
111
|
+
let runner=f.make();
|
|
112
|
+
for(const attempt of [1,2]){
|
|
113
|
+
assert.equal((await runner.executeEffect(f.effect('develop',attempt))).state,'awaiting_review');
|
|
114
|
+
const first=await runner.executeEffect(f.effect('review',attempt));assert.equal(first.state,'pending_review');
|
|
115
|
+
runner=f.reopen();assert.deepEqual(runner.status(),first);
|
|
116
|
+
const second=await runner.executeEffect(retryEffect(f,attempt));
|
|
117
|
+
assert.equal(second.state,attempt===1?'changes_requested':'approved');
|
|
118
|
+
assert.notEqual(first.reviewInvocation.registration.grant.invocationId,second.reviewInvocation.registration.grant.invocationId);
|
|
119
|
+
assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,second.reviewInvocation.registration.grant.grantDigest);
|
|
120
|
+
runner=f.reopen();assert.deepEqual(runner.status(),second);
|
|
121
|
+
}
|
|
122
|
+
const records=f.getStore().snapshot().records,history=readRunnerHistory(records,records[0].payload.config,3);
|
|
123
|
+
assert.equal(history.state.cache.length,6);assert.equal(completedEffectCount(history.state.cache),4);
|
|
124
|
+
const complete=await runner.executeEffect(f.effect('complete',2));
|
|
125
|
+
assert.notEqual(complete.outcome,'rejected');assert.notEqual(complete.code,'limit_exceeded');
|
|
126
|
+
assert.equal(f.reopen().status().state,complete.state);
|
|
127
|
+
}));
|
|
128
|
+
|
|
129
|
+
function rechain(records){
|
|
130
|
+
let previousDigest=null;
|
|
131
|
+
for(const row of records){row.previousDigest=previousDigest;const {digest:old,...body}=row;row.digest=digest(body);previousDigest=row.digest;}
|
|
132
|
+
return records;
|
|
133
|
+
}
|
|
134
|
+
test('legacy worker unknown and legacy runner timed_out checkpoints remain unknown, never resumable',()=>fixture(async f=>{
|
|
135
|
+
const runner=f.make();await runner.executeEffect(f.effect('develop'));await runner.executeEffect(f.effect('review'));
|
|
136
|
+
for(const oldOutcome of ['unknown','timed_out']){
|
|
137
|
+
const records=structuredClone(f.getStore().snapshot().records),configuration=records[0].payload.config;
|
|
138
|
+
const result=records.find(row=>row.payload.type==='review-invocation-result').payload;
|
|
139
|
+
result.outcome=oldOutcome;result.reconciliationRequired=true;
|
|
140
|
+
if(oldOutcome==='timed_out')result.inspection=null;
|
|
141
|
+
const view=Object.fromEntries(Object.entries(result).filter(([key])=>!['version','protocol','type','effectId','invocationId'].includes(key)));
|
|
142
|
+
const checkpoint=records.at(-1).payload.checkpoint;
|
|
143
|
+
checkpoint.state='unknown';checkpoint.code=oldOutcome==='unknown'?'transport_timeout':'reconciliation_required';
|
|
144
|
+
checkpoint.reviewInvocation.result=view;
|
|
145
|
+
checkpoint.calls.at(-1).terminal='unknown';checkpoint.calls.at(-1).resultDigest=digest(view);
|
|
146
|
+
checkpoint.cache.at(-1).result=runnerStatus(checkpoint,configuration);
|
|
147
|
+
const recovered=readRunnerHistory(rechain(records),configuration,3);
|
|
148
|
+
assert.equal(recovered.state.state,'unknown');assert.equal(recovered.state.reviewInvocation.result.reconciliationRequired,true);
|
|
149
|
+
assert.equal(completedEffectCount(recovered.state.cache),2);
|
|
150
|
+
}
|
|
151
|
+
},{reviewRun:timeoutRun}));
|
|
152
|
+
|
|
153
|
+
test('replay rejects a fabricated pending retry after any final message',()=>fixture(async f=>{
|
|
154
|
+
const runner=f.make();await runner.executeEffect(f.effect('develop'));await runner.executeEffect(f.effect('review'));
|
|
155
|
+
const records=structuredClone(f.getStore().snapshot().records),configuration=records[0].payload.config;
|
|
156
|
+
const result=records.find(row=>row.payload.type==='review-invocation-result').payload;
|
|
157
|
+
result.observation.events.splice(2,0,{event:'item.completed',item_type:'agent_message'});
|
|
158
|
+
const {inspectProviderReview}=await import('../runtime/js/cm-ai/provider-review-observation.mjs');
|
|
159
|
+
// Even with a recomputed valid inspection and record chain, a result event
|
|
160
|
+
// cannot claim reconciliationRequired=false.
|
|
161
|
+
const before=records.filter(row=>row.payload.type==='effect-checkpoint')[0].payload.checkpoint;
|
|
162
|
+
const {requestFor}=await import('../runtime/js/cm-ai/effect-contract.mjs');
|
|
163
|
+
const request=requestFor({invocationId:result.invocationId,identity:f.options.identity,role:'reviewer',provider:'codex',
|
|
164
|
+
requestedModel:'fixture',contextId:'review-logical-1',payload:{reviewPackage:before.reviewPackage,priorReview:null}});
|
|
165
|
+
result.inspection=inspectProviderReview(JSON.stringify(result.observation),JSON.stringify({request,
|
|
166
|
+
developerThreadId:'actual-developer',excludedThreadIds:['actual-main']}));
|
|
167
|
+
assert.throws(()=>readRunnerHistory(rechain(records),configuration,3),{code:'runner_invocation'});
|
|
168
|
+
},{reviewRun:timeoutRun}));
|
|
169
|
+
|
|
170
|
+
for(const runtime of ['codex','claude'])for(const providerMode of [false,true])
|
|
171
|
+
test(`factory passes exact configured timeout to ${runtime} reviewer, provider mode=${providerMode}`,async t=>fixture(async f=>{
|
|
172
|
+
const {default:childProcess}=await import('node:child_process');
|
|
173
|
+
const {syncBuiltinESMExports}=await import('node:module');
|
|
174
|
+
const {EventEmitter}=await import('node:events');
|
|
175
|
+
const {PassThrough}=await import('node:stream');
|
|
176
|
+
const {createConversationExecution}=await import('../runtime/js/cm-ai/host-conversation-execution.mjs');
|
|
177
|
+
const {configFingerprint}=await import('../runtime/js/cm-ai/codex-config.mjs');
|
|
178
|
+
const {claudeReviewFingerprint}=await import('../runtime/js/cm-ai/worker-claude.mjs');
|
|
179
|
+
const {requestFor}=await import('../runtime/js/cm-ai/effect-contract.mjs');
|
|
180
|
+
const runner=f.make();await runner.executeEffect(f.effect('develop'));
|
|
181
|
+
const reviewPackage=f.getStore().snapshot().records.at(-1).payload.checkpoint.reviewPackage;
|
|
182
|
+
fs.writeFileSync(path.join(f.root,'.cm-workflow.json'),JSON.stringify({version:1,runtimes:{available:runtime}}));
|
|
183
|
+
const definition={codeProject:f.root,specsDir:path.dirname(f.options.taskCompletion.reviewsDir),feature:'feature',
|
|
184
|
+
identity:f.options.identity,scope:['code.js'],requirements:['requirements.md']};
|
|
185
|
+
const workerOptions={cwd:f.root,model:'fixture',promptTransport:'stdin',disabledSkills:[]};
|
|
186
|
+
// Matching synthetic diagnostic data is confined to this mocked process test.
|
|
187
|
+
const review={model:'fixture',disabledSkills:[],preflight:{passed:true,provider:runtime,cli_model:'fixture',
|
|
188
|
+
prompt_transport:'stdin',config_fingerprint:(runtime==='codex'?configFingerprint:claudeReviewFingerprint)(workerOptions)}};
|
|
189
|
+
const timeoutMs=providerMode?6789:5123;
|
|
190
|
+
const execution=createConversationExecution(definition,'host-test',{call:()=>assert.fail('unexpected host call')},review,1,null,false,runtime,
|
|
191
|
+
{protection:{checkCommands:[{id:'syntax',command:[process.execPath,'--version']}],timeoutMs},
|
|
192
|
+
...(providerMode?{providerDevelopment:{model:'fixture',attempt:1,coderRuntime:runtime,reviewerRuntime:runtime}}:{})});
|
|
193
|
+
const timers=[],originalTimer=globalThis.setTimeout;
|
|
194
|
+
t.mock.method(globalThis,'setTimeout',(fn,delay,...args)=>{timers.push(delay);return originalTimer(fn,delay,...args);});
|
|
195
|
+
t.mock.method(childProcess,'spawn',()=>{
|
|
196
|
+
const child=new EventEmitter();child.stdin=new PassThrough();child.stdout=new PassThrough();child.stderr=new PassThrough();
|
|
197
|
+
child.kill=()=>true;
|
|
198
|
+
queueMicrotask(()=>{child.stdout.end();child.stderr.end();child.emit('close',1,null);});
|
|
199
|
+
return child;
|
|
200
|
+
});
|
|
201
|
+
syncBuiltinESMExports();
|
|
202
|
+
try{
|
|
203
|
+
const request=requestFor({invocationId:'synthetic-timeout-config',identity:f.options.identity,role:'reviewer',provider:runtime,
|
|
204
|
+
requestedModel:'fixture',contextId:'cm-conversation-review-1',payload:{reviewPackage,priorReview:null}});
|
|
205
|
+
await execution.reviewers[0].run(request,{signal:new AbortController().signal,onEvent:()=>{}});
|
|
206
|
+
assert.deepEqual(timers,[timeoutMs]);
|
|
207
|
+
assert.equal(execution.timeoutMs,providerMode?timeoutMs:1800000,'outer host timeout remains unchanged');
|
|
208
|
+
}finally{t.mock.restoreAll();syncBuiltinESMExports();}
|
|
209
|
+
}));
|
|
210
|
+
|
|
211
|
+
for(const boundary of ['stale-grant','package-drift','cancelled'])
|
|
212
|
+
test(`retry preserves original authorization/package/cancellation boundary: ${boundary}`,()=>fixture(async f=>{
|
|
213
|
+
if(boundary==='stale-grant'){
|
|
214
|
+
let firstGrant;
|
|
215
|
+
f.options.reviewInvocation.authorize=(request,{authorizationAt})=>firstGrant??=grantFor(request,authorizationAt);
|
|
216
|
+
}
|
|
217
|
+
let runner=f.make();await runner.executeEffect(f.effect('develop'));
|
|
218
|
+
const pending=await runner.executeEffect(f.effect('review'));assert.equal(pending.state,'pending_review');
|
|
219
|
+
if(boundary==='package-drift')fs.writeFileSync(path.join(f.root,'code.js'),'outside drift\n');
|
|
220
|
+
if(boundary==='cancelled')runner.cancel();
|
|
221
|
+
if(boundary!=='stale-grant')runner=f.reopen();
|
|
222
|
+
const result=await runner.executeEffect(retryEffect(f));
|
|
223
|
+
assert.equal(result.code,boundary==='stale-grant'?'authorization_invalid':boundary==='package-drift'?'package_mismatch':'stage_mismatch');
|
|
224
|
+
assert.equal(f.dispatches(),1);
|
|
225
|
+
if(boundary==='stale-grant')assert.equal(f.reopen().status().state,'unknown');
|
|
226
|
+
},{reviewRun:timeoutRun}));
|
package/scripts/cm-ai-run.mjs
CHANGED
|
@@ -6,9 +6,11 @@ import {fileURLToPath} from 'node:url';
|
|
|
6
6
|
import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
|
|
7
7
|
import {digest as sha} from '../runtime/js/cm-ai/contracts.mjs';
|
|
8
8
|
import {resolveCodeProjects,codeProjectPaths,assertCodeProjectSelections} from '../runtime/js/cm-ai/code-projects.mjs';
|
|
9
|
+
import {preQaConfigurations,readQaAttachment} from '../runtime/js/cm-ai/qa-attachment.mjs';
|
|
10
|
+
import {recordCmAiQaAttachment} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
|
|
9
11
|
import {isSupportedExecutionPlatform} from '../runtime/js/cm-ai/execution-platform.mjs';
|
|
10
12
|
|
|
11
|
-
const usage='cm-ai-run.mjs serve --config PATH --mode create|resume (no provider dispatch)';
|
|
13
|
+
const usage='cm-ai-run.mjs serve --config PATH --mode create|resume (no provider dispatch)\nNew runs bind approved specification material from specsDir; requirements may be [] or supplemental code-project files. Manifest drift blocks as spec_drift; legacy journals retain their original format.';
|
|
12
14
|
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
13
15
|
// In-process provenance only; a config flag cannot certify protected callbacks.
|
|
14
16
|
const protectedExecutions=new WeakMap();
|
|
@@ -145,7 +147,7 @@ export function validateRunDefinition(input){
|
|
|
145
147
|
if(typeof value.identity[key]!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value.identity[key]))fail('invalid_identity');
|
|
146
148
|
}
|
|
147
149
|
for(const key of ['scope','requirements']){
|
|
148
|
-
if(!Array.isArray(value[key])||(!value[key].length&&!(key==='requirements'
|
|
150
|
+
if(!Array.isArray(value[key])||(!value[key].length&&!(key==='requirements'))||value[key].length>256
|
|
149
151
|
||value[key].some(p=>typeof p!=='string'||!p||p.includes('\\')||p.includes('\0')
|
|
150
152
|
||path.isAbsolute(p)||p.split('/').some(x=>!x||x==='.'||x==='..')))fail('invalid_paths');
|
|
151
153
|
}
|
|
@@ -158,11 +160,12 @@ export function validateRunDefinition(input){
|
|
|
158
160
|
return value;
|
|
159
161
|
}
|
|
160
162
|
|
|
161
|
-
export async function openControlRun(definition,mode,execution=null){
|
|
163
|
+
export async function openControlRun(definition,mode,execution=null,{rerunUnknownQa=false}={}){
|
|
162
164
|
// Check before importing node:sqlite: legacy Node users get a useful error.
|
|
163
165
|
if(!isSupportedExecutionPlatform())fail('unsupported_runner_platform');
|
|
164
166
|
const {conversationProtection}=await import('../runtime/js/cm-ai/host-conversation-execution.mjs');
|
|
165
167
|
if(!['create','resume'].includes(mode))fail('invalid_mode');
|
|
168
|
+
if(typeof rerunUnknownQa!=='boolean'||rerunUnknownQa&&(mode!=='resume'||!execution?.qaExecutor))fail('qa_recovery_authorization_required');
|
|
166
169
|
const {openTaskExecutionStore}=await import('../runtime/js/cm-ai/task-owner.mjs');
|
|
167
170
|
const {createCmAiHost}=await import('../runtime/js/cm-ai/host.mjs');
|
|
168
171
|
const {inspectCmAiAdmission}=await import('../runtime/js/cm-ai/cm-ai-admission.mjs');
|
|
@@ -196,7 +199,6 @@ export async function openControlRun(definition,mode,execution=null){
|
|
|
196
199
|
const {bootstrapConfiguration}=await import('../runtime/js/cm-ai/host-bootstrap.mjs');
|
|
197
200
|
bootstrapConfig=bootstrapConfiguration(execution.bootstrap,{root:codeProject,identity,scope,feature});
|
|
198
201
|
}
|
|
199
|
-
if(requirements.length===0&&!bootstrapConfig)fail('bootstrap_capability_required');
|
|
200
202
|
const selectedRoots=definition.codeProjects?codeProjectPaths(codeProject,resolveCodeProjects(codeProject,definition.codeProjects)):null;
|
|
201
203
|
if(selectedRoots){
|
|
202
204
|
if(!execution||conversationProtection(execution)===null)fail('multi_root_protection_required');
|
|
@@ -218,15 +220,13 @@ export async function openControlRun(definition,mode,execution=null){
|
|
|
218
220
|
const handoffs=[1,2].map(attempt=>path.join(reviewsDir,`${featureSlug}-${identity.taskId}-a${attempt}-handoff.json`));
|
|
219
221
|
// Reuse the runner's real validator before creating durable state. A failed
|
|
220
222
|
// baseline must not strand an otherwise unused run ID.
|
|
221
|
-
const
|
|
223
|
+
const specification={specsRoot:specsDir,feature};
|
|
224
|
+
const baselineOptions={root:codeProject,specsRoot:specsDir,identity,scope,requirements,specification,
|
|
222
225
|
...(bootstrapConfig?{bootstrapRequirements:bootstrapConfig.bootstrapRequirements}:{}),
|
|
223
226
|
...(selectedRoots?{codeProjectPaths:selectedRoots}:{})};
|
|
224
227
|
if(mode==='create')captureReviewBaseline(baselineOptions);
|
|
225
228
|
// Definition is data, never an import path, command, grant or executable callback.
|
|
226
|
-
const
|
|
227
|
-
identity:{repositoryId:identity.repositoryId,runId:identity.runId},
|
|
228
|
-
fingerprints:{workflow:sha(execution===null?'cm-ai-control-v1':'cm-ai-host-execution-v1'),
|
|
229
|
-
config:sha(execution===null?definition:{definition,execution:execution.configuration,
|
|
229
|
+
const configMaterial=execution===null?definition:{definition,execution:execution.configuration,
|
|
230
230
|
...(bootstrapConfig?{bootstrap:bootstrapConfig}:{}),
|
|
231
231
|
...(Object.hasOwn(execution,'developmentAttempt')?{developmentAuthorization:'per-attempt-v1'}:{}),
|
|
232
232
|
...(execution.hostDecisionProvider?{hostDecisionProvider:{version:1,timeoutMs:execution.hostDecisionProvider.timeoutMs}}:{}),
|
|
@@ -237,9 +237,28 @@ export async function openControlRun(definition,mode,execution=null){
|
|
|
237
237
|
...(execution.applicableAgentFiles?{applicableAgentFiles:execution.applicableAgentFiles}:{}),
|
|
238
238
|
...(execution.documentationProvider?{documentationProvider:{version:1,timeoutMs:execution.documentationProvider.timeoutMs}}:{}),
|
|
239
239
|
...(execution.documentationResult?{documentationResult:execution.documentationResult}:{}),
|
|
240
|
-
...(execution.documentationSync?{documentationSync:{version:1,paths:execution.documentationSync.paths}}:{})}
|
|
241
|
-
|
|
240
|
+
...(execution.documentationSync?{documentationSync:{version:1,paths:execution.documentationSync.paths}}:{})};
|
|
241
|
+
const fingerprints={workflow:sha(execution===null?'cm-ai-control-v1':'cm-ai-host-execution-v1'),
|
|
242
|
+
config:sha(configMaterial),inputs:sha({feature,task:identity.taskId})};
|
|
243
|
+
const storeOptions={tasksPath,feature:featureSlug,specsRoot:specsDir,
|
|
244
|
+
identity:{repositoryId:identity.repositoryId,runId:identity.runId},fingerprints,create:mode==='create'};
|
|
245
|
+
let store,attaching=false;
|
|
246
|
+
try{store=openTaskExecutionStore(storeOptions);}
|
|
247
|
+
catch(error){
|
|
248
|
+
if(mode!=='resume'||error.code!=='fingerprint_mismatch')throw error;
|
|
249
|
+
for(const previous of preQaConfigurations(configMaterial)){
|
|
250
|
+
try{store=openTaskExecutionStore({...storeOptions,fingerprints:{...fingerprints,config:sha(previous)}});break;}
|
|
251
|
+
catch(cause){if(cause.code!=='fingerprint_mismatch')throw cause;}
|
|
252
|
+
}
|
|
253
|
+
if(!store)throw error;
|
|
254
|
+
attaching=true;
|
|
255
|
+
}
|
|
242
256
|
try{
|
|
257
|
+
const attachments=store.snapshot().records.filter(row=>row.payload.type==='qa-attached');
|
|
258
|
+
if(attachments.length>1)fail('qa_attachment_duplicate');
|
|
259
|
+
const attached=attachments.length?readQaAttachment(attachments[0].payload.record):null;
|
|
260
|
+
if(attached&&attached.qaFingerprint!==fingerprints.config)fail('fingerprint_mismatch');
|
|
261
|
+
if(attaching&&store.snapshot().records.length===0)fail('qa_attach_not_completed');
|
|
243
262
|
let runnerMode=mode;
|
|
244
263
|
if(mode==='resume'&&store.snapshot().records.length===0){
|
|
245
264
|
// Only the genuine, fingerprint-matching empty initializer can be finished.
|
|
@@ -251,7 +270,7 @@ export async function openControlRun(definition,mode,execution=null){
|
|
|
251
270
|
}
|
|
252
271
|
const unavailable=()=>fail('execution_adapter_required');
|
|
253
272
|
const host=createCmAiHost({
|
|
254
|
-
runner:{root:codeProject,identity,scope,requirements,...(selectedRoots?{codeProjectPaths:selectedRoots}:{}),excludedContexts:['control-host'],
|
|
273
|
+
runner:{root:codeProject,identity,scope,requirements,specification,...(selectedRoots?{codeProjectPaths:selectedRoots}:{}),excludedContexts:['control-host'],
|
|
255
274
|
developer:{provider:'codex',requestedModel:'unconfigured',contextId:'control-developer',run:unavailable},
|
|
256
275
|
reviewers:[],check:unavailable,taskCompletion:{reviewsDir,handoffs},taskLearning:{feature},
|
|
257
276
|
persistence:{store,mode:runnerMode,version:execution===null?2:3},
|
|
@@ -260,9 +279,17 @@ export async function openControlRun(definition,mode,execution=null){
|
|
|
260
279
|
reviewInvocation:execution.reviewInvocation,check:execution.check,
|
|
261
280
|
excludedContexts:execution.excludedContexts,timeoutMs:execution.timeoutMs,
|
|
262
281
|
taskLearning:{feature,hostHandoff:true}})},
|
|
263
|
-
entry:{specsDir,codeProject,feature,identity,...(execution===null?{}:{hostDecision:execution.hostDecision,
|
|
282
|
+
entry:{specsDir,codeProject,feature,identity,rerunUnknownQa,...(execution===null?{}:{hostDecision:execution.hostDecision,
|
|
264
283
|
...Object.fromEntries(['developmentAttempt','hostDecisionProvider','qaDecisionProvider','qaLogHome','qaExecutor','applicableAgentFiles','documentationProvider','documentationResult'].filter(key=>Object.hasOwn(execution,key)).map(key=>[key,execution[key]]))})},
|
|
265
284
|
});
|
|
285
|
+
if(attaching||attached){
|
|
286
|
+
const record=host.attachQa(attached??{version:1,qaFingerprint:fingerprints.config,
|
|
287
|
+
attachedAt:new Date().toISOString().replace(/\.\d{3}Z$/,'Z'),hostContextId:execution.configuration.hostContextId});
|
|
288
|
+
// Repeating this deterministic log write also repairs a crash after the
|
|
289
|
+
// journal append; neither the attachment nor QA dispatch is repeated.
|
|
290
|
+
recordCmAiQaAttachment({specsDir,codeProject,feature,identity,record,
|
|
291
|
+
...(execution.qaLogHome?{logHome:execution.qaLogHome}:{})});
|
|
292
|
+
}
|
|
266
293
|
return {host:{async handle(request){
|
|
267
294
|
if(execution===null&&!['status','cancel'].includes(request.operation)){
|
|
268
295
|
// Do not imply an unavailable execution adapter was dispatched.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {buildManifest} from './cm-spec-manifest.mjs';
|
|
1
2
|
import test from 'node:test';
|
|
2
3
|
import assert from 'node:assert/strict';
|
|
3
4
|
import fs from 'node:fs';
|
|
@@ -12,6 +13,39 @@ const cli=fileURLToPath(new URL('./cm-ai-run.mjs',import.meta.url));
|
|
|
12
13
|
const identity={repositoryId:'control-fixture',runId:'control-run',taskId:'T-001',attempt:1};
|
|
13
14
|
const request=(operation,requestId=operation)=>({version:1,operation,requestId,identity});
|
|
14
15
|
const platform=process.platform==='darwin'&&Number(process.versions.node.split('.')[0])>=24;
|
|
16
|
+
test('QA attachment projections preserve every non-workflow fingerprint input and validate the immutable record',async()=>{
|
|
17
|
+
const {preQaConfigurations,readQaAttachment}=await import('../runtime/js/cm-ai/qa-attachment.mjs');
|
|
18
|
+
const material={definition:{identity,scope:['a.js'],requirements:['requirements.md']},
|
|
19
|
+
execution:{kind:'cm-current-conversation-v1',hostContextId:'host',review:{model:'fixture'},
|
|
20
|
+
workflow:{qa:{commands:[],environment:{}},documentationPaths:['README.md'],applicableAgentFiles:[]}},
|
|
21
|
+
qaExecutor:{version:1,mode:'commands'},qaDecisionProvider:'host-v1',qaTimeoutMs:60000,
|
|
22
|
+
applicableAgentFiles:[],documentationProvider:{version:1,timeoutMs:60000},documentationSync:{version:1,paths:['README.md']},
|
|
23
|
+
hostDecisionProvider:{version:1,timeoutMs:60000},developmentAuthorization:'per-attempt-v1'};
|
|
24
|
+
const original=structuredClone(material),[withoutQa,withoutWorkflow]=preQaConfigurations(material);
|
|
25
|
+
assert.deepEqual(material,original);
|
|
26
|
+
assert.equal(withoutQa.execution.workflow.qa,null);
|
|
27
|
+
assert.deepEqual(withoutQa.documentationSync,material.documentationSync);
|
|
28
|
+
assert(!Object.hasOwn(withoutWorkflow.execution,'workflow'));
|
|
29
|
+
assert(!Object.hasOwn(withoutWorkflow,'documentationSync'));
|
|
30
|
+
for(const projection of [withoutQa,withoutWorkflow]){
|
|
31
|
+
assert.deepEqual(projection.definition,material.definition);
|
|
32
|
+
assert.deepEqual(projection.execution.review,material.execution.review);
|
|
33
|
+
assert.equal(projection.execution.hostContextId,'host');
|
|
34
|
+
assert.deepEqual(projection.hostDecisionProvider,material.hostDecisionProvider);
|
|
35
|
+
assert.equal(projection.developmentAuthorization,material.developmentAuthorization);
|
|
36
|
+
assert(!Object.hasOwn(projection,'qaExecutor'));
|
|
37
|
+
}
|
|
38
|
+
const legacy=structuredClone(material);
|
|
39
|
+
legacy.execution={codeProject:'/fixture',workflow:{definition:material.definition,configuration:material.execution.workflow}};
|
|
40
|
+
const [legacyNull,legacyAbsent]=preQaConfigurations(legacy);
|
|
41
|
+
assert.equal(legacyNull.execution.workflow.configuration.qa,null);
|
|
42
|
+
assert(!Object.hasOwn(legacyAbsent,'applicableAgentFiles'));
|
|
43
|
+
assert.deepEqual(preQaConfigurations({definition:material.definition}),[]);
|
|
44
|
+
const record={version:1,qaFingerprint:'a'.repeat(64),attachedAt:'2026-09-17T00:00:00Z',hostContextId:'host'};
|
|
45
|
+
assert.deepEqual(readQaAttachment(record),record);
|
|
46
|
+
for(const invalid of [{...record,version:2},{...record,qaFingerprint:'invalid'},
|
|
47
|
+
{...record,attachedAt:'invalid'},{...record,extra:true}])assert.throws(()=>readQaAttachment(invalid));
|
|
48
|
+
});
|
|
15
49
|
test('fixed Codex assembly requires review preflight and denies developer dispatch without host approval',()=>fixture(async f=>{
|
|
16
50
|
const {createCodexExecution}=await import('./cm-ai-run.mjs');
|
|
17
51
|
const {configFingerprint}=await import('../runtime/js/cm-ai/codex-config.mjs');
|
|
@@ -30,7 +64,7 @@ test('fixed Codex assembly requires review preflight and denies developer dispat
|
|
|
30
64
|
assert.equal(decisions,1);assert.equal(fs.readFileSync(path.join(f.codeProject,'a.js'),'utf8'),'old\n');
|
|
31
65
|
assert.equal(execution.reviewInvocation.authorize,authority.authorizeReview);
|
|
32
66
|
}));
|
|
33
|
-
for(const [mode,nested] of [...['manual','approved','denied','awaiting','blocked','repair','review_limit'].map(mode=>[mode,false]),['approved',true],['blocked',true]])
|
|
67
|
+
for(const [mode,nested] of [...['manual','approved','denied','awaiting','blocked','repair','review_limit','spec_drift'].map(mode=>[mode,false]),['approved',true],['blocked',true]])
|
|
34
68
|
test(`trusted host execution uses the same entry and sole gate: ${mode} nested=${nested}`,
|
|
35
69
|
{skip:!platform},()=>fixture(async f=>{
|
|
36
70
|
const {main}=await import('./cm-ai-run.mjs');
|
|
@@ -51,7 +85,7 @@ test(`trusted host execution uses the same entry and sole gate: ${mode} nested=$
|
|
|
51
85
|
}})},
|
|
52
86
|
reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',
|
|
53
87
|
allowed:true,available:true,contexts:['review-1','review-2'],run:(request,{onEvent})=>{
|
|
54
|
-
assert(['approved','blocked','repair','review_limit'].includes(mode));reviews++;
|
|
88
|
+
assert(['approved','blocked','repair','review_limit','spec_drift'].includes(mode));reviews++;
|
|
55
89
|
assert(!JSON.stringify(request.payload.reviewPackage).includes('cm-synthetic-worktree-metadata'));
|
|
56
90
|
if(mode==='approved'&&!nested){
|
|
57
91
|
assert(request.payload.reviewPackage.changes.some(change=>change.path==='README.md'));
|
|
@@ -63,21 +97,22 @@ test(`trusted host execution uses the same entry and sole gate: ${mode} nested=$
|
|
|
63
97
|
onEvent({event:'turn.completed',item_type:null});
|
|
64
98
|
onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
|
|
65
99
|
const verdict=mode==='review_limit'||(mode==='repair'&&request.identity.attempt===1)?'changes_requested':
|
|
66
|
-
|
|
100
|
+
['repair','spec_drift'].includes(mode)?'approved':mode;
|
|
101
|
+
if(mode==='spec_drift')fs.appendFileSync(path.join(f.specsDir,'1.login','design.md'),'changed while review was running');
|
|
67
102
|
return {status:'succeeded',value:{verdict,packageDigest:request.payload.reviewPackage.packageDigest,
|
|
68
103
|
examinedPaths:reviewPaths(request.payload.reviewPackage),findings:verdict==='changes_requested'
|
|
69
104
|
?[{id:'F1',severity:'P2',path:'a.js',message:'Synthetic repair required',evidence:'First implementation'}]:[],summary:'Synthetic review'}};
|
|
70
105
|
}}],
|
|
71
106
|
reviewInvocation:{developerThreadId:'host-author',excludedThreadIds:['main'],
|
|
72
107
|
authorize:(request,{authorizationAt})=>{
|
|
73
|
-
assert(['approved','blocked','repair','review_limit'].includes(mode));
|
|
108
|
+
assert(['approved','blocked','repair','review_limit','spec_drift'].includes(mode));
|
|
74
109
|
const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${request.identity.attempt}`,adapterId:'codex-review-adapter',
|
|
75
110
|
invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,
|
|
76
111
|
reviewerId:'reviewer',logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,
|
|
77
112
|
hostContextId:'main',decisionId:`decision-${request.identity.attempt}`,decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
|
|
78
113
|
return {...body,grantDigest:digest(body)};
|
|
79
114
|
}},
|
|
80
|
-
hostDecision:mode==='awaiting'?null:['approved','blocked','repair','review_limit'].includes(mode)?{status:'approved'}:{status:'denied',code:'permission_denied'},
|
|
115
|
+
hostDecision:mode==='awaiting'?null:['approved','blocked','repair','review_limit','spec_drift'].includes(mode)?{status:'approved'}:{status:'denied',code:'permission_denied'},
|
|
81
116
|
check:createHostCheck({cwd:f.codeProject,commands:[{id:'content',command:[process.execPath,'-e',
|
|
82
117
|
"require('node:assert/strict').equal(require('node:fs').readFileSync('a.js','utf8'),'new\\n')"]}]})};
|
|
83
118
|
let qaCalls=0,qaRuns=0,docInspections=0,docWrites=0,reviewDecisions=0;
|
|
@@ -142,14 +177,15 @@ test(`trusted host execution uses the same entry and sole gate: ${mode} nested=$
|
|
|
142
177
|
}
|
|
143
178
|
assert.equal(await main(['serve','--config',f.config,'--mode','create'],{input,output,error,execution}),0,stderr);
|
|
144
179
|
const repaired=['repair','review_limit'].includes(mode),completed=['approved','repair'].includes(mode);
|
|
145
|
-
const expected=dynamicQa?'run_done':completed?'fixture_completed':['blocked','review_limit'].includes(mode)?'blocked':'awaiting_review';
|
|
180
|
+
const expected=dynamicQa?'run_done':completed?'fixture_completed':['blocked','review_limit','spec_drift'].includes(mode)?'blocked':'awaiting_review';
|
|
146
181
|
assert.equal(JSON.parse(stdout).result.state,expected,stdout);assert.equal(calls,repaired?2:1);
|
|
147
182
|
if(completed){
|
|
148
183
|
assert.equal(JSON.parse(stdout).result.code,dynamicQa?'run_done':'qa_decision_required');
|
|
149
184
|
assert.equal(JSON.parse(stdout).result.outcome,dynamicQa?'finalized':'awaiting');
|
|
150
185
|
}
|
|
151
|
-
assert.equal(reviews,repaired?2:['approved','blocked'].includes(mode)?1:0);
|
|
186
|
+
assert.equal(reviews,repaired?2:['approved','blocked','spec_drift'].includes(mode)?1:0);
|
|
152
187
|
if(repaired)assert.equal(JSON.parse(stdout).result.identity.attempt,2);
|
|
188
|
+
if(mode==='spec_drift')assert.equal(JSON.parse(stdout).result.code,'spec_drift');
|
|
153
189
|
if(mode==='review_limit')assert.equal(JSON.parse(stdout).result.code,'review_limit');
|
|
154
190
|
if(mode==='denied')assert.equal(JSON.parse(stdout).result.outcome,'denied');
|
|
155
191
|
if(mode==='awaiting')assert.equal(JSON.parse(stdout).result.code,'decision_required');
|
|
@@ -162,7 +198,7 @@ test(`trusted host execution uses the same entry and sole gate: ${mode} nested=$
|
|
|
162
198
|
assert.equal(await main(['serve','--config',f.config,'--mode','resume'],
|
|
163
199
|
{input:resumedInput,output:resumedOutput,error,execution}),0,stderr);
|
|
164
200
|
assert.equal(JSON.parse(resumed).result.state,expected,resumed);
|
|
165
|
-
assert.equal(calls,repaired?2:1);assert.equal(reviews,repaired?2:['approved','blocked'].includes(mode)?1:0);
|
|
201
|
+
assert.equal(calls,repaired?2:1);assert.equal(reviews,repaired?2:['approved','blocked','spec_drift'].includes(mode)?1:0);
|
|
166
202
|
if(dynamicReview)assert.equal(reviewDecisions,repaired?2:1,'reopen must not reauthorize completed review');
|
|
167
203
|
if(dynamicQa){
|
|
168
204
|
assert.equal(qaCalls,1);assert.equal(qaRuns,1);assert.equal(docInspections,2);assert.equal(docWrites,1);
|
|
@@ -181,7 +217,7 @@ async function fixture(fn,{nested=false}={}){
|
|
|
181
217
|
fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'# Requirements\n');
|
|
182
218
|
fs.writeFileSync(path.join(specsDir,feature,'design.md'),'# Design\n');
|
|
183
219
|
fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement\n');
|
|
184
|
-
fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature]}));
|
|
220
|
+
fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
|
|
185
221
|
const definition={version:1,specsDir,codeProject,feature,identity,scope:['a.js'],requirements:['requirements.md']};
|
|
186
222
|
const config=path.join(root,'run.json');fs.writeFileSync(config,JSON.stringify(definition));
|
|
187
223
|
const invoke=(mode,requests)=>{
|
|
@@ -12,7 +12,7 @@ const root=fileURLToPath(new URL('..',import.meta.url));
|
|
|
12
12
|
function fixture(t,exitCode=0){
|
|
13
13
|
const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-host-'))),project=path.join(dir,'project');fs.mkdirSync(project);
|
|
14
14
|
t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
|
15
|
-
for(const file of ['scripts/cm-check-entry.mjs','scripts/cm-check-host.mjs','runtime/js/cm-check/host.mjs',
|
|
15
|
+
for(const file of ['scripts/cm-check-entry.mjs','scripts/cm-check-host.mjs','scripts/cm-workflow-config.mjs','runtime/js/cm-check/host.mjs',
|
|
16
16
|
'runtime/js/cm-ai/host-tool-bridge.mjs','runtime/js/cm-ai/host-session.mjs','runtime/js/cm-ai/effect-contract.mjs',
|
|
17
17
|
'runtime/js/cm-ai/contracts.mjs','runtime/js/cm-init/draft-inspection.mjs','skills/cm-check/SKILL.md']){
|
|
18
18
|
fs.mkdirSync(path.dirname(path.join(dir,file)),{recursive:true});fs.copyFileSync(path.join(root,file),path.join(dir,file));
|