@aibyzero/cm-workflow 0.16.9 → 0.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +4 -0
- package/CHANGELOG.md +18 -1
- package/CONTRIBUTING.md +47 -0
- package/README.md +16 -1
- package/VERSION +1 -1
- package/docs/architecture.md +29 -13
- package/docs/cm-control-policy-v2.md +331 -0
- package/docs/execution-optimizations.md +1 -1
- package/docs/external-models.md +3 -3
- package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
- package/docs/human-correction.md +5 -5
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +104 -85
- package/docs/next-steps.md +11 -0
- package/docs/untested-branches.md +2 -3
- package/docs/user-guide.md +3 -3
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
- package/runtime/js/cm-ai/control-policy.mjs +112 -0
- package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
- package/runtime/js/cm-ai/drive-core.mjs +124 -25
- package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
- package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
- package/runtime/js/cm-ai/host-check.mjs +3 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
- package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
- package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
- package/runtime/js/cm-ai/host-review-file.mjs +1 -1
- package/runtime/js/cm-ai/host-session.mjs +41 -8
- package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
- package/runtime/js/cm-ai/host-tool-bridge.mjs +25 -9
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
- package/runtime/js/cm-ai/host.mjs +1 -2
- package/runtime/js/cm-ai/operator-guidance.mjs +57 -54
- package/runtime/js/cm-ai/review-package.mjs +16 -4
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
- package/runtime/js/cm-ai/task-runner.mjs +41 -101
- package/runtime/js/cm-init/review-evidence.mjs +3 -1
- package/runtime/js/cm-prd/review-host.mjs +1 -1
- package/runtime/js/cm-prd/review-publication.mjs +5 -3
- package/runtime/js/cm-prd/summary.mjs +27 -12
- package/runtime/js/cm-refactor/workflow.mjs +1 -1
- package/runtime/js/notify-send.mjs +15 -14
- package/runtime/js/notify.mjs +27 -4
- package/runtime/js/policy-binding-compat.mjs +2 -1
- package/runtime/review.md +61 -7
- package/runtime/task-gates.md +107 -9
- package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
- package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
- package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
- package/scripts/cm-ai-batch-drive.mjs +50 -31
- package/scripts/cm-ai-batch-drive.test.mjs +62 -19
- package/scripts/cm-ai-batch-host.mjs +39 -20
- package/scripts/cm-ai-batch-host.test.mjs +83 -47
- package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
- package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
- package/scripts/cm-ai-batch-run.mjs +46 -14
- package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
- package/scripts/cm-ai-bootstrap.test.mjs +2 -3
- package/scripts/cm-ai-control-launch.test.mjs +219 -0
- package/scripts/cm-ai-control-policy.test.mjs +192 -0
- package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
- package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
- package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
- package/scripts/cm-ai-direct-review.test.mjs +348 -0
- package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
- package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +57 -27
- package/scripts/cm-ai-drive.mjs +96 -54
- package/scripts/cm-ai-drive.test.mjs +46 -87
- package/scripts/cm-ai-fix-integration.test.mjs +3 -5
- package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
- package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
- package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
- package/scripts/cm-ai-host-fixture.mjs +47 -16
- package/scripts/cm-ai-host-protected.test.mjs +35 -33
- package/scripts/cm-ai-host.mjs +103 -93
- package/scripts/cm-ai-host.test.mjs +34 -18
- package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
- package/scripts/cm-ai-legacy-history.test.mjs +53 -0
- package/scripts/cm-ai-light-modules.test.mjs +4 -7
- package/scripts/cm-ai-multi-root.test.mjs +4 -4
- package/scripts/cm-ai-nested-execution.test.mjs +16 -19
- package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
- package/scripts/cm-ai-progress.test.mjs +10 -8
- package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
- package/scripts/cm-ai-protected-scope.test.mjs +1 -2
- package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
- package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
- package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
- package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
- package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
- package/scripts/cm-ai-review-failure.test.mjs +13 -19
- package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
- package/scripts/cm-ai-review-timeout.test.mjs +35 -128
- package/scripts/cm-ai-run.mjs +78 -24
- package/scripts/cm-ai-run.test.mjs +11 -38
- package/scripts/cm-ai-selection-guard.test.mjs +2 -2
- package/scripts/cm-ai-session-chain.test.mjs +18 -15
- package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
- package/scripts/cm-ai-supersede.test.mjs +3 -10
- package/scripts/cm-blocked-reason.test.mjs +2 -3
- package/scripts/cm-capability-gate.test.mjs +33 -1
- package/scripts/cm-check-drive-files.mjs +1 -1
- package/scripts/cm-check-host.test.mjs +1 -1
- package/scripts/cm-check-runtime.sh +1 -1
- package/scripts/cm-claude-probe.test.mjs +26 -0
- package/scripts/cm-claude-review-stream.test.mjs +36 -0
- package/scripts/cm-claude-worker.test.mjs +21 -3
- package/scripts/cm-controlled-correction.test.mjs +469 -0
- package/scripts/cm-drive-liveness.test.mjs +83 -0
- package/scripts/cm-external-batch-host.test.mjs +38 -17
- package/scripts/cm-external-model-host.test.mjs +1 -1
- package/scripts/cm-external-model-recovery.test.mjs +3 -9
- package/scripts/cm-external-qa-fix.test.mjs +1 -1
- package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
- package/scripts/cm-fix-review-recovery.test.mjs +1 -1
- package/scripts/cm-host-diagnostic.test.mjs +33 -0
- package/scripts/cm-host-liveness.test.mjs +150 -0
- package/scripts/cm-host-qa-executor.test.mjs +1 -2
- package/scripts/cm-host-qa-policy.test.mjs +43 -16
- package/scripts/cm-host-review-authority.test.mjs +0 -31
- package/scripts/cm-host-stage-observer.test.mjs +41 -0
- package/scripts/cm-knowledge-closeout.test.mjs +3 -3
- package/scripts/cm-notify-command.test.mjs +54 -18
- package/scripts/cm-notify-read-drift.test.mjs +69 -4
- package/scripts/cm-notify.mjs +16 -4
- package/scripts/cm-notify.test.mjs +135 -29
- package/scripts/cm-patrol.test.mjs +3 -2
- package/scripts/cm-prd-drive.test.mjs +1 -1
- package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
- package/scripts/cm-prd-session-recovery.test.mjs +5 -3
- package/scripts/cm-prd-summary.test.mjs +31 -0
- package/scripts/cm-release-smoke.sh +2 -14
- package/scripts/cm-task-gate-correction.test.mjs +69 -16
- package/scripts/cm-task-gate.mjs +368 -34
- package/scripts/cm-task-gate.py +2 -0
- package/scripts/cm-task-gate.test.mjs +252 -4
- package/scripts/cm-test-suite.mjs +109 -0
- package/scripts/cm-test-suite.test.mjs +162 -0
- package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
- package/scripts/fixtures/host-diagnostic.mjs +33 -0
- package/scripts/fixtures/native-gate-fixture.mjs +18 -0
- package/scripts/policy-binding-compat.test.mjs +4 -0
- package/skills/cm-ai/SKILL.md +8 -6
- package/skills/cm-ai/references/N3-execute-task.md +17 -2
- package/skills/cm-ai/references/N4-review.md +11 -21
- package/skills/cm-ai/references/N5-mark-done.md +1 -1
- package/skills/cm-ai/references/N6-qa-eval.md +49 -21
- package/skills/cm-ai/references/js-host-modes.md +35 -14
- package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
- package/skills/cm-ai/references/js-host-recovery.md +95 -47
- package/skills/cm-ai/references/js-host.md +98 -29
- package/skills/cm-fix/SKILL.md +12 -0
- package/skills/cm-init/references/js-host.md +1 -1
- package/skills/cm-prd/references/js-host.md +1 -1
- package/skills/cm-refactor/SKILL.md +12 -0
- package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
- package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {createNativeUsageLog} from './native-usage-log.mjs';
|
|
2
2
|
import {readExecutionPolicy} from './execution-policy.mjs';
|
|
3
|
+
import {readControlPolicy} from './control-policy.mjs';
|
|
3
4
|
import {selectExternalModels} from './external-models.mjs';
|
|
4
5
|
// Fixed current-conversation factory, separate from CLI top-level execution.
|
|
5
6
|
import fs from 'node:fs';
|
|
@@ -17,7 +18,6 @@ import {createCodexReviewRun} from './codex-review-adapter.mjs';
|
|
|
17
18
|
import {createClaudeReviewRun} from './claude-review-adapter.mjs';
|
|
18
19
|
import {claudeWorker,claudePreflightMatches} from './worker-claude.mjs';
|
|
19
20
|
import {codexWorker,preflightMatches} from './worker-codex.mjs';
|
|
20
|
-
import {createHostReviewAuthority} from './host-review-authority.mjs';
|
|
21
21
|
import {createHostWorkflowCapabilities} from './host-workflow-capabilities.mjs';
|
|
22
22
|
import {resolveHostRole} from './host-role-routing.mjs';
|
|
23
23
|
import {checklistGaps} from './checklist-coverage.mjs';
|
|
@@ -105,13 +105,21 @@ export function resolveReviewTimeout(review,protection){
|
|
|
105
105
|
// after its own deadline; the margin leaves room for that and for close.
|
|
106
106
|
export const REVIEW_BOUND_MARGIN_MS=60000;
|
|
107
107
|
export const reviewRaceTimeout=(outerTimeoutMs,reviewTimeoutMs)=>Math.max(outerTimeoutMs,reviewTimeoutMs+REVIEW_BOUND_MARGIN_MS);
|
|
108
|
-
export function createConversationExecution(definition,hostContextId,bridge,review=null,
|
|
108
|
+
export function createConversationExecution(definition,hostContextId,bridge,review=null,reservedReviewAttempt=null,workflow=null,allowQa=false,runtime='codex',options={}){
|
|
109
109
|
definition=json(definition);workflow=workflow===null?null:json(workflow);options=json(options);
|
|
110
|
-
shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','externalModels','reviewerRuntime','reviewRuntime','parallelMember','verificationPrecheck','executionPolicy'].filter(key=>Object.hasOwn(options,key))]);
|
|
110
|
+
shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','externalModels','reviewerRuntime','reviewRuntime','parallelMember','verificationPrecheck','executionPolicy','controlPolicy'].filter(key=>Object.hasOwn(options,key))]);
|
|
111
|
+
const controlPolicy=options.controlPolicy?readControlPolicy(options.controlPolicy):null;
|
|
111
112
|
need(!Object.hasOwn(options,'verificationPrecheck')||typeof options.verificationPrecheck==='boolean','invalid_input');
|
|
112
113
|
const executionPolicy=options.executionPolicy?readExecutionPolicy(options.executionPolicy):null;
|
|
113
114
|
const parallelMember=options.parallelMember??false;need(typeof parallelMember==='boolean','invalid_input');
|
|
114
115
|
const provider=options.providerDevelopment??null;
|
|
116
|
+
if(controlPolicy){
|
|
117
|
+
need((controlPolicy.development==='provider')===Boolean(provider),'invalid_arguments');
|
|
118
|
+
need(controlPolicy.bootstrap!=='write'||Boolean(options.bootstrap),'invalid_arguments');
|
|
119
|
+
need(controlPolicy.qa!=='run'||workflow?.qa!=null,'invalid_arguments');
|
|
120
|
+
need(!options.bootstrap||controlPolicy.bootstrap==='write','invalid_arguments');
|
|
121
|
+
need(allowQa===(controlPolicy.qa==='run'),'invalid_input');
|
|
122
|
+
}
|
|
115
123
|
if(provider){
|
|
116
124
|
shape(provider,['model','attempt','coderRuntime','reviewerRuntime',...(Object.hasOwn(provider,'effort')?['effort']:[])]);
|
|
117
125
|
need(options.protection&&review!==null,'protected_configuration_required');
|
|
@@ -148,9 +156,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
148
156
|
const check=projectExecution?.check??null;
|
|
149
157
|
const documentationPaths=workflow?validateDocumentationPaths(workflow.documentationPaths,definition.scope):[];
|
|
150
158
|
need(['codex','claude'].includes(runtime),'invalid_runtime');
|
|
151
|
-
|
|
152
|
-
need(allowedAttempts.length<=2&&new Set(allowedAttempts).size===allowedAttempts.length
|
|
153
|
-
&&allowedAttempts.every(value=>value===1||value===2),'invalid_review_attempt');
|
|
159
|
+
need(reservedReviewAttempt===null,'invalid_input');
|
|
154
160
|
const author='cm-conversation-author',reviewContexts=['cm-conversation-review-1','cm-conversation-review-2'];
|
|
155
161
|
const durableHostContextId=options.originalHostContextId??hostContextId;
|
|
156
162
|
for(const context of [hostContextId,durableHostContextId]){
|
|
@@ -160,6 +166,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
160
166
|
// slice too. A transport is not physical protection of nested specs.
|
|
161
167
|
need(protection||!definition.specsDir.startsWith(definition.codeProject+path.sep),'nested_specs_protection_required');
|
|
162
168
|
const configuration={kind:'cm-current-conversation-v1',...(parallelMember?{parallelMember}:{}),definitionDigest:digest(definition),hostContextId:durableHostContextId,
|
|
169
|
+
...(controlPolicy?{controlPolicy}:{}),
|
|
163
170
|
...(runtime==='claude'?{runtime}:{}),
|
|
164
171
|
...(options.reviewRuntime===undefined?{}:{reviewRuntime:options.reviewRuntime}),
|
|
165
172
|
...(executionPolicy?{executionPolicy}:{}),
|
|
@@ -174,13 +181,10 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
174
181
|
disabledSkills:review?.disabledSkills??[],
|
|
175
182
|
...resolveReviewTimeout(review,protection),
|
|
176
183
|
promptTransport:'stdin',schemaPath:fileURLToPath(new URL('./review-result.schema.json',import.meta.url))};
|
|
177
|
-
|
|
178
|
-
if(allowedAttempts.length||provider)need((reviewerRuntime==='codex'?preflightMatches:claudePreflightMatches)(reviewOptions.preflight,reviewOptions),'tool_preflight_missing');
|
|
184
|
+
if(review!==null||provider)need((reviewerRuntime==='codex'?preflightMatches:claudePreflightMatches)(reviewOptions.preflight,reviewOptions),'tool_preflight_missing');
|
|
179
185
|
need(reviewerRuntime!=='claude'||!review||review.disabledSkills.length===0,'invalid_review_config');
|
|
180
186
|
// Preserve P4a's unauthorizable placeholder bytes for existing unconfigured runs.
|
|
181
187
|
const reviewProvider=review?reviewerRuntime:'codex', adapterId=`${reviewProvider}-review-adapter`;
|
|
182
|
-
const authority=review?createHostReviewAuthority({hostContextId,reviewerId:'reviewer',adapterId,
|
|
183
|
-
decide:async binding=>allowedAttempts.includes(binding.identity.attempt)?{status:'approved'}:null}):null;
|
|
184
188
|
// Reread role declarations at each boundary; never switch a bound invocation.
|
|
185
189
|
// onWorker (provider development, task-runner.mjs) journals the worker's
|
|
186
190
|
// identity right before and right after the spawn; a journal failure kills
|
|
@@ -232,17 +236,17 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
232
236
|
const outerTimeoutMs=provider?protection.timeoutMs:1800000;
|
|
233
237
|
const progress=(request,control,stage,run,selectedRuntime=runtime)=>withHostProgress({definition,
|
|
234
238
|
identity:request.identity,runtime:selectedRuntime,stage,signal:control.signal},run);
|
|
235
|
-
const execution={configuration,timeoutMs:outerTimeoutMs,excludedContexts:[durableHostContextId],
|
|
239
|
+
const execution={configuration,timeoutMs:outerTimeoutMs,excludedContexts:[durableHostContextId],applicableAgentFiles:[],
|
|
236
240
|
...(verificationGate?{verificationGate:(request,control)=>progress(request,control,'verifying',()=>verificationGate(request,control))}:{}),
|
|
237
241
|
...(bootstrap?{bootstrap}:{}),
|
|
238
|
-
...(provider?{developmentAttempt:provider.attempt}:{}),
|
|
239
|
-
...(workflow?createHostWorkflowCapabilities({definition,configuration:workflow,bridge,allowQa,runtime,protectedExecution:protection!==null,bootstrap,parallelMember}):{}),
|
|
242
|
+
...(provider&&!controlPolicy?{developmentAttempt:provider.attempt}:{}),
|
|
243
|
+
...(workflow?createHostWorkflowCapabilities({definition,configuration:workflow,bridge,allowQa,runtime,protectedExecution:protection!==null,bootstrap,parallelMember,controlPolicy}):{}),
|
|
240
244
|
...(options.qaLogHome?{qaLogHome:options.qaLogHome}:{}),
|
|
241
|
-
...(authority?{hostDecisionProvider:authority.hostDecisionProvider}:{}),
|
|
242
245
|
developer:{provider:coderRuntime,requestedModel:provider?.model??'current-session',contextId:author,run:async(request,control)=>{
|
|
243
246
|
const bound=(coderRuntime==='codex'?readCodexDeveloperRequest:readClaudeDeveloperRequest)(request);
|
|
244
247
|
if(provider){
|
|
245
|
-
need(bound.identity.attempt
|
|
248
|
+
need((controlPolicy?[1,2].includes(bound.identity.attempt):bound.identity.attempt===provider.attempt)
|
|
249
|
+
&&digest({...bound.identity,attempt:1})===digest(definition.identity),'invalid_development_attempt');
|
|
246
250
|
need(!used.has(bound.invocationId),'duplicate_dispatch');used.add(bound.invocationId);
|
|
247
251
|
}
|
|
248
252
|
const route=provider?null:resolveHostRole({definition,identity:bound.identity,role:'coder',signal:control.signal,runtime});
|
|
@@ -314,7 +318,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
314
318
|
}
|
|
315
319
|
}
|
|
316
320
|
// CLI session identity comes from the observed process stream; current
|
|
317
|
-
// conversation responses retain the
|
|
321
|
+
// conversation responses retain the declared host context.
|
|
318
322
|
return {status:response.status,value:response.value,providerThread:provider?response.providerThread:hostContextId};
|
|
319
323
|
}
|
|
320
324
|
if(provider){const {providerThread,...failure}=response;shape(failure,['status','code']);return failure;}
|
|
@@ -329,8 +333,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
329
333
|
return bridge.call('check',{...request,codeProject:definition.codeProject,
|
|
330
334
|
scope:definition.scope,requirements:definition.requirements,route},control.signal);
|
|
331
335
|
}),
|
|
332
|
-
// The
|
|
333
|
-
// Diagnostic preflight alone never grants review dispatch.
|
|
336
|
+
// The process adapter records observed reviewer events. Preflight checks capability.
|
|
334
337
|
reviewers:[{id:'reviewer',adapterId,provider:reviewProvider,requestedModel:reviewOptions.model,
|
|
335
338
|
allowed:true,available:true,contexts:reviewContexts,
|
|
336
339
|
run:(request,control)=>{
|
|
@@ -350,8 +353,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
350
353
|
}}],
|
|
351
354
|
reviewInvocation:{developerThreadId:author,excludedThreadIds:[durableHostContextId],hostContextId,
|
|
352
355
|
// Not journaled (unlike timeoutMs above), so a resumed run may raise it.
|
|
353
|
-
timeoutMs:reviewRaceTimeout(outerTimeoutMs,reviewOptions.timeoutMs),
|
|
354
|
-
authorize:authority?.authorize??(()=>({status:'denied',code:'permission_denied'}))},
|
|
356
|
+
timeoutMs:reviewRaceTimeout(outerTimeoutMs,reviewOptions.timeoutMs)},
|
|
355
357
|
};
|
|
356
358
|
if(definition.codeProjects)execution.applicableAgentFiles=[...new Set([...execution.applicableAgentFiles,
|
|
357
359
|
...codeProjectInstructionPaths(codeProjectPaths(definition.codeProject,definition.codeProjects))
|
|
@@ -7,6 +7,8 @@ import {openFixExecution} from '../cm-fix/execution.mjs';
|
|
|
7
7
|
import {createFixHost} from '../cm-fix/host.mjs';
|
|
8
8
|
import {bindQaFixDefinition} from './qa-fix-definition.mjs';
|
|
9
9
|
import {digest,id,json,need,shape,validIdentity,hex} from './effect-contract.mjs';
|
|
10
|
+
import {readExecutionSnapshot} from './execution-snapshot.mjs';
|
|
11
|
+
import {readFixControlTarget,CONTROL_FIX_RECOVERY_OPERATIONS} from './control-policy.mjs';
|
|
10
12
|
|
|
11
13
|
// Q23: the child's recovery operations, each with the original cm-fix flag the
|
|
12
14
|
// shared dispatcher (cm-fix/host.mjs) checks and the parent flag that grants it.
|
|
@@ -23,7 +25,7 @@ const parentFlag=flag=>flag.replace(/^--allow-/,'--allow-qa-fix-');
|
|
|
23
25
|
const actionRefusal=(fixOperation,code,reason)=>Object.freeze({outcome:'rejected',code,fixOperation,reason,
|
|
24
26
|
guidance:Object.freeze({summary:'QA 修复子流程的这次操作被拒绝,子运行没有因此改变。',nextStep:reason,
|
|
25
27
|
recoveryOperation:null,prerequisites:Object.freeze([]),authorizationGranted:false})});
|
|
26
|
-
export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={},externalModels=null,executionPolicy=null,recoveryInvocationId=null}){
|
|
28
|
+
export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={},externalModels=null,executionPolicy=null,recoveryInvocationId=null,controlPolicy=null}){
|
|
27
29
|
id(hostContextId);id(parentHostContextId);
|
|
28
30
|
if(recoveryInvocationId!==null)id(recoveryInvocationId);
|
|
29
31
|
need((fix===null)!==(template===null),'invalid_fix_config');
|
|
@@ -81,7 +83,8 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
|
|
|
81
83
|
...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='reconcile_review'?['invocationId']:[]),
|
|
82
84
|
...(QA_FIX_REASONED.includes(request.fixOperation)&&Object.hasOwn(request,'reason')?['reason']:[]),
|
|
83
85
|
...(request.fixOperation==='prepare_revision'&&Object.hasOwn(request,'tests')?['tests']:[]),
|
|
84
|
-
...(request.fixOperation==='recover_final_review'?['invocationId','reviewPackageDigest','previousInvocationStopped','reason']:[])]:[])
|
|
86
|
+
...(request.fixOperation==='recover_final_review'?['invocationId','reviewPackageDigest','previousInvocationStopped','reason']:[])]:[]),
|
|
87
|
+
...(controlPolicy&&request.operation==='fix_action'&&CONTROL_FIX_RECOVERY_OPERATIONS.includes(request.fixOperation)?['expectedFixControl']:[])]);
|
|
85
88
|
need(value.version===1,'invalid_input');id(value.requestId);validIdentity(value.identity);hex(value.packageDigest);id(value.testRunId);
|
|
86
89
|
if(fixedTemplate)definition=bindQaFixDefinition({template:fixedTemplate,identity:value.identity,
|
|
87
90
|
packageDigest:value.packageDigest,testRunId:value.testRunId});
|
|
@@ -110,6 +113,11 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
|
|
|
110
113
|
if(advancing&&!existing)need([hostContextId,parentHostContextId].includes(definition.configuration.hostContextId),'qa_fix_host_mismatch');
|
|
111
114
|
child=openFixExecution({...definition,hostContextId,create:advancing&&!existing},advancing||acting?fixExecution:{});
|
|
112
115
|
activeChild=child;
|
|
116
|
+
const childTarget=()=>readFixControlTarget({runId:definition.identity.runId,stage:child.status().stage,
|
|
117
|
+
revision:readExecutionSnapshot({specsRoot:definition.specsRoot,
|
|
118
|
+
identity:{repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}}).revision});
|
|
119
|
+
if(controlPolicy&&acting&&CONTROL_FIX_RECOVERY_OPERATIONS.includes(value.fixOperation))
|
|
120
|
+
need(digest(readFixControlTarget(value.expectedFixControl))===digest(childTarget()),'snapshot_changed');
|
|
113
121
|
let actionResult;
|
|
114
122
|
if(advancing||acting){
|
|
115
123
|
const host=createFixHost({owner:child,config:{...definition.configuration,specsRoot:definition.specsRoot,identity:definition.identity},
|
|
@@ -138,6 +146,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
|
|
|
138
146
|
?json({outcome:'verified',code:'qa_fix_completed',evidence:child.completionEvidence()},12*1024*1024)
|
|
139
147
|
:json({outcome:'blocked',code:'qa_fix_incomplete',fixStage:observed.stage,
|
|
140
148
|
...(acting?{actionResult}: {})},12*1024*1024);
|
|
149
|
+
if(controlPolicy&&value.operation==='fix_status')result={...result,childControlTarget:childTarget()};
|
|
141
150
|
}finally{
|
|
142
151
|
try{activeChild=null;child?.close();if(released)current=await reopenParent();}
|
|
143
152
|
finally{busy=false;switching=false;}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// N6
|
|
1
|
+
// N6 fixed checkpoints over registered paths and runner-proven changes.
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import {inspectCmAiQaTaskContext} from './cm-ai-admission.mjs';
|
|
@@ -28,43 +28,85 @@ function history(binding,context) {
|
|
|
28
28
|
return new Set([...unseen,...since,key(binding.feature,binding.identity.taskId)]).size;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
31
|
+
const categories=['migration','authentication','authorization','payment','api'];
|
|
32
|
+
|
|
33
|
+
// Deliberately bounded POSIX glob grammar: literals, *, ?, and whole-segment **.
|
|
34
|
+
// A registry never imports executable patterns, absolute roots or parent traversal.
|
|
35
|
+
function relativePath(value,pattern=false){
|
|
36
|
+
need(typeof value==='string'&&value.length>0&&value.length<=1024&&!/[\\\r\n\0]/.test(value)
|
|
37
|
+
&&!value.startsWith('/')&&!/^[A-Za-z]:/.test(value),'qa_assessment_invalid');
|
|
38
|
+
const parts=value.split('/');
|
|
39
|
+
need(parts.every(part=>part.length>0&&part!=='.'&&part!=='..'),'qa_assessment_invalid');
|
|
40
|
+
if(pattern)need(!/[\[\]{}()!+@]/.test(value)&&parts.every(part=>!part.includes('**')||part==='**'),'qa_assessment_invalid');
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
export function readQaCriticalPaths(raw={}){
|
|
44
|
+
const registry=json(raw);need(registry&&typeof registry==='object'&&!Array.isArray(registry),'qa_assessment_invalid');
|
|
45
|
+
need(Object.keys(registry).every(name=>categories.includes(name)),'qa_assessment_invalid');
|
|
46
|
+
for(const patterns of Object.values(registry)){
|
|
47
|
+
need(Array.isArray(patterns)&&patterns.length<=256&&new Set(patterns).size===patterns.length,'qa_assessment_invalid');
|
|
48
|
+
patterns.forEach(pattern=>relativePath(pattern,true));
|
|
49
|
+
}
|
|
50
|
+
return registry;
|
|
51
|
+
}
|
|
52
|
+
function matchesPath(file,pattern){
|
|
53
|
+
const segments=pattern.split('/');
|
|
54
|
+
const source=segments.map((part,index)=>part==='**'
|
|
55
|
+
?index===segments.length-1?'.*':'(?:[^/]+/)*'
|
|
56
|
+
:part.replace(/[.*+?^${}()|[\]\\]/g,char=>char==='*'?'[^/]*':char==='?'?'[^/]':`\\${char}`)
|
|
57
|
+
+(index===segments.length-1?'':'/')).join('');
|
|
58
|
+
return new RegExp(`^${source}$`).test(file);
|
|
59
|
+
}
|
|
60
|
+
export function readQaAssessment(raw){
|
|
61
|
+
const value=json(raw);shape(value,['confirmed']);need(value.confirmed===true,'qa_assessment_invalid');
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
export function readQaChangedFiles(raw){
|
|
65
|
+
const value=json(raw);shape(value,['paths','source']);
|
|
66
|
+
need(['review_package','handoff_only','unavailable'].includes(value.source),'qa_policy_unavailable');
|
|
67
|
+
need(Array.isArray(value.paths)&&value.paths.length<=10000&&new Set(value.paths).size===value.paths.length,'qa_policy_unavailable');
|
|
68
|
+
value.paths.forEach(file=>relativePath(file));
|
|
69
|
+
need(value.source!=='unavailable'||value.paths.length===0,'qa_policy_unavailable');
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
export function decideHostQaPolicy({changedFiles,criticalPaths={},pending,mergeEligible,unassessedTasks}) {
|
|
73
|
+
const registry=readQaCriticalPaths(criticalPaths);
|
|
74
|
+
need(Array.isArray(changedFiles)&&new Set(changedFiles).size===changedFiles.length,'qa_policy_unavailable');
|
|
75
|
+
changedFiles.forEach(file=>relativePath(file));
|
|
37
76
|
need(Number.isSafeInteger(pending)&&pending>=0&&typeof mergeEligible==='boolean'
|
|
38
77
|
&&Number.isSafeInteger(unassessedTasks)&&unassessedTasks>=1,'qa_policy_unavailable');
|
|
39
78
|
need(!mergeEligible||pending===1,'qa_policy_unavailable');
|
|
40
|
-
const
|
|
79
|
+
const hits=new Set(categories.filter(name=>(registry[name]??[]).some(pattern=>changedFiles.some(file=>matchesPath(file,pattern)))));
|
|
41
80
|
const reasons=[];
|
|
42
81
|
if(pending===0)reasons.push('feature_complete');
|
|
43
|
-
for(const name of
|
|
82
|
+
for(const name of categories.slice(0,-1))if(hits.has(name))reasons.push(name);
|
|
44
83
|
if(unassessedTasks>=5)reasons.push('five_tasks_without_qa');
|
|
45
|
-
if(
|
|
84
|
+
if(hits.has('api')&&!mergeEligible)reasons.push('api');
|
|
46
85
|
if(reasons.length)return {status:'triggered',score:null,reason:reasons.join(',')};
|
|
47
|
-
|
|
48
|
-
return {status:'skipped',score,reason:value.changes.api&&mergeEligible?'merged_to_feature_qa':'risk_score_below_threshold'};
|
|
86
|
+
return {status:'skipped',score:null,reason:hits.has('api')&&mergeEligible?'merged_to_feature_qa':'no_fixed_trigger'};
|
|
49
87
|
}
|
|
50
88
|
|
|
51
89
|
// Plug directly into the existing trusted qaDecisionProvider seam. The host
|
|
52
|
-
//
|
|
53
|
-
export function createHostQaDecisionProvider({assess,timeoutMs}) {
|
|
90
|
+
// confirms the supplied inventory source; JS owns the decision and binding.
|
|
91
|
+
export function createHostQaDecisionProvider({assess,timeoutMs,criticalPaths={}}) {
|
|
92
|
+
const registry=readQaCriticalPaths(criticalPaths);
|
|
54
93
|
need(typeof assess==='function'&&Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=60000,'qa_assessment_invalid');
|
|
55
94
|
return Object.freeze({timeoutMs,async decide(raw,signal){
|
|
56
95
|
const input=json(raw);
|
|
57
|
-
shape(input,['specsDir','codeProject','feature','identity','packageDigest',...(Object.hasOwn(input,'previousDecisionId')?['previousDecisionId']:[])
|
|
96
|
+
shape(input,['specsDir','codeProject','feature','identity','packageDigest',...(Object.hasOwn(input,'previousDecisionId')?['previousDecisionId']:[]),
|
|
97
|
+
...(Object.hasOwn(input,'changedFiles')?['changedFiles']:[])]);
|
|
58
98
|
// previousDecisionId names an older recorded decision that an explicit
|
|
59
99
|
// recovery supersedes; it only derives a distinct id, never the assessment.
|
|
60
|
-
const {previousDecisionId=null,...binding}=input;
|
|
100
|
+
const {previousDecisionId=null,changedFiles:rawFiles={paths:[],source:'unavailable'},...binding}=input;
|
|
101
|
+
const changedFiles=readQaChangedFiles(rawFiles);
|
|
102
|
+
need(changedFiles.source!=='unavailable'||!Object.values(registry).some(patterns=>patterns.length),'qa_policy_unavailable');
|
|
103
|
+
if(previousDecisionId!==null)id(previousDecisionId);
|
|
61
104
|
validIdentity(binding.identity);hex(binding.packageDigest);
|
|
62
105
|
const context=inspectCmAiQaTaskContext({...binding,taskId:binding.identity.taskId});
|
|
63
106
|
const unassessedTasks=history(binding,context);
|
|
64
107
|
need(!signal.aborted,'cancelled');
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
unassessedTasks}),signal);}
|
|
108
|
+
try{readQaAssessment(await assess(freeze({...binding,pending:context.pending,mergeEligible:context.mergeEligible,
|
|
109
|
+
unassessedTasks,changedFiles,criticalPaths:registry}),signal));}
|
|
68
110
|
catch(error){
|
|
69
111
|
// A missed answer window is a transport outcome, not a QA decision. It is
|
|
70
112
|
// reported like the outer decision timer: retryable, and nothing durable.
|
|
@@ -76,9 +118,9 @@ export function createHostQaDecisionProvider({assess,timeoutMs}) {
|
|
|
76
118
|
// another decision; do not bind an answer to different policy inputs.
|
|
77
119
|
const current=inspectCmAiQaTaskContext({...binding,taskId:binding.identity.taskId});
|
|
78
120
|
need(digest(current)===digest(context)&&history(binding,current)===unassessedTasks,'stale_qa');
|
|
79
|
-
const result=decideHostQaPolicy({
|
|
121
|
+
const result=decideHostQaPolicy({changedFiles:changedFiles.paths,criticalPaths:registry,pending:context.pending,mergeEligible:context.mergeEligible,unassessedTasks});
|
|
80
122
|
const bound={identity:binding.identity,packageDigest:binding.packageDigest,...(previousDecisionId===null?{}:{previousDecisionId})};
|
|
81
123
|
return freeze({...result,decisionId:`qa-${digest(bound).slice(0,48)}`,
|
|
82
|
-
identity:binding.identity,packageDigest:binding.packageDigest,at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')});
|
|
124
|
+
identity:binding.identity,packageDigest:binding.packageDigest,changedFilesSource:changedFiles.source,at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')});
|
|
83
125
|
}});
|
|
84
126
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// CMFIX legacy decision-to-grant consistency adapter. It does not verify a person
|
|
2
|
+
// or an independent identity. cm-ai no longer calls this adapter.
|
|
3
3
|
import {randomUUID} from 'node:crypto';
|
|
4
4
|
import {digest,id,json,need,shape,validIdentity} from './effect-contract.mjs';
|
|
5
5
|
|
|
@@ -15,7 +15,7 @@ export function publishHostReview({reviewsDir,feature,handoffPath,reviewPackage,
|
|
|
15
15
|
const {receiptDigest,...body}=r;
|
|
16
16
|
need(receiptDigest===digest(body)&&r.packageDigest===pkg.packageDigest
|
|
17
17
|
&&digest(r.identity)===digest(pkg.identity),'review_package_mismatch');
|
|
18
|
-
need(r.execution.channel
|
|
18
|
+
need(['host-review','host-authorized'].includes(r.execution.channel)&&r.execution.started===true
|
|
19
19
|
&&r.execution.terminal==='succeeded'&&['codex','claude'].includes(r.execution.provider),'execution_mismatch');
|
|
20
20
|
id(r.execution.providerThreadId);
|
|
21
21
|
const result=reviewResult(r.result,pkg);
|
|
@@ -3,6 +3,7 @@ import {randomUUID} from 'node:crypto';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import {executionDiagnostic,need} from './effect-contract.mjs';
|
|
5
5
|
import {diagnosticReason} from './diagnostic-reason.mjs';
|
|
6
|
+
import {withHostStageObserver} from './host-stage-observer.mjs';
|
|
6
7
|
|
|
7
8
|
const LIMIT=64*1024;
|
|
8
9
|
// One wording for every host that stops on an over-limit line.
|
|
@@ -53,11 +54,18 @@ function idleNotice(sessionKey,seq,row,since){
|
|
|
53
54
|
// A line above the transport limit ends the session. Carry a code and the
|
|
54
55
|
// limit so every host can name it instead of a generic launch failure.
|
|
55
56
|
const tooLarge=limit=>Object.assign(new Error('request_too_large'),{code:'request_too_large',limit});
|
|
56
|
-
export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimit=LIMIT,errorOutput=process.stderr}){
|
|
57
|
+
export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimit=LIMIT,errorOutput=process.stderr,heartbeat=process.env.CM_HOST_HEARTBEAT==='1'}){
|
|
57
58
|
if(!Number.isSafeInteger(inputLimit)||inputLimit<LIMIT||inputLimit>4*1024*1024)throw Error('input_limit_invalid');
|
|
58
59
|
let pending=null,buffer=Buffer.alloc(0),failure=null,closeRequested=false;
|
|
59
60
|
let writing=Promise.resolve();
|
|
60
|
-
const controls=new Set();let queuedWrites=0;
|
|
61
|
+
const controls=new Set(),activeControls=new Map();let queuedWrites=0,activeOperation=null;
|
|
62
|
+
let progressAt=Date.now(),heartbeatTimer=null,heartbeatWriting=false;
|
|
63
|
+
const inFlight=()=>{
|
|
64
|
+
const operation=activeOperation??activeControls.values().next().value??null;
|
|
65
|
+
const call=toolBridge?.inFlight?.()??null;
|
|
66
|
+
return operation?{...operation,stage:call?.kind??operation.nativeStage?.kind??operation.operation,call}:
|
|
67
|
+
call?{requestId:null,operation:null,startedAt:call.startedAt,stage:call.kind,call}:null;
|
|
68
|
+
};
|
|
61
69
|
const sessionKey=randomUUID(),startedAt=Date.now();let idle=null,seq=0,ended=false,lastRow=undefined,idleSince=0;
|
|
62
70
|
// Host registry (runtime/js/notify.mjs): serialised so a session that ends at
|
|
63
71
|
// once still removes its own entry. Each step is best-effort and synchronous.
|
|
@@ -93,7 +101,21 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
|
|
|
93
101
|
writing.catch(error=>{failure=error;});
|
|
94
102
|
return writing;
|
|
95
103
|
};
|
|
96
|
-
toolBridge?.attach(reply);
|
|
104
|
+
toolBridge?.attach(reply,{heartbeat});
|
|
105
|
+
// Opt-in transport telemetry: no runner reads, journal writes or fingerprint changes.
|
|
106
|
+
// Keep at most one heartbeat queued so a slow peer cannot accumulate timer output.
|
|
107
|
+
if(heartbeat&&toolBridge){
|
|
108
|
+
const beat=()=>{
|
|
109
|
+
if(ended||failure||closeRequested||heartbeatWriting||queuedWrites>0)return;
|
|
110
|
+
heartbeatWriting=true;
|
|
111
|
+
reply({type:'host_heartbeat',sessionId:toolBridge.sessionId,pid:process.pid,at:new Date().toISOString(),
|
|
112
|
+
lastProgressAt:new Date(Math.max(progressAt,toolBridge.lastProgressAt?.()??0)).toISOString(),inFlight:inFlight()})
|
|
113
|
+
.catch(error=>{failure=error;}).finally(()=>{heartbeatWriting=false;});
|
|
114
|
+
};
|
|
115
|
+
// ready is already queued; send the first beat immediately after that write.
|
|
116
|
+
writing.then(beat).catch(()=>{});
|
|
117
|
+
heartbeatTimer=setInterval(beat,5000);heartbeatTimer.unref?.();
|
|
118
|
+
}
|
|
97
119
|
async function dispatch(bytes){
|
|
98
120
|
if(failure)throw failure;
|
|
99
121
|
let request;
|
|
@@ -101,7 +123,7 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
|
|
|
101
123
|
request=JSON.parse(bytes.toString('utf8'));
|
|
102
124
|
if(POLLS.has(request?.operation))clearIdle();else nextStep();
|
|
103
125
|
if(toolBridge!==null&&['host_result','host_close'].includes(request?.type)){
|
|
104
|
-
const accepted=toolBridge.accept(request);closeRequested=accepted.closing===true;
|
|
126
|
+
const accepted=toolBridge.accept(request,{inFlight:inFlight()});closeRequested=accepted.closing===true;
|
|
105
127
|
reply({type:'host_response',...accepted}).catch(error=>{failure=error;});return;
|
|
106
128
|
}
|
|
107
129
|
if(!request||typeof request!=='object'||Array.isArray(request)
|
|
@@ -110,11 +132,20 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
|
|
|
110
132
|
}catch{nextStep();reply({requestId:null,error:{code:'invalid_request'}}).catch(error=>{failure=error;});return;}
|
|
111
133
|
const requestId=request.requestId;
|
|
112
134
|
let row=null;
|
|
135
|
+
let operationActive=false,metadata=null;
|
|
136
|
+
const release=()=>{if(!operationActive)return;operationActive=false;
|
|
137
|
+
if(activeOperation===metadata)activeOperation=null;
|
|
138
|
+
activeControls.delete(request);if(!POLLS.has(request.operation))progressAt=Date.now();};
|
|
139
|
+
const begin=control=>{operationActive=true;const at=Date.now();if(!POLLS.has(request.operation))progressAt=at;
|
|
140
|
+
metadata={requestId,operation:request.operation,startedAt:new Date(at).toISOString(),nativeStage:null};
|
|
141
|
+
if(control)activeControls.set(request,metadata);else activeOperation=metadata;};
|
|
113
142
|
const invoke=async()=>{
|
|
114
|
-
try{const result=await
|
|
143
|
+
try{const result=await withHostStageObserver(stage=>{
|
|
144
|
+
if(operationActive){metadata.nativeStage=stage;if(!POLLS.has(request.operation))progressAt=Date.now();}
|
|
145
|
+
},()=>host.handle(request));row={result};release();await reply({requestId,result});}
|
|
115
146
|
catch(error){
|
|
116
147
|
reportRequestFailure(errorOutput,request.operation,error);
|
|
117
|
-
row={error:{code:'host_request_failed'}};
|
|
148
|
+
row={error:{code:'host_request_failed'}};release();
|
|
118
149
|
await reply({requestId,...row});
|
|
119
150
|
}
|
|
120
151
|
finally{if(!POLLS.has(request.operation))register(row,request.operation);}
|
|
@@ -123,10 +154,12 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
|
|
|
123
154
|
if(request.operation==='status'||request.operation==='cancel'){
|
|
124
155
|
// The input reader must not wait for a slow response consumer before it
|
|
125
156
|
// can deliver the next control request (especially cancellation).
|
|
157
|
+
begin(true);
|
|
126
158
|
const control=invoke().finally(()=>{controls.delete(control);finished(row,request.operation);});
|
|
127
159
|
controls.add(control);control.catch(error=>{failure=error;});return;
|
|
128
160
|
}
|
|
129
|
-
if(pending){reply({requestId,error:{code:'host_busy'}}).catch(error=>{failure=error;});return;}
|
|
161
|
+
if(pending){reply({requestId,error:{code:'host_busy',inFlight:inFlight(),message:'上一步仍在执行,请继续等待该请求的结果。'}}).catch(error=>{failure=error;});return;}
|
|
162
|
+
begin(false);
|
|
130
163
|
pending=invoke().finally(()=>{pending=null;finished(row,request.operation);});
|
|
131
164
|
pending.catch(error=>{failure=error;});
|
|
132
165
|
}
|
|
@@ -150,7 +183,7 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
|
|
|
150
183
|
}finally{
|
|
151
184
|
// With a duplex conversation, EOF means no more tool replies can arrive.
|
|
152
185
|
// Reject that wait as disconnected, not as an explicit user cancellation.
|
|
153
|
-
toolBridge?.close();ended=true;clearIdle();
|
|
186
|
+
toolBridge?.close();ended=true;clearInterval(heartbeatTimer);clearIdle();
|
|
154
187
|
// EOF is not a user cancellation. Finish the in-flight result before close.
|
|
155
188
|
try{await Promise.allSettled([...(pending?[pending]:[]),...controls,writing]);}
|
|
156
189
|
finally{
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Process-local transport telemetry only. No durable state, authority or timers.
|
|
2
|
+
import {AsyncLocalStorage} from 'node:async_hooks';
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
const operations=new AsyncLocalStorage();
|
|
6
|
+
const emit=context=>{
|
|
7
|
+
if(context.closed)return;
|
|
8
|
+
const stages=[...context.stages.values()],latest=stages.at(-1);
|
|
9
|
+
const snapshot=latest?Object.freeze({...latest,deadlineMs:Math.min(...stages.map(stage=>stage.deadlineMs))}):null;
|
|
10
|
+
try{context.observer(snapshot);}catch{/* diagnostic observers cannot change execution */}
|
|
11
|
+
};
|
|
12
|
+
export async function withHostStageObserver(observer,run){
|
|
13
|
+
const context={observer,stages:new Map(),closed:false};
|
|
14
|
+
return operations.run(context,async()=>{
|
|
15
|
+
try{return await run();}
|
|
16
|
+
finally{context.stages.clear();emit(context);context.closed=true;}
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export function beginHostStage(kind,timeoutMs){
|
|
20
|
+
const context=operations.getStore();
|
|
21
|
+
if(!context||context.closed||!Number.isSafeInteger(timeoutMs)||timeoutMs<1)return ()=>{};
|
|
22
|
+
const now=Date.now(),id=randomUUID();
|
|
23
|
+
context.stages.set(id,{id,kind,startedAt:new Date(now).toISOString(),deadlineMs:now+timeoutMs});emit(context);
|
|
24
|
+
let ended=false;
|
|
25
|
+
return ()=>{if(ended||context.closed)return;ended=true;context.stages.delete(id);emit(context);};
|
|
26
|
+
}
|
|
@@ -30,6 +30,9 @@ export function hostAnswerTimeoutMs(env=process.env){
|
|
|
30
30
|
need(/^[1-9][0-9]?$/.test(raw)&&Number(raw)<=60,'host_answer_timeout_invalid');
|
|
31
31
|
return Number(raw)*60000;
|
|
32
32
|
}
|
|
33
|
+
// qa_assess carries runner-proven changedFiles and project criticalPaths. Its
|
|
34
|
+
// consumer validates only {confirmed:true}; scores/semantic risk flags are not
|
|
35
|
+
// part of this kind's business contract. The bridge remains transport-only.
|
|
33
36
|
// Every kind a workflow host may ask the session. A kind missing here makes
|
|
34
37
|
// that step throw host_operation_invalid on every attempt (O20: the second-round
|
|
35
38
|
// refactor judge revision, refactor_revise_tests, was missing).
|
|
@@ -45,19 +48,25 @@ const lateDiagnostic=fields=>{try{process.stderr.write(JSON.stringify({diagnosti
|
|
|
45
48
|
export function createHostToolBridge({responseLimit=64*1024,answerTimeoutMs=hostAnswerTimeoutMs()}={}){
|
|
46
49
|
need(Number.isSafeInteger(responseLimit)&&responseLimit>=64*1024&&responseLimit<=4*1024*1024,'host_response_limit_invalid');
|
|
47
50
|
need(Number.isSafeInteger(answerTimeoutMs)&&answerTimeoutMs>=1000&&answerTimeoutMs<=HOST_ANSWER_BACKSTOP_MS,'host_answer_timeout_invalid');
|
|
48
|
-
const sessionId=randomUUID();let send=null,pending=null,closed=false;
|
|
51
|
+
const sessionId=randomUUID();let send=null,pending=null,closed=false,lastProgressAt=Date.now();
|
|
52
|
+
// Metadata only: never expose the request payload or answer through liveness.
|
|
53
|
+
const inFlight=()=>pending?{callId:pending.request.callId,kind:pending.request.kind,
|
|
54
|
+
startedAt:new Date(pending.startedAt).toISOString(),deadlineMs:pending.deadlineMs}:null;
|
|
49
55
|
const stopped=new Map();
|
|
50
56
|
const stop=(code,call=pending)=>{
|
|
51
|
-
if(!call||pending!==call)return;pending=null;clearTimeout(call.timer);call.notice?.();
|
|
57
|
+
if(!call||pending!==call)return;pending=null;lastProgressAt=Date.now();clearTimeout(call.timer);call.notice?.();
|
|
52
58
|
call.signal.removeEventListener('abort',call.abort);
|
|
53
59
|
if(code!=='host_disconnected'){stopped.set(call.request.callId,{kind:call.request.kind,stoppedBy:code});
|
|
54
60
|
if(stopped.size>LATE_CALLS)stopped.delete(stopped.keys().next().value);}
|
|
55
61
|
call.reject(Object.assign(new Error(code),{code}));
|
|
56
62
|
};
|
|
57
63
|
return Object.freeze({
|
|
58
|
-
|
|
64
|
+
sessionId,
|
|
65
|
+
inFlight,
|
|
66
|
+
lastProgressAt:()=>lastProgressAt,
|
|
67
|
+
attach(sender,{heartbeat=false}={}){
|
|
59
68
|
need(send===null&&typeof sender==='function'&&!closed,'host_bridge_unavailable');send=sender;
|
|
60
|
-
Promise.resolve(send({type:'host_ready',sessionId})).catch(()=>{closed=true;stop('host_disconnected');});
|
|
69
|
+
Promise.resolve(send({type:'host_ready',sessionId,...(heartbeat?{heartbeat:{intervalMs:5000,timeoutMs:30000}}:{})})).catch(()=>{closed=true;stop('host_disconnected');});
|
|
61
70
|
},
|
|
62
71
|
call(kind,payload,signal,{timeoutMs=null}={}){
|
|
63
72
|
need(send!==null&&!closed,'host_bridge_unavailable');need(pending===null,'host_bridge_busy');
|
|
@@ -70,7 +79,9 @@ export function createHostToolBridge({responseLimit=64*1024,answerTimeoutMs=host
|
|
|
70
79
|
stop('cancelled',call);
|
|
71
80
|
Promise.resolve(send({type:'host_call_cancelled',sessionId,callId:request.callId})).catch(()=>{});
|
|
72
81
|
};
|
|
73
|
-
const
|
|
82
|
+
const startedAt=Date.now(),duration=timeoutMs??(COMMAND_KINDS.has(kind)?Math.max(answerTimeoutMs,HOST_ANSWER_TIMEOUT_MAX_MS):answerTimeoutMs);
|
|
83
|
+
const call={request,signal,abort,resolve,reject,startedAt,deadlineMs:startedAt+duration,timer:null,notice:waitNotice(kind,request.callId)};
|
|
84
|
+
pending=call;lastProgressAt=startedAt;
|
|
74
85
|
if(timeoutMs!==null)call.timer=setTimeout(()=>stop('host_request_timeout',call),timeoutMs);
|
|
75
86
|
// The default deadline never keeps an otherwise finished process alive.
|
|
76
87
|
else {call.timer=setTimeout(()=>stop('host_request_timeout',call),
|
|
@@ -82,12 +93,17 @@ export function createHostToolBridge({responseLimit=64*1024,answerTimeoutMs=host
|
|
|
82
93
|
}).catch(()=>stop('host_disconnected',call));
|
|
83
94
|
});
|
|
84
95
|
},
|
|
85
|
-
accept(raw){
|
|
96
|
+
accept(raw,{inFlight:operation=null}={}){
|
|
86
97
|
let reply;
|
|
87
98
|
try{
|
|
88
99
|
if(raw?.type==='host_close'){
|
|
89
|
-
shape(raw,['type','sessionId']);need(raw.sessionId===sessionId&&!closed,'host_response_mismatch');
|
|
90
|
-
|
|
100
|
+
shape(raw,['type','sessionId',...(Object.hasOwn(raw,'force')?['force']:[])]);need(raw.sessionId===sessionId&&!closed,'host_response_mismatch');
|
|
101
|
+
need(raw.force===undefined||typeof raw.force==='boolean','host_response_mismatch');
|
|
102
|
+
const active=operation??(pending?{requestId:null,operation:null,startedAt:inFlight().startedAt,stage:pending.request.kind,call:inFlight()}:null);
|
|
103
|
+
if(active&&raw.force!==true)return {accepted:false,code:'host_close_busy',inFlight:active,
|
|
104
|
+
message:'上一步仍在执行,请继续等待其结果;只有明确放弃本次在途工作时才传 force:true。'};
|
|
105
|
+
closed=true;stop('host_disconnected');return {accepted:true,closing:true,...(active?{
|
|
106
|
+
warning:'已强制关闭在途工作,原运行可能进入 unknown;请核对原运行状态后恢复。',inFlight:active}:{})};
|
|
91
107
|
}
|
|
92
108
|
reply=json(raw,responseLimit);shape(reply,['type','sessionId','callId','requestDigest','result']);
|
|
93
109
|
const late=reply.type==='host_result'&&reply.sessionId===sessionId&&pending?.request.callId!==reply.callId
|
|
@@ -97,7 +113,7 @@ export function createHostToolBridge({responseLimit=64*1024,answerTimeoutMs=host
|
|
|
97
113
|
need(reply.type==='host_result'&&pending!==null&&!closed,'host_response_mismatch');
|
|
98
114
|
for(const key of ['sessionId','callId','requestDigest'])need(reply[key]===pending.request[key],'host_response_mismatch');
|
|
99
115
|
}catch(error){return {accepted:false,code:error?.code==='limit_exceeded'?'host_response_too_large':'host_response_mismatch'};}
|
|
100
|
-
const call=pending;pending=null;clearTimeout(call.timer);call.notice?.();call.signal.removeEventListener('abort',call.abort);
|
|
116
|
+
const call=pending;pending=null;lastProgressAt=Date.now();clearTimeout(call.timer);call.notice?.();call.signal.removeEventListener('abort',call.abort);
|
|
101
117
|
call.resolve(reply.result);return {accepted:true,callId:reply.callId};
|
|
102
118
|
},
|
|
103
119
|
close(){closed=true;stop('host_disconnected');},
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import {digest,json,need,shape,validIdentity,hex} from './effect-contract.mjs';
|
|
5
|
-
import {createHostQaDecisionProvider} from './host-qa-policy.mjs';
|
|
5
|
+
import {createHostQaDecisionProvider,readQaCriticalPaths} from './host-qa-policy.mjs';
|
|
6
6
|
import {createHostQaExecutor} from './host-qa-executor.mjs';
|
|
7
7
|
import {loadConfig} from '../../../scripts/cm-workflow-config.mjs';
|
|
8
8
|
import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
|
|
@@ -56,7 +56,9 @@ export function validateHostWorkflowConfiguration(raw){
|
|
|
56
56
|
for(const key of ['documentationPaths','applicableAgentFiles'])
|
|
57
57
|
need(Array.isArray(config[key])&&config[key].length<=256&&config[key].every(item=>typeof item==='string'),'invalid_workflow_config');
|
|
58
58
|
if(config.qa!==null){
|
|
59
|
-
shape(config.qa,['commands','environment',...(Object.hasOwn(config.qa,'timeoutMs')?['timeoutMs']:[])
|
|
59
|
+
shape(config.qa,['commands','environment',...(Object.hasOwn(config.qa,'timeoutMs')?['timeoutMs']:[]),
|
|
60
|
+
...(Object.hasOwn(config.qa,'criticalPaths')?['criticalPaths']:[])]);
|
|
61
|
+
if(Object.hasOwn(config.qa,'criticalPaths'))readQaCriticalPaths(config.qa.criticalPaths);
|
|
60
62
|
// A real browser walkthrough of one blocking case runs for minutes, so this
|
|
61
63
|
// follows the shared call-timeout range rather than a fixed minute. The
|
|
62
64
|
// default below is unchanged; only an explicit configuration may raise it.
|
|
@@ -66,7 +68,7 @@ export function validateHostWorkflowConfiguration(raw){
|
|
|
66
68
|
return config;
|
|
67
69
|
}
|
|
68
70
|
|
|
69
|
-
export function createHostWorkflowCapabilities({definition,configuration,bridge,allowQa,runtime='codex',protectedExecution=false,bootstrap=null,parallelMember=false}){
|
|
71
|
+
export function createHostWorkflowCapabilities({definition,configuration,bridge,allowQa,runtime='codex',protectedExecution=false,bootstrap=null,parallelMember=false,controlPolicy=null}){
|
|
70
72
|
need(['codex','claude'].includes(runtime),'invalid_runtime');
|
|
71
73
|
const {specsDir,codeProject,feature,requirements}=definition;
|
|
72
74
|
const logHome=path.join(specsDir,'.reviews','host-log-mirror');
|
|
@@ -74,18 +76,25 @@ export function createHostWorkflowCapabilities({definition,configuration,bridge,
|
|
|
74
76
|
documentationProvider:{timeoutMs:60000,inspect:(request,signal)=>bridge.call('documentation_inspect',request,signal)}};
|
|
75
77
|
if(!protectedExecution&&configuration.documentationPaths.length)result.documentationSync={paths:configuration.documentationPaths,
|
|
76
78
|
run:(request,signal)=>bridge.call('documentation_sync',request,signal)};
|
|
77
|
-
|
|
78
|
-
|
|
79
|
+
// The N6 disposition is required even when execution is disabled. Its
|
|
80
|
+
// fixed checkpoints and registered path matches may require QA;
|
|
81
|
+
// only a configured executor can then supply actual execution evidence.
|
|
82
|
+
// Legacy qa:null keeps its historical caller-supplied disposition contract.
|
|
83
|
+
if(configuration.qa!==null||controlPolicy!==null){
|
|
79
84
|
result.qaLogHome=logHome;
|
|
80
|
-
const requestTimeout={timeoutMs:configuration.qa
|
|
81
|
-
result.qaDecisionProvider=parallelMember?createParallelMemberQaDecisionProvider():createHostQaDecisionProvider({timeoutMs:60000,
|
|
85
|
+
const requestTimeout={timeoutMs:configuration.qa?.timeoutMs??60000};
|
|
86
|
+
result.qaDecisionProvider=parallelMember?createParallelMemberQaDecisionProvider():createHostQaDecisionProvider({timeoutMs:60000,criticalPaths:configuration.qa?.criticalPaths??{},
|
|
82
87
|
assess:(request,signal)=>bridge.call('qa_assess',request,signal,requestTimeout)});
|
|
88
|
+
}
|
|
89
|
+
if(configuration.qa!==null&&(controlPolicy===null||controlPolicy.qa==='run')){
|
|
90
|
+
need(allowQa===true,'qa_authorization_required');
|
|
91
|
+
const requestTimeout={timeoutMs:configuration.qa.timeoutMs??60000};
|
|
83
92
|
// requestTimeoutMs stays outside the fingerprinted executor configuration;
|
|
84
93
|
// timed-out QA recovery reads older case_blocked rows against it.
|
|
85
94
|
result.qaExecutor=Object.freeze({...createHostQaExecutor({specsDir,codeProject,feature,requirements,runtime,
|
|
86
95
|
...(definition.codeProjects?{codeProjects:definition.codeProjects}:{}),
|
|
87
96
|
...(bootstrap?{bootstrap:{requirements:bootstrap.configuration.bootstrapRequirements,scope:definition.scope}}:{}),
|
|
88
|
-
|
|
97
|
+
commands:configuration.qa.commands,environment:configuration.qa.environment,timeoutMs:1800000,logHome,
|
|
89
98
|
...(protectedExecution?{specsRoot:specsDir}:{}),
|
|
90
99
|
logic:(request,signal)=>bridge.call('qa_logic',request,signal,requestTimeout),
|
|
91
100
|
browser:(request,signal)=>bridge.call('qa_browser',request,signal,requestTimeout)}),requestTimeoutMs:requestTimeout.timeoutMs});
|
|
@@ -95,10 +104,12 @@ export function createHostWorkflowCapabilities({definition,configuration,bridge,
|
|
|
95
104
|
|
|
96
105
|
export function createParallelMemberQaDecisionProvider(){
|
|
97
106
|
return Object.freeze({timeoutMs:60000,async decide(raw,signal){
|
|
98
|
-
const binding=json(raw);shape(binding,['specsDir','codeProject','feature','identity','packageDigest'
|
|
107
|
+
const binding=json(raw);shape(binding,['specsDir','codeProject','feature','identity','packageDigest',
|
|
108
|
+
...(Object.hasOwn(binding,'changedFiles')?['changedFiles']:[])]);
|
|
99
109
|
validIdentity(binding.identity);hex(binding.packageDigest);need(!signal.aborted,'cancelled');
|
|
100
110
|
return {decisionId:`qa-${digest({identity:binding.identity,packageDigest:binding.packageDigest}).slice(0,48)}`,
|
|
101
111
|
identity:binding.identity,packageDigest:binding.packageDigest,status:'skipped',
|
|
102
|
-
reason:'parallel_member_deferred',score:
|
|
112
|
+
reason:'parallel_member_deferred',score:null,
|
|
113
|
+
...(binding.changedFiles?{changedFilesSource:binding.changedFiles.source}:{}),at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')};
|
|
103
114
|
}});
|
|
104
115
|
}
|