@aibyzero/cm-workflow 0.16.3 → 0.16.5
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 +8 -0
- package/CHANGELOG.md +59 -0
- package/README.md +55 -3
- package/VERSION +1 -1
- package/docs/installation.md +21 -1
- package/docs/js-workflow-control.md +245 -33
- package/docs/next-steps.md +14 -24
- package/docs/runtime-failover.md +1 -1
- package/package.json +1 -1
- package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
- package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
- package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
- package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
- package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
- package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
- package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
- package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
- package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
- package/runtime/js/cm-ai/drive-core.mjs +39 -7
- package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
- package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
- package/runtime/js/cm-ai/effect-contract.mjs +44 -2
- package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
- package/runtime/js/cm-ai/execution-store.mjs +6 -4
- package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
- package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
- package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
- package/runtime/js/cm-ai/host-handoff.mjs +13 -6
- package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
- package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
- package/runtime/js/cm-ai/host-session.mjs +20 -5
- package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
- package/runtime/js/cm-ai/host.mjs +1 -1
- package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
- package/runtime/js/cm-ai/log-rows.mjs +21 -0
- package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
- package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
- package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
- package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
- package/runtime/js/cm-ai/review-package.mjs +427 -31
- package/runtime/js/cm-ai/review-runner.mjs +47 -1
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
- package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
- package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
- package/runtime/js/cm-ai/specification-material.mjs +154 -12
- package/runtime/js/cm-ai/task-commit.mjs +2 -2
- package/runtime/js/cm-ai/task-runner.mjs +502 -65
- package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
- package/runtime/js/cm-fix/execution.mjs +109 -25
- package/runtime/js/cm-fix/host-review.mjs +7 -3
- package/runtime/js/cm-fix/host.mjs +3 -1
- package/runtime/js/cm-fix/progress.mjs +1 -0
- package/runtime/js/cm-fix/protected-edits.mjs +15 -4
- package/runtime/js/cm-fix/qa-source.mjs +6 -4
- package/runtime/js/cm-prd/analysis.mjs +2 -1
- package/runtime/js/cm-prd/change.mjs +28 -10
- package/runtime/js/cm-prd/draft.mjs +5 -2
- package/runtime/js/cm-prd/review-preparation.mjs +10 -3
- package/runtime/js/cm-prd/review-publication.mjs +4 -2
- package/runtime/js/cm-prd/self-check.mjs +6 -3
- package/runtime/js/cm-prd/summary.mjs +6 -2
- package/runtime/js/cm-prd/validation-reason.mjs +20 -0
- package/runtime/js/spec-task-line.mjs +117 -0
- package/runtime/js/specs-status.mjs +14 -3
- package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
- package/scripts/cm-ai-admission.mjs +19 -10
- package/scripts/cm-ai-admission.test.mjs +65 -1
- package/scripts/cm-ai-batch-drive.mjs +93 -21
- package/scripts/cm-ai-batch-drive.test.mjs +171 -3
- package/scripts/cm-ai-batch-host.mjs +37 -13
- package/scripts/cm-ai-batch-host.test.mjs +26 -0
- package/scripts/cm-ai-batch-run.mjs +33 -10
- package/scripts/cm-ai-batch-run.test.mjs +56 -5
- package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
- package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
- package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
- package/scripts/cm-ai-bootstrap.test.mjs +99 -7
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
- package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
- package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
- package/scripts/cm-ai-drive.mjs +480 -47
- package/scripts/cm-ai-drive.test.mjs +247 -10
- package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
- package/scripts/cm-ai-host.mjs +89 -25
- package/scripts/cm-ai-host.test.mjs +274 -12
- package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
- package/scripts/cm-ai-multi-root.test.mjs +9 -3
- package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
- package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
- package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
- package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
- package/scripts/cm-ai-review-failure.test.mjs +917 -0
- package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
- package/scripts/cm-ai-review-timeout.test.mjs +199 -4
- package/scripts/cm-ai-run.mjs +160 -60
- package/scripts/cm-ai-run.test.mjs +4 -3
- package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
- package/scripts/cm-ai-selection-guard.test.mjs +100 -0
- package/scripts/cm-ai-session-chain.test.mjs +7 -3
- package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
- package/scripts/cm-ai-supersede.test.mjs +571 -17
- package/scripts/cm-ai-verification-gate.test.mjs +2 -1
- package/scripts/cm-capability-gate.test.mjs +21 -2
- package/scripts/cm-check-drive.mjs +4 -3
- package/scripts/cm-check-drive.test.mjs +17 -1
- package/scripts/cm-check-entry.mjs +13 -2
- package/scripts/cm-check-host.mjs +2 -2
- package/scripts/cm-check-host.test.mjs +57 -1
- package/scripts/cm-check-runtime.sh +16 -7
- package/scripts/cm-claude-developer-worker.test.mjs +43 -2
- package/scripts/cm-claude-probe.test.mjs +9 -1
- package/scripts/cm-claude-review-stream.test.mjs +68 -0
- package/scripts/cm-claude-worker.test.mjs +11 -4
- package/scripts/cm-codex-developer-worker.test.mjs +4 -2
- package/scripts/cm-failover.mjs +8 -8
- package/scripts/cm-fix-abandon.test.mjs +123 -5
- package/scripts/cm-fix-cause-package.test.mjs +2 -0
- package/scripts/cm-fix-drive.mjs +45 -13
- package/scripts/cm-fix-drive.test.mjs +36 -1
- package/scripts/cm-fix-host.mjs +9 -6
- package/scripts/cm-fix-review-budget.test.mjs +141 -0
- package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
- package/scripts/cm-host-check.test.mjs +6 -3
- package/scripts/cm-host-qa-executor.test.mjs +192 -17
- package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
- package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
- package/scripts/cm-log-event.mjs +17 -0
- package/scripts/cm-log-event.test.mjs +31 -0
- package/scripts/cm-prd-completion.test.mjs +105 -2
- package/scripts/cm-prd-draft.test.mjs +14 -0
- package/scripts/cm-prd-drive.mjs +13 -7
- package/scripts/cm-prd-drive.test.mjs +10 -0
- package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
- package/scripts/cm-prd-review-gate.mjs +126 -81
- package/scripts/cm-prd-review-gate.test.mjs +105 -1
- package/scripts/cm-prd-review-preparation.test.mjs +15 -0
- package/scripts/cm-prd-review-publication.test.mjs +6 -0
- package/scripts/cm-prd-self-check.test.mjs +6 -0
- package/scripts/cm-prd-summary.test.mjs +40 -0
- package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
- package/scripts/cm-review-inventory.test.mjs +253 -1
- package/scripts/cm-spec-manifest.mjs +28 -10
- package/scripts/cm-spec-manifest.test.mjs +8 -4
- package/scripts/cm-spec-task-line.test.mjs +138 -0
- package/scripts/cm-specs-status.test.mjs +31 -1
- package/scripts/cm-task-gate.mjs +18 -10
- package/scripts/cm-task-gate.py +1 -1
- package/scripts/cm-test-branch-impact.test.mjs +6 -3
- package/scripts/fixtures/claude-review-process.mjs +1 -0
- package/scripts/fixtures/process-cleanup.mjs +99 -0
- package/scripts/test-cm-log-event.py +2 -0
- package/scripts/test-cm-prd-review-gate.py +2 -1
- package/scripts/test-npm-install.py +1 -1
- package/scripts/test-scan-public-safety.py +1 -1
- package/scripts/test-shell-compat.sh +67 -0
- package/scripts/test-spec-manifest.py +16 -8
- package/scripts/test-task-gate.py +2 -2
- package/scripts/test-workflow-config.py +1 -0
- package/scripts/validate-public-repo.py +1 -0
- package/skills/cm-ai/references/N1-init.md +1 -1
- package/skills/cm-ai/references/js-host.md +264 -40
- package/skills/cm-check/SKILL.md +6 -1
- package/skills/cm-check/references/js-host.md +3 -3
- package/skills/cm-fix/references/js-host.md +22 -1
- package/skills/cm-prd/references/js-change-recovery.md +30 -0
- package/skills/cm-prd/references/js-host.md +6 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {readQaConfigRevision} from './qa-config-revision.mjs';
|
|
1
|
+
import {beforeFirstQaRound,readQaConfigRevision} from './qa-config-revision.mjs';
|
|
2
2
|
import {readQaAttachment} from './qa-attachment.mjs';
|
|
3
3
|
// Trusted synthetic fixture host; explicit V2 supports isolated task-file writes.
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
@@ -6,22 +6,28 @@ import { types } from 'node:util';
|
|
|
6
6
|
import fs from 'node:fs';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import {createRequire} from 'node:module';
|
|
9
|
-
import {verifySpecificationMaterial
|
|
10
|
-
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
9
|
+
import {verifySpecificationMaterial,boundSpecificationMaterial,inspectSpecificationDrift,describeSpecificationDrift,
|
|
10
|
+
readSpecificationRebind} from './specification-material.mjs';
|
|
11
|
+
import { captureReviewBaseline, captureReviewInventory, compareReviewBaseline, createReviewPackage, verifyReviewPackage, verifyCompletionReviewPackage, validChecks, readReviewSourceFiles } from './review-package.mjs';
|
|
12
|
+
import { digest,need,shape,id,text,json,freeze,arrayItems,validIdentity,validTaskLearningInput,validCallTimeout,requestFor,terminalFor,failureCode,
|
|
13
|
+
JOURNAL_PAYLOAD_LIMIT,developCheckpointReserve,taskReviewScope,boundedReason } from './effect-contract.mjs';
|
|
14
|
+
import { reviewResult,reviewReceipt,boundReviewText,reviewPaths } from './review-runner.mjs';
|
|
13
15
|
import { checkCompletion } from './gate-bridge.mjs';
|
|
14
16
|
import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
|
|
15
|
-
MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,
|
|
17
|
+
MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage,
|
|
18
|
+
reviewRetrySpent,abandonableReviewResult,developBudget,developBudgetExhausted,
|
|
19
|
+
completionBlockCount,completionRetriesExhausted,supersededReviewPayload } from './durable-runner-state.mjs';
|
|
16
20
|
import {commitRunnerFixture} from './task-commit.mjs';
|
|
17
|
-
import {inspectProviderReview,hasProviderReviewResult} from './provider-review-observation.mjs';
|
|
21
|
+
import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure} from './provider-review-observation.mjs';
|
|
18
22
|
import {attachCmAiTaskLearningApplicationEvidence,attachCmAiTaskLearningEvidence,
|
|
19
23
|
readCmAiTaskLearningApplication} from './cm-ai-context-refresh.mjs';
|
|
20
24
|
import {readCmAiProjectLearningWriteback,writeCmAiProjectLearning} from './cm-ai-learning-writer.mjs';
|
|
21
25
|
import {verifyCmAiTaskLearningHandoff,writeCmAiTaskLearningHandoff} from './cm-ai-learning-handoff-writer.mjs';
|
|
22
26
|
import {createHostHandoff} from './host-handoff.mjs';
|
|
23
|
-
import {inspectFixCodeAssociation} from './fix-code-association.mjs';
|
|
27
|
+
import {inspectFixCodeAssociation,explainCompletedDelivery} from './fix-code-association.mjs';
|
|
28
|
+
import {approvedReviewAt,completedReviewedDeliveries,fixReviewedAt,resolveDeliverySteps} from './reviewed-deliveries.mjs';
|
|
24
29
|
import {validateAcceptedFix} from './accepted-fix.mjs';
|
|
30
|
+
import {appendFits} from './execution-store-limits.mjs';
|
|
25
31
|
import {inspectCmAiQaFailure} from './cm-ai-qa-log.mjs';
|
|
26
32
|
import {readHostQaFixHistory} from './host-qa-fix.mjs';
|
|
27
33
|
import {publishHostReview} from './host-review-file.mjs';
|
|
@@ -82,6 +88,38 @@ function observePromise(value,onFulfilled,onRejected) {
|
|
|
82
88
|
}
|
|
83
89
|
}
|
|
84
90
|
const ignorePromiseResult=()=>{};
|
|
91
|
+
// Reviewer budgets go up to 3,600,000 ms; the host adds its cleanup margin.
|
|
92
|
+
export const MAX_REVIEW_BOUND_MS=3600000+60000;
|
|
93
|
+
// What the user does next for each retryable reviewer failure class. The class
|
|
94
|
+
// itself is also journaled in reviewInvocation.result.inspection.failure.
|
|
95
|
+
const REVIEW_FAILURE_HINTS=Object.freeze({
|
|
96
|
+
reviewer_auth_failed:'审查 CLI 未登录或凭证失效;先在本机重新登录审查 CLI,再恢复原 run 重派本轮审查',
|
|
97
|
+
reviewer_billing_error:'审查账号额度或计费不可用;恢复额度后再恢复原 run 重派本轮审查',
|
|
98
|
+
reviewer_rate_limited:'审查请求被限流或额度用尽;等额度恢复后再恢复原 run 重派本轮审查',
|
|
99
|
+
reviewer_server_error:'审查服务端错误或过载;稍后恢复原 run 重派本轮审查',
|
|
100
|
+
reviewer_model_not_found:'审查模型不存在或当前账号不可用;模型已绑定原 run 配置,确认账号可用该模型后恢复,换模型需新建运行',
|
|
101
|
+
reviewer_api_error:'审查 API 返回错误且没有结论;核对审查 CLI 账号与网络后恢复原 run 重派本轮审查',
|
|
102
|
+
reviewer_provider_failed:'审查进程报告失败且没有结论;核对审查 CLI 后恢复原 run 重派本轮审查',
|
|
103
|
+
reviewer_exited:'审查进程没有给出结论就退出;核对审查 CLI 能否正常运行后恢复原 run 重派本轮审查',
|
|
104
|
+
reviewer_stream_unrecognized:'审查 CLI 输出了无法识别的事件(常见于 CLI 升级);核对 CLI 版本后恢复原 run 重派本轮审查',
|
|
105
|
+
contradictory_verdict:'审查结论与 finding 等级矛盾:approved 不能带 P0–P2,changes_requested 至少要有一条 P0–P2;本轮结论作废并重派',
|
|
106
|
+
invalid_finding_path:'审查 finding 的 path 不在 examinedPaths 或 handoff 路径内;本轮结论作废并重派',
|
|
107
|
+
missing_material:'审查没有原样复制 examinedPaths;本轮结论作废并重派',
|
|
108
|
+
review_package_mismatch:'审查没有原样复制 packageDigest;本轮结论作废并重派',
|
|
109
|
+
invalid_finding_severity:'审查 finding 的 severity 不是 P0–P3;本轮结论作废并重派',
|
|
110
|
+
invalid_finding_id:'审查 finding 的 id 不合格式;本轮结论作废并重派',
|
|
111
|
+
invalid_finding_shape:'审查 finding 字段不全或重复;本轮结论作废并重派'});
|
|
112
|
+
const reviewFailureReason=failure=>`${failure}: ${REVIEW_FAILURE_HINTS[failure]??'审查失败且没有可用结论'}`;
|
|
113
|
+
// A verdict the review round ends on names why, instead of a bare code.
|
|
114
|
+
const verdictReason=(prefix,summary)=>`${prefix}:${String(summary).replace(/[\x00-\x1f\x7f]/g,' ').slice(0,300)}`;
|
|
115
|
+
const HALTED_SPEC_DRIFT='规格在本运行执行中途变化,运行已停在 blocked/spec_drift,不能继续或换绑。'
|
|
116
|
+
+'出口:用 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做;本运行改动的代码需还原,或加 --accept-superseded-code-drift 作为已有代码记录。';
|
|
117
|
+
const safeReason=error=>{
|
|
118
|
+
if(error===null||typeof error!=='object'||types.isProxy(error))return null;
|
|
119
|
+
const descriptor=Object.getOwnPropertyDescriptor(error,'message');
|
|
120
|
+
return descriptor&&Object.hasOwn(descriptor,'value')&&typeof descriptor.value==='string'
|
|
121
|
+
&&descriptor.value.length<=8192&&!/[\r\n\0]/.test(descriptor.value)?descriptor.value:null;
|
|
122
|
+
};
|
|
85
123
|
|
|
86
124
|
export function createTaskRunner(options) {
|
|
87
125
|
const taskMode=options && Object.hasOwn(options,'taskCompletion');
|
|
@@ -95,8 +133,10 @@ export function createTaskRunner(options) {
|
|
|
95
133
|
if(options && Object.hasOwn(options,'bootstrap'))optionKeys.push('bootstrap');
|
|
96
134
|
if(options && Object.hasOwn(options,'codeProjectPaths'))optionKeys.push('codeProjectPaths');
|
|
97
135
|
if(options && Object.hasOwn(options,'verificationGate'))optionKeys.push('verificationGate');
|
|
136
|
+
if(options && Object.hasOwn(options,'providerDevelopment'))optionKeys.push('providerDevelopment');
|
|
98
137
|
if(invocationMode)optionKeys.push('reviewInvocation');
|
|
99
138
|
shape(options,optionKeys);
|
|
139
|
+
need(options.providerDevelopment===undefined||typeof options.providerDevelopment==='boolean','invalid_input');
|
|
100
140
|
const {check,commit}=options;need(typeof check==='function' && (taskMode||typeof commit==='function'));
|
|
101
141
|
// Opt-in gate between the task's own checks and the independent review. It may
|
|
102
142
|
// only block: passing it grants nothing and never substitutes for that review.
|
|
@@ -126,12 +166,18 @@ export function createTaskRunner(options) {
|
|
|
126
166
|
if(invocationMode)id(r.adapterId);
|
|
127
167
|
return {...v,...(invocationMode?{adapterId:r.adapterId}:{}),run};
|
|
128
168
|
});
|
|
129
|
-
let invocationConfig=null,authorize=null,liveHostContextId=null;
|
|
169
|
+
let invocationConfig=null,authorize=null,liveHostContextId=null,reviewTimeoutMs=null;
|
|
130
170
|
if(invocationMode){
|
|
131
171
|
need(reviewers.length===1&&['codex','claude'].includes(reviewers[0].provider)&&reviewers[0].allowed&&reviewers[0].available,'runner_invocation');
|
|
132
172
|
shape(options.reviewInvocation,['developerThreadId','excludedThreadIds','authorize',
|
|
133
|
-
...(Object.hasOwn(options.reviewInvocation,
|
|
173
|
+
...['hostContextId','timeoutMs'].filter(key=>Object.hasOwn(options.reviewInvocation,key))]);
|
|
134
174
|
liveHostContextId=options.reviewInvocation.hostContextId??null;
|
|
175
|
+
// Transient like hostContextId, never journaled: the host sizes the review
|
|
176
|
+
// race above its reviewer's own budget, which a resumed run may raise.
|
|
177
|
+
if(Object.hasOwn(options.reviewInvocation,'timeoutMs')){
|
|
178
|
+
reviewTimeoutMs=options.reviewInvocation.timeoutMs;
|
|
179
|
+
need(Number.isSafeInteger(reviewTimeoutMs)&&reviewTimeoutMs>=1&&reviewTimeoutMs<=MAX_REVIEW_BOUND_MS,'runner_invocation');
|
|
180
|
+
}
|
|
135
181
|
if(liveHostContextId!==null){id(liveHostContextId);
|
|
136
182
|
need(![developer.contextId,...reviewers.flatMap(r=>r.contexts)].includes(liveHostContextId),'not_independent');}
|
|
137
183
|
authorize=options.reviewInvocation.authorize;need(typeof authorize==='function','runner_invocation');
|
|
@@ -201,10 +247,20 @@ export function createTaskRunner(options) {
|
|
|
201
247
|
const controller=new AbortController(),calls=[],cache=new Map(),session=restored?.session??randomUUID(),registered=new Map(),receipts=[];
|
|
202
248
|
let state=reviewers.some(r=>r.allowed&&r.available)?'ready':'pending_review',code=null,attempt=1;
|
|
203
249
|
let busy=false,pending=null,sequence=0,base=original,reviewPackage=null,currentChecks=null,workflowRunning=false;
|
|
250
|
+
let reason=null,checkNewPaths=null;
|
|
204
251
|
let receipt=null,priorReview=null,cancelAfterCommit=false,workflowError=null,cancellationRequested=false,reviewInvocation=null;
|
|
205
252
|
let learningResult=null;
|
|
253
|
+
// Journaled supersession context: shown, never counted as a review verdict.
|
|
254
|
+
let carriedReview=restored?.supersession?.carriedReview??null;
|
|
206
255
|
const acceptedFixes=structuredClone(restored?.acceptedFixes??[]);
|
|
207
256
|
let qaAttachment=restored?.qaAttachment??null;
|
|
257
|
+
// A fresh ready-state capture carries the current material; represent an
|
|
258
|
+
// accepted (identical or explicitly rebound) one by the bound material.
|
|
259
|
+
const withBoundSpecification=fresh=>{
|
|
260
|
+
if(!Object.hasOwn(fresh,'specification'))return fresh;
|
|
261
|
+
const {baselineDigest,...data}={...fresh,specification:boundSpecificationMaterial(original,fresh.specification)};
|
|
262
|
+
return {...data,baselineDigest:digest(data)};
|
|
263
|
+
};
|
|
208
264
|
const handoffBinding=(pkg=reviewPackage)=>pkg&&Object.hasOwn(pkg,'handoff')
|
|
209
265
|
?{handoffPath:completion.handoffs[pkg.identity.attempt-1]}:{};
|
|
210
266
|
function publishRegisteredReview(inspectOnly=false){
|
|
@@ -219,15 +275,72 @@ export function createTaskRunner(options) {
|
|
|
219
275
|
// the blocked result back out of the cache. Counting them here keeps that
|
|
220
276
|
// derivation in one place, next to the cache it is derived from.
|
|
221
277
|
const verificationBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='develop'
|
|
222
|
-
&&entry.result?.state==='blocked'
|
|
223
|
-
|
|
278
|
+
&&entry.result?.state==='blocked'
|
|
279
|
+
&&['verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed'].includes(entry.result?.code)).length;
|
|
280
|
+
const completionBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='complete'
|
|
281
|
+
&&entry.result?.state==='blocked'&&['completion_checks_changed','completion_package_changed'].includes(entry.result?.code)).length;
|
|
282
|
+
const privateStatus=()=>json({state,code,...(reason?{reason}:{}),
|
|
283
|
+
...(state==='unknown'&&restored?.pendingAbandonable
|
|
284
|
+
?{pendingEffectKind:restored.pending.kind}:{}),
|
|
285
|
+
...(state==='unknown'&&restored?.pending?.kind==='review'
|
|
286
|
+
&&restored.state.reviewInvocation?.registration&&restored.state.reviewInvocation.result===null
|
|
287
|
+
?{pendingReviewInvocation:true}:{}),
|
|
288
|
+
identity:{...config.identity,attempt},packageDigest:reviewPackage?.packageDigest??null,
|
|
224
289
|
receipt,receipts,calls,cancelAfterCommit,workflowError,...(store?{cancellationRequested}:{}),...(taskMode?{taskCommit}:{}),
|
|
225
290
|
...(invocationMode?{reviewInvocation}:{}),...(taskLearning!==null?{learningWriteback:learningResult?.writeback??null}:{})},16*1024*1024);
|
|
291
|
+
// Other task runs' committed, reviewed deliveries in this specs root, only
|
|
292
|
+
// those reviewed after this run's own approving review, and the live proof
|
|
293
|
+
// that recorded interleaving steps are exactly such deliveries.
|
|
294
|
+
const laterDeliveries=()=>completedReviewedDeliveries({specsRoot:completion.owner.specsRoot,root:config.root,identity:config.identity});
|
|
295
|
+
const reviewedAt=()=>approvedReviewAt({reviewInvocation,reviewPackage});
|
|
296
|
+
const resolveSteps=(steps,allowAbsent=false)=>resolveDeliverySteps({specsRoot:completion.owner.specsRoot,root:config.root,
|
|
297
|
+
identity:config.identity,after:reviewedAt(),steps,allowAbsent});
|
|
298
|
+
// This run's own QA fixes take their place in the same order at the final
|
|
299
|
+
// review time their completion evidence cites (evidence: a fix not yet accepted).
|
|
300
|
+
const fixTime=(evidence=null)=>fix=>{
|
|
301
|
+
const cited=[...acceptedFixes.map(item=>item.evidence),...(evidence?[evidence]:[])]
|
|
302
|
+
.find(item=>item.reviewPackage.packageDigest===fix.packageDigest);
|
|
303
|
+
return cited?fixReviewedAt(completion.owner.specsRoot,cited):null;
|
|
304
|
+
};
|
|
305
|
+
const laterOptions=(evidence=null)=>({deliveries:laterDeliveries,after:reviewedAt(),fixTime:fixTime(evidence)});
|
|
226
306
|
let publication;
|
|
307
|
+
// Replay decides; this only reports an exit abandonReview would accept.
|
|
308
|
+
function reviewResultAbandonable(){
|
|
309
|
+
return invocationMode&&store&&!busy&&!poisoned&&state==='unknown'&&!restored?.pending
|
|
310
|
+
&&abandonableReviewResult({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1]);
|
|
311
|
+
}
|
|
227
312
|
const status=()=>{
|
|
228
|
-
|
|
313
|
+
let current=store?publication:privateStatus();
|
|
314
|
+
// Status only; never part of a cached result or checkpoint.
|
|
315
|
+
if(current.state==='unknown'&&reviewResultAbandonable())current=freeze({...current,abandonableReviewResult:true});
|
|
229
316
|
if(!busy&&!poisoned)try{publishRegisteredReview(true);}
|
|
230
317
|
catch{return freeze({...current,code:'review_publication_required'});}
|
|
318
|
+
// Every next effect re-verifies the bound specification. When it no longer
|
|
319
|
+
// verifies, report that and its real exits instead of the refused action.
|
|
320
|
+
if(!busy&&!poisoned&&specificationLive(current.state,current.code)){
|
|
321
|
+
const drift=inspectSpecificationDrift(original);
|
|
322
|
+
if(drift)return freeze({...current,code:'spec_drift',reason:describeSpecificationDrift(drift),
|
|
323
|
+
specificationRebind:drift.rebindable?'available':'unavailable'});
|
|
324
|
+
}
|
|
325
|
+
if(current.state==='blocked'&¤t.code==='spec_drift'&&!current.reason)
|
|
326
|
+
return freeze({...current,reason:HALTED_SPEC_DRIFT});
|
|
327
|
+
if(!busy&&reviewPackage&&(['awaiting_review','approved','changes_requested'].includes(current.state)
|
|
328
|
+
||current.state==='blocked'&&['review_package_changed','completion_package_changed'].includes(current.code))){
|
|
329
|
+
try{
|
|
330
|
+
verifyReviewPackage({root:config.root,baseline:attemptBaseline(original,reviewPackage.identity.attempt),
|
|
331
|
+
checks:currentChecks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
|
|
332
|
+
if(current.state==='blocked'&¤t.code==='review_package_changed'){
|
|
333
|
+
const {reason:oldReason,...rest}=current;
|
|
334
|
+
if(priorReview?.verdict==='approved')return freeze({...rest,state:'approved',code:null});
|
|
335
|
+
if(priorReview?.verdict==='changes_requested'&&attempt===2&&reviewPackage.identity.attempt===1)
|
|
336
|
+
return freeze({...rest,state:'changes_requested',code:null});
|
|
337
|
+
return freeze({...rest,state:'blocked',code:priorReview?.verdict==='changes_requested'?'review_limit':'review_blocked'});
|
|
338
|
+
}
|
|
339
|
+
if(current.code==='completion_package_changed')return freeze({...current,retryReady:true});
|
|
340
|
+
}catch(error){return freeze({...current,state:'blocked',
|
|
341
|
+
code:current.code==='completion_package_changed'?'completion_package_changed':'review_package_changed',
|
|
342
|
+
...(current.code==='completion_package_changed'?{retryReady:false}:{}),reason:error.message});}
|
|
343
|
+
}
|
|
231
344
|
if(current.state!=='fixture_completed')return current;
|
|
232
345
|
try {
|
|
233
346
|
if(acceptedFixes.length){
|
|
@@ -237,18 +350,35 @@ export function createTaskRunner(options) {
|
|
|
237
350
|
need(history.handoffDigest===handoffDigest,'fix_qa_source_changed');
|
|
238
351
|
}
|
|
239
352
|
inspectFixCodeAssociation({root:config.root,specsRoot:completion.owner.specsRoot,baseline:base,
|
|
240
|
-
parentPackage:reviewPackage,fixPackages:acceptedFixes.map(item=>item.evidence.reviewPackage)
|
|
353
|
+
parentPackage:reviewPackage,fixPackages:acceptedFixes.map(item=>item.evidence.reviewPackage),
|
|
354
|
+
steps:acceptedFixes.at(-1).association.laterDeliveries??[],...laterOptions()});
|
|
241
355
|
const last=acceptedFixes.at(-1);
|
|
242
356
|
return freeze({...current,acceptedQaFix:{qaRound:last.qaRound,testRunId:last.evidence.qaSource.testRunId,
|
|
243
357
|
evidenceDigest:digest(last)}});
|
|
244
358
|
}
|
|
245
|
-
verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
|
|
246
|
-
reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
|
|
359
|
+
try{verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
|
|
360
|
+
reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});}
|
|
361
|
+
catch(error){
|
|
362
|
+
// The exact reviewed tree no longer holds. A committed task may still be
|
|
363
|
+
// intact under later, separately reviewed deliveries of other runs.
|
|
364
|
+
if(!completion)throw error;
|
|
365
|
+
if(reviewPackage.handoff){
|
|
366
|
+
const handoff=handoffBinding().handoffPath;
|
|
367
|
+
need(digest(readReviewSourceFiles(path.dirname(handoff),[path.basename(handoff)])[0])===digest(reviewPackage.handoff),'package_mismatch');
|
|
368
|
+
}
|
|
369
|
+
explainCompletedDelivery({root:config.root,baseline:base,parentPackage:reviewPackage,deliveries:laterDeliveries(),after:reviewedAt()});
|
|
370
|
+
}
|
|
247
371
|
return current;
|
|
248
|
-
} catch
|
|
372
|
+
} catch(error){
|
|
373
|
+
return freeze({...current,code:'correction_review_required',...(error?.code==='fix_current_code_unexplained'
|
|
374
|
+
?{reason:`未经审查的改动:${error.paths.slice(0,20).join(', ')}${error.paths.length>20?` 等 ${error.paths.length} 个路径`:''}`}
|
|
375
|
+
:error?.code==='fix_association_unverified'?{reason:'已登记 QA 修复所接续的后续交付无法按其运行存档核实(存档缺失、未完成或内容不符)'}:{})});
|
|
376
|
+
}
|
|
249
377
|
};
|
|
250
|
-
const halt=(next,why)=>{state=next;code=why;};
|
|
251
|
-
|
|
378
|
+
const halt=(next,why,detail=null)=>{state=next;code=why;reason=detail;};
|
|
379
|
+
const specificationLive=(currentState,currentCode)=>Object.hasOwn(original,'specification')
|
|
380
|
+
&&['develop','review','complete'].some(kind=>stageAllowed(kind,currentState,currentCode,priorReview?.verdict));
|
|
381
|
+
function frame(){return {state,code,reason,attempt,session,sequence,reviewPackage,currentChecks,receipt,receipts,calls,
|
|
252
382
|
cache:[...cache.values()],priorReview,cancelAfterCommit,workflowError,cancellationRequested,...(taskMode?{taskCommit}:{}),
|
|
253
383
|
...(invocationMode?{reviewInvocation}:{}),...(taskLearning!==null?{learningResult}:{})};}
|
|
254
384
|
const same=(a,b,why)=>need(digest(a)===digest(b),why);
|
|
@@ -269,13 +399,22 @@ export function createTaskRunner(options) {
|
|
|
269
399
|
kind:{init:'result','effect-intent':'intent','effect-checkpoint':'result',control:'cancel',
|
|
270
400
|
'task-commit-intent':'commit-intent','task-commit-result':'commit-result',
|
|
271
401
|
'review-invocation-registered':'intent','review-invocation-started':'result','review-invocation-result':'result',
|
|
402
|
+
'review-invocation-abandoned':'result','effect-abandoned':'result',
|
|
272
403
|
'host-joined':'result','qa-fix-accepted':'result','qa-attached':'result','qa-config-revised':'result',
|
|
273
|
-
'evidence-superseded':'result'}[type],
|
|
404
|
+
'evidence-superseded':'result','develop-retry-limit':'result','completion-retry-limit':'result','specification-rebound':'result'}[type],
|
|
274
405
|
payload:version===3?runnerPayloadV3(type,fields):runnerPayload(type,fields,version)};
|
|
275
406
|
const body={version:1,seq:journal.length+1,...basic,previousDigest:journal.at(-1)?.digest??null};
|
|
276
407
|
const record={...body,digest:digest(body)};boundRunnerRecord(record,body.seq);
|
|
277
408
|
return {record,parsed:readRunnerHistory([...journal,record],metadata,version)};
|
|
278
409
|
}
|
|
410
|
+
// The exact record the store would append must fit its limits (payload, append
|
|
411
|
+
// input, record count, whole state). Refusing here leaves the store usable,
|
|
412
|
+
// where an over-limit append inside persist would poison it.
|
|
413
|
+
function assertJournalFits(type,fields,why){
|
|
414
|
+
if(!store||!taskMode)return;
|
|
415
|
+
const {record}=candidate(type,fields);
|
|
416
|
+
need(appendFits(currentStore(),{id:record.id,kind:record.kind,payload:record.payload,expectedRevision:storeRevision}),why);
|
|
417
|
+
}
|
|
279
418
|
function persist(type,fields) {
|
|
280
419
|
if(!store)return;
|
|
281
420
|
if(taskMode)return storeOperation(()=>{
|
|
@@ -329,15 +468,35 @@ export function createTaskRunner(options) {
|
|
|
329
468
|
same(result,{outcome:'fixture_committed',intentDigest:taskCommit.intentDigest,planDigest:taskCommit.planDigest},'commit_unknown');
|
|
330
469
|
}finally{revoke();}
|
|
331
470
|
}
|
|
471
|
+
// Exact byte count of the payload the store validates for this record, built by
|
|
472
|
+
// the same record builder; an oversized record is measured, never written.
|
|
473
|
+
const payloadBytes=(type,fields)=>Buffer.byteLength(JSON.stringify(version===3
|
|
474
|
+
?runnerPayloadV3(type,fields,Infinity):runnerPayload(type,fields,version,Infinity)));
|
|
475
|
+
const largestFiles=files=>files.slice().sort((a,b)=>b.size-a.size).slice(0,3)
|
|
476
|
+
.map(file=>`${file.path} ${file.size} bytes`);
|
|
332
477
|
if(restored) {
|
|
333
478
|
const s=structuredClone(restored.state);
|
|
334
479
|
({state,code,attempt,sequence,reviewPackage,currentChecks,receipt,priorReview,cancelAfterCommit,workflowError,cancellationRequested}=s);
|
|
480
|
+
reason=s.reason??null;
|
|
335
481
|
if(taskLearning!==null)learningResult=s.learningResult;
|
|
336
482
|
if(taskMode)taskCommit=s.taskCommit;
|
|
337
483
|
if(invocationMode)reviewInvocation=s.reviewInvocation;
|
|
338
484
|
calls.push(...s.calls);receipts.push(...s.receipts);s.cache.forEach(c=>cache.set(c.effect.id,c));
|
|
339
485
|
receipts.forEach(r=>registered.set(r.id,r));base=attemptBaseline(original,attempt);
|
|
340
|
-
|
|
486
|
+
// Replay re-proves each version 2 record (its steps and the composition they
|
|
487
|
+
// give) against the referenced stores when they all still exist; a missing
|
|
488
|
+
// store is left to the live checks, which refuse it.
|
|
489
|
+
for(const [index,item] of acceptedFixes.entries())if(item.association.version===2)
|
|
490
|
+
validateAcceptedFix({record:item,previous:acceptedFixes.slice(0,index),baseline:base,parentPackage:reviewPackage,
|
|
491
|
+
feature:taskLearning?.feature,resolveSteps:steps=>resolveSteps(steps,true)});
|
|
492
|
+
} else {
|
|
493
|
+
// A baseline too large for its record is refused before anything is appended.
|
|
494
|
+
const bytes=store?payloadBytes('init',{config:metadata,baseline:original,session}):0;
|
|
495
|
+
if(bytes>JOURNAL_PAYLOAD_LIMIT)throw Object.assign(new Error(boundedReason(`limit_exceeded: the task baseline journal record would be ${bytes} bytes, `
|
|
496
|
+
+`above the journal record limit ${JOURNAL_PAYLOAD_LIMIT}; largest baseline material: `,
|
|
497
|
+
largestFiles(original.files.filter(file=>Object.hasOwn(file,'contentBase64'))))),{code:'limit_exceeded'});
|
|
498
|
+
persist('init',{config:metadata,baseline:original,session});
|
|
499
|
+
}
|
|
341
500
|
publication=privateStatus();
|
|
342
501
|
function control(event) {
|
|
343
502
|
if(poisoned)return false;
|
|
@@ -402,8 +561,13 @@ export function createTaskRunner(options) {
|
|
|
402
561
|
}
|
|
403
562
|
function acceptReview(request,call,rawResult,fallbackReasons=[]) {
|
|
404
563
|
const result=reviewResult(rawResult,reviewPackage);
|
|
405
|
-
|
|
406
|
-
|
|
564
|
+
let drift=null;
|
|
565
|
+
try{verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
|
|
566
|
+
reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});}
|
|
567
|
+
catch(error){drift=error;}
|
|
568
|
+
// Changed approved specs invalidate the verdict itself. Do not register a
|
|
569
|
+
// receipt that the code-root cleanup path could later reuse.
|
|
570
|
+
if(drift?.code==='spec_drift'){halt('blocked','spec_drift');return;}
|
|
407
571
|
receipt=reviewReceipt({request,call,result,reviewPackage,developerProvider:developer.provider,fallbackReasons});
|
|
408
572
|
registered.set(receipt.id,receipt);receipts.push(receipt);priorReview=result;
|
|
409
573
|
if(result.verdict==='approved'){state='approved';code=null;}
|
|
@@ -411,7 +575,10 @@ export function createTaskRunner(options) {
|
|
|
411
575
|
state='changes_requested';code=null;attempt=2;
|
|
412
576
|
const {baselineDigest:old,...data}=original,newData={...data,identity:{...config.identity,attempt}};
|
|
413
577
|
base=freeze({...newData,baselineDigest:digest(newData)});
|
|
414
|
-
} else halt('blocked',result.verdict==='changes_requested'?'review_limit':'review_blocked'
|
|
578
|
+
} else halt('blocked',result.verdict==='changes_requested'?'review_limit':'review_blocked',
|
|
579
|
+
verdictReason(result.verdict==='changes_requested'?'review_limit: 第 2 轮审查仍要求修改,本运行两轮已用完'
|
|
580
|
+
:'review_blocked: 审查判定 blocked,无法靠修改批准范围内的代码解决',result.summary));
|
|
581
|
+
if(drift)halt('blocked','review_package_changed',drift.message);
|
|
415
582
|
}
|
|
416
583
|
const clock=Date.now.bind(Date);
|
|
417
584
|
const safeTime=()=>{const value=clock();need(Number.isSafeInteger(value),'clock_invalid');return value;};
|
|
@@ -527,7 +694,7 @@ export function createTaskRunner(options) {
|
|
|
527
694
|
})),
|
|
528
695
|
invalidPromise,
|
|
529
696
|
new Promise((_,reject)=>{timer=setTimeout(()=>{timedOut=true;localController.abort();
|
|
530
|
-
reject(Object.assign(new Error('call_timeout'),{code:'call_timeout'}));},config.timeoutMs);}),
|
|
697
|
+
reject(Object.assign(new Error('call_timeout'),{code:'call_timeout'}));},reviewTimeoutMs??config.timeoutMs);}),
|
|
531
698
|
new Promise((_,reject)=>{cancelReject=()=>reject(Object.assign(new Error('cancelled'),{code:'cancelled'}));
|
|
532
699
|
controller.signal.addEventListener('abort',cancelReject,{once:true});})
|
|
533
700
|
]);
|
|
@@ -548,7 +715,7 @@ export function createTaskRunner(options) {
|
|
|
548
715
|
fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'unknown',observation:recorded,inspection,reconciliationRequired:true};
|
|
549
716
|
}
|
|
550
717
|
persist('review-invocation-result',fields);const result=resultView(fields);
|
|
551
|
-
const retry=reviewTimeoutTransition(result,[...cache.values()],attempt);
|
|
718
|
+
const retry=reviewTimeoutTransition(result,[...cache.values()],attempt,calls.slice(0,-1),contextId);
|
|
552
719
|
Object.assign(call,{terminal:fields.outcome==='cancelled'?'cancelled':retry?'failed':'unknown',resultDigest:digest(result)});
|
|
553
720
|
reviewInvocation=json({registration,started,result});
|
|
554
721
|
if(fields.outcome==='cancelled')halt('cancelled','cancelled');
|
|
@@ -569,19 +736,44 @@ export function createTaskRunner(options) {
|
|
|
569
736
|
Object.assign(call,{terminal:'unknown',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
|
|
570
737
|
halt('unknown',inspection.code??'reconciliation_required');return;
|
|
571
738
|
}
|
|
739
|
+
// A reviewer that failed without a verdict, or whose complete answer breaks
|
|
740
|
+
// the verdict contract, ends in a new explicit retryable result.
|
|
741
|
+
const reviewerFailed=(recorded,failure)=>{
|
|
742
|
+
const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'failed',observation:recorded,
|
|
743
|
+
inspection:failure,reconciliationRequired:false};
|
|
744
|
+
persist('review-invocation-result',fields);const result=resultView(fields);
|
|
745
|
+
const retry=reviewTimeoutTransition(result,[...cache.values()],attempt,calls.slice(0,-1),contextId);
|
|
746
|
+
Object.assign(call,{terminal:'failed',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
|
|
747
|
+
halt(retry.state,retry.code,reviewFailureReason(failure.failure));
|
|
748
|
+
};
|
|
749
|
+
// Bound the reviewer text before it is observed, inspected or journaled.
|
|
750
|
+
if(providerResult.status==='succeeded'){
|
|
751
|
+
const bounded=boundReviewText(providerResult.value);
|
|
752
|
+
if(bounded===null){
|
|
753
|
+
const fields=invalidFields();persist('review-invocation-result',fields);const result=resultView(fields);
|
|
754
|
+
Object.assign(call,{terminal:'unknown',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
|
|
755
|
+
halt('unknown','observation_invalid');return;
|
|
756
|
+
}
|
|
757
|
+
providerResult=json({status:'succeeded',value:bounded});
|
|
758
|
+
}
|
|
572
759
|
let recorded,inspection;
|
|
573
760
|
try{recorded=observation(providerResult);inspection=inspectProviderReview(JSON.stringify(recorded),JSON.stringify(expectation));}
|
|
574
761
|
catch{
|
|
762
|
+
const failure=recorded===undefined?null:inspectProviderReviewFailure(JSON.stringify(recorded),JSON.stringify(expectation));
|
|
763
|
+
if(failure){reviewerFailed(recorded,failure);return;}
|
|
575
764
|
const fields=invalidFields();persist('review-invocation-result',fields);const result=resultView(fields);
|
|
576
765
|
Object.assign(call,{terminal:'unknown',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
|
|
577
766
|
halt('unknown','observation_invalid');return;
|
|
578
767
|
}
|
|
579
768
|
const observed=inspection.observationStatus==='completed';
|
|
769
|
+
const failure=!observed&&inspection.code==='transport_incomplete'
|
|
770
|
+
?inspectProviderReviewFailure(JSON.stringify(recorded),JSON.stringify(expectation)):null;
|
|
771
|
+
if(failure){reviewerFailed(recorded,failure);return;}
|
|
580
772
|
const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:observed?'observed':inspection.code==='transport_timeout'?'timed_out':'unknown',
|
|
581
773
|
observation:recorded,inspection,reconciliationRequired:!observed
|
|
582
774
|
&&(inspection.code!=='transport_timeout'||hasProviderReviewResult(recorded.events))};
|
|
583
775
|
persist('review-invocation-result',fields);const result=resultView(fields);
|
|
584
|
-
const retry=reviewTimeoutTransition(result,[...cache.values()],attempt);
|
|
776
|
+
const retry=reviewTimeoutTransition(result,[...cache.values()],attempt,calls.slice(0,-1),contextId);
|
|
585
777
|
Object.assign(call,{terminal:observed?'succeeded':retry?'failed':'unknown',resultDigest:digest(observed?inspection.review:result)});
|
|
586
778
|
reviewInvocation=json({registration,started,result});
|
|
587
779
|
if(observed)acceptReview(request,call,inspection.review);
|
|
@@ -590,7 +782,20 @@ export function createTaskRunner(options) {
|
|
|
590
782
|
}finally{sealed=true;clearTimeout(timer);controller.signal.removeEventListener('abort',abort);
|
|
591
783
|
if(cancelReject)controller.signal.removeEventListener('abort',cancelReject);}
|
|
592
784
|
}
|
|
593
|
-
async function collectChecks(){
|
|
785
|
+
async function collectChecks(){
|
|
786
|
+
const before=new Map(captureReviewInventory(config.root,base).map(file=>[file.path,file.sha256]));
|
|
787
|
+
const results=json(await bounded(check,json({identity:{...config.identity,attempt}})));
|
|
788
|
+
validChecks(results);
|
|
789
|
+
const after=captureReviewInventory(config.root,base);
|
|
790
|
+
checkNewPaths=new Set(after.filter(file=>!before.has(file.path)).map(file=>file.path));
|
|
791
|
+
return results;
|
|
792
|
+
}
|
|
793
|
+
const failedChecks=checks=>checks.filter(item=>item.outcome!=='passed'||item.kind!=='visual'&&item.exitCode!==0);
|
|
794
|
+
const checkFailureReason=(checks,code='checks_not_passed')=>{
|
|
795
|
+
const details=failedChecks(checks).map(item=>
|
|
796
|
+
`${item.id}: ${item.outcome}; ${item.evidence.replace(/[\x00-\x1f]/g,' ').slice(0,60)}`);
|
|
797
|
+
return `${code}: ${details.join(' | ')}`;
|
|
798
|
+
};
|
|
594
799
|
// Runs on the checks just collected, before any handoff or review package is
|
|
595
800
|
// built, so a deliverable that does not satisfy the task's own written
|
|
596
801
|
// verification never spends an independent review round.
|
|
@@ -612,21 +817,64 @@ export function createTaskRunner(options) {
|
|
|
612
817
|
shape(verdict,['satisfied']);need(typeof verdict.satisfied==='boolean','invalid_result');
|
|
613
818
|
return verdict.satisfied;
|
|
614
819
|
}
|
|
820
|
+
// Attempt 2 exists to answer the findings that rejected attempt 1. Code
|
|
821
|
+
// byte-identical to that rejected artifact cannot, so it never spends the
|
|
822
|
+
// last review round; the same attempt may deliver again under a new effect id.
|
|
823
|
+
function unchangedSinceRejection(){
|
|
824
|
+
if(attempt!==2||priorReview?.verdict!=='changes_requested')return null;
|
|
825
|
+
const rejected=receipts.findLast(item=>item.identity.attempt===1&&item.result.verdict==='changes_requested');
|
|
826
|
+
if(!rejected)return null;
|
|
827
|
+
const candidate=createReviewPackage({root:config.root,baseline:base,checks:currentChecks});
|
|
828
|
+
return candidate.artifactDigest===rejected.artifactDigest
|
|
829
|
+
?`develop_unchanged_after_review: 第 2 轮交付与第 1 轮被要求修改的代码逐字节相同(artifactDigest ${rejected.artifactDigest.slice(0,12)});按审查 findings 修改后重新交付`:null;
|
|
830
|
+
}
|
|
831
|
+
// A delivery that changes nothing in scope has no review package to build. It
|
|
832
|
+
// is the delivery that must be redone, exactly like failed checks, not an
|
|
833
|
+
// unknown effect: nothing was dispatched to a reviewer and no round was spent.
|
|
834
|
+
const EMPTY_DELIVERY='develop_empty_changes: the delivery changes nothing in scope relative to the task baseline; '
|
|
835
|
+
+'write the actual change and resume to redo this attempt';
|
|
836
|
+
// Scope may overlap requirements. A delivery that removed such a file cannot be
|
|
837
|
+
// packaged (every requirement must exist), which is again a delivery to redo.
|
|
838
|
+
// Only in-scope requirements qualify: touching any other file stays out_of_scope,
|
|
839
|
+
// which the package builder reports before it ever reads the requirements.
|
|
840
|
+
const missingScopeRequirements=()=>config.scope.filter(p=>config.requirements.includes(p)).filter(p=>{
|
|
841
|
+
try{const stat=fs.lstatSync(path.join(config.root,p));return !stat.isFile()||stat.isSymbolicLink();}
|
|
842
|
+
catch(error){if(error.code==='ENOENT'||error.code==='ENOTDIR')return true;throw error;}
|
|
843
|
+
});
|
|
844
|
+
const emptyDelivery=error=>{
|
|
845
|
+
if(error?.code==='empty_changes'){halt('blocked','develop_empty_changes',EMPTY_DELIVERY);return;}
|
|
846
|
+
const missing=error?.code==='read_failed'?missingScopeRequirements():[];
|
|
847
|
+
if(!missing.length)throw error;
|
|
848
|
+
halt('blocked','develop_requirement_missing',boundedReason('develop_requirement_missing: ',missing,
|
|
849
|
+
' are requirement files and must exist in the review package; restore them and resume to redo this attempt'));
|
|
850
|
+
};
|
|
615
851
|
async function perform(v) {
|
|
616
852
|
if(v.kind==='develop') {
|
|
617
|
-
need(stageAllowed('develop',state,code),'stage_mismatch');state='developing';code=null;receipt=null;
|
|
853
|
+
need(stageAllowed('develop',state,code,priorReview?.verdict),'stage_mismatch');state='developing';code=null;reason=null;checkNewPaths=null;receipt=null;
|
|
854
|
+
const previousLearning=learningResult;
|
|
618
855
|
const previousBootstrap=learningResult?.bootstrap??null;
|
|
619
856
|
const previousWriteback=learningResult?.writeback??null;
|
|
620
857
|
if(taskLearning!==null)learningResult=null;
|
|
858
|
+
let verificationReason=null;
|
|
621
859
|
const adapter=bootstrap===null?developer:{...developer,run:(request,control)=>
|
|
622
|
-
bootstrap.run(request,control,developer.run,{previous:previousBootstrap,previousWriteback,baseline:original
|
|
860
|
+
bootstrap.run(request,control,developer.run,{previous:previousBootstrap,previousWriteback,baseline:original,
|
|
861
|
+
verificationFailed:detail=>{verificationReason=detail;}})};
|
|
623
862
|
const result=await invoke(adapter,'developer',developer.contextId,{scope:config.scope,
|
|
624
863
|
requirements:original.files.filter(f=>config.requirements.includes(f.path)),priorReview,
|
|
864
|
+
...supersededReviewPayload(carriedReview,attempt),
|
|
625
865
|
...(Object.hasOwn(original,'specification')?{specification:verifySpecificationMaterial(original)}:{}),
|
|
626
866
|
...(Object.hasOwn(v,'learningInput')?{learningInput:v.learningInput}:{})});
|
|
627
867
|
if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
|
|
628
868
|
if(result.response.status!=='succeeded'){
|
|
629
869
|
const failure=result.response.result?.code;
|
|
870
|
+
// The live session's init_verify did not pass, before any rule write.
|
|
871
|
+
// Keep the Learning/bootstrap evidence this develop started from, so the
|
|
872
|
+
// retry of the same attempt binds to exactly the files still on disk.
|
|
873
|
+
if(failure==='bootstrap_verification_failed'){
|
|
874
|
+
need(metadata.bootstrap?.mode==='instructions'&&typeof verificationReason==='string','invalid_result');
|
|
875
|
+
learningResult=previousLearning;
|
|
876
|
+
halt('blocked','bootstrap_verification_failed',verificationReason);return;
|
|
877
|
+
}
|
|
630
878
|
halt(result.response.status==='unknown'?'unknown':'blocked',
|
|
631
879
|
failure==='invalid_result'&&result.response.result.retryable===true?'developer_result_invalid':
|
|
632
880
|
failure==='protected_edit_stale'?failure:result.response.status);return;
|
|
@@ -645,16 +893,25 @@ export function createTaskRunner(options) {
|
|
|
645
893
|
&&application.learningDigest===v.learningInput.learningDigest,'identity_mismatch');
|
|
646
894
|
const retrospective=json(result.response.result.retrospective,16*1024);
|
|
647
895
|
const writeback=readCmAiProjectLearningWriteback(writeCmAiProjectLearning({codeProject:config.root,
|
|
648
|
-
learningInput:v.learningInput,retrospective},instructionEvidence?.files.find(file=>file.path==='AGENTS.md').afterSha256??null
|
|
896
|
+
learningInput:v.learningInput,retrospective},instructionEvidence?.files.find(file=>file.path==='AGENTS.md').afterSha256??null,
|
|
897
|
+
metadata.bootstrap?.feature??null),
|
|
649
898
|
{learningInput:v.learningInput,retrospective});
|
|
650
899
|
learningResult=freeze({application,retrospective,writeback,...(instructionEvidence?{bootstrap:instructionEvidence}:{})});
|
|
651
900
|
if(writeback.outcome==='writeback_pending'){halt('blocked','learning_writeback_pending');return;}
|
|
652
901
|
if(taskLearning.hostHandoff===true){
|
|
653
902
|
currentChecks=await collectChecks();active();
|
|
903
|
+
if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return;}
|
|
654
904
|
if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return;}
|
|
655
905
|
active();
|
|
656
|
-
|
|
657
|
-
|
|
906
|
+
// unchangedSinceRejection builds a package too, so an empty delivery or a
|
|
907
|
+
// deleted in-scope requirement surfaces there first and takes the same
|
|
908
|
+
// retryable block (emptyDelivery).
|
|
909
|
+
let unchanged;
|
|
910
|
+
try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return;}
|
|
911
|
+
if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return;}
|
|
912
|
+
try{createHostHandoff({root:config.root,baseline:base,checks:currentChecks,
|
|
913
|
+
handoffPath:completion.handoffs[attempt-1]});}
|
|
914
|
+
catch(error){emptyDelivery(error);return;}
|
|
658
915
|
}
|
|
659
916
|
writeCmAiTaskLearningHandoff({handoffPath:completion.handoffs[attempt-1],feature:taskLearning.feature,
|
|
660
917
|
identity:{...config.identity,attempt},learningInput:v.learningInput,application,retrospective,writeback});
|
|
@@ -662,11 +919,18 @@ export function createTaskRunner(options) {
|
|
|
662
919
|
need(result.response.result.outcome==='implemented','invalid_result');
|
|
663
920
|
if(taskLearning?.hostHandoff!==true){
|
|
664
921
|
currentChecks=await collectChecks();active();
|
|
922
|
+
if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return;}
|
|
665
923
|
if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return;}
|
|
924
|
+
active();
|
|
925
|
+
let unchanged;
|
|
926
|
+
try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return;}
|
|
927
|
+
if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return;}
|
|
666
928
|
}
|
|
667
929
|
active();
|
|
668
|
-
|
|
669
|
-
|
|
930
|
+
let nextPackage;
|
|
931
|
+
try{nextPackage=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,
|
|
932
|
+
...(taskLearning?.hostHandoff===true?{handoffPath:completion.handoffs[attempt-1]}:{})});}
|
|
933
|
+
catch(error){emptyDelivery(error);return;}
|
|
670
934
|
if(taskLearning!==null)validateTaskLearningReviewPackage(nextPackage,learningResult.writeback,v.learningInput,
|
|
671
935
|
learningResult.bootstrap??null,metadata.bootstrap??null);
|
|
672
936
|
reviewPackage=nextPackage;
|
|
@@ -675,12 +939,14 @@ export function createTaskRunner(options) {
|
|
|
675
939
|
if(v.kind==='review') {
|
|
676
940
|
state='reviewing';verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
|
|
677
941
|
reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
|
|
678
|
-
if(invocationMode){await invokeObserved(reviewers[0],reviewers[0].contexts[attempt-1],{reviewPackage,priorReview
|
|
942
|
+
if(invocationMode){await invokeObserved(reviewers[0],reviewers[0].contexts[attempt-1],{reviewPackage,priorReview,
|
|
943
|
+
...supersededReviewPayload(carriedReview,attempt)},v.id);return;}
|
|
679
944
|
const fallbackReasons=[];
|
|
680
945
|
for(const candidate of reviewers) {
|
|
681
946
|
active();
|
|
682
947
|
if(!candidate.allowed || !candidate.available){fallbackReasons.push({id:candidate.id,reason:!candidate.allowed?'not_authorized':'unavailable'});continue;}
|
|
683
|
-
const {request,response,call}=await invoke(candidate,'reviewer',candidate.contexts[attempt-1],{reviewPackage,priorReview
|
|
948
|
+
const {request,response,call}=await invoke(candidate,'reviewer',candidate.contexts[attempt-1],{reviewPackage,priorReview,
|
|
949
|
+
...supersededReviewPayload(carriedReview,attempt)});
|
|
684
950
|
if(['unavailable','auth_required','permission_denied'].includes(response.status)) {
|
|
685
951
|
fallbackReasons.push({id:candidate.id,reason:response.status});continue;
|
|
686
952
|
}
|
|
@@ -693,8 +959,14 @@ export function createTaskRunner(options) {
|
|
|
693
959
|
if(v.kind==='complete') {
|
|
694
960
|
const fresh=await collectChecks();active();
|
|
695
961
|
try {
|
|
696
|
-
|
|
697
|
-
} catch(error){
|
|
962
|
+
verifyCompletionReviewPackage({root:config.root,baseline:base,checks:fresh,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
|
|
963
|
+
} catch(error){
|
|
964
|
+
const duringCheck=error.code==='out_of_scope'&&Array.isArray(error.violations)
|
|
965
|
+
&&error.violations.length>0&&error.violations.every(item=>item.newFile);
|
|
966
|
+
const blockedCode=duringCheck?'completion_package_changed':failureCode(error);
|
|
967
|
+
halt('blocked',blockedCode,blockedCode==='completion_checks_changed'&&failedChecks(fresh).length
|
|
968
|
+
?checkFailureReason(fresh):safeReason(error));return;
|
|
969
|
+
}
|
|
698
970
|
if(taskLearning!==null)try {
|
|
699
971
|
const learningInput=currentLearningInput();
|
|
700
972
|
verifyCmAiTaskLearningHandoff({handoffPath:completion.handoffs[attempt-1],feature:taskLearning.feature,
|
|
@@ -717,6 +989,25 @@ export function createTaskRunner(options) {
|
|
|
717
989
|
state='fixture_completed';return;
|
|
718
990
|
}
|
|
719
991
|
}
|
|
992
|
+
// No delivery can still be reviewed: journal the terminal limit instead of an
|
|
993
|
+
// intent, so no developer call runs (see developBudgetExhausted).
|
|
994
|
+
const retryLimitDue=()=>invocationMode&&store&&!poisoned
|
|
995
|
+
&&developBudgetExhausted({state,code,priorReview,calls,cache:[...cache.values()]});
|
|
996
|
+
function recordRetryLimit(){
|
|
997
|
+
const used=developBudget({calls,cache:[...cache.values()]});
|
|
998
|
+
persist('develop-retry-limit',{fromState:state,fromCode:code,countedCalls:used.calls,countedEffects:used.effects});
|
|
999
|
+
const recovered=readRunnerHistory(journal,metadata,3).state;
|
|
1000
|
+
({state,code}=recovered);reason=recovered.reason??null;publication=privateStatus();return publication;
|
|
1001
|
+
}
|
|
1002
|
+
// The completion re-check bound is spent: journal the terminal limit instead
|
|
1003
|
+
// of another complete intent (see completionRetriesExhausted).
|
|
1004
|
+
const completionLimitDue=()=>invocationMode&&store&&!poisoned&&completionRetriesExhausted({state,code,cache:[...cache.values()]});
|
|
1005
|
+
function recordCompletionLimit(){
|
|
1006
|
+
persist('completion-retry-limit',{fromCode:code,completionBlocks:completionBlockCount([...cache.values()])});
|
|
1007
|
+
const recovered=readRunnerHistory(journal,metadata,3).state;
|
|
1008
|
+
({state,code}=recovered);reason=recovered.reason??null;publication=privateStatus();return publication;
|
|
1009
|
+
}
|
|
1010
|
+
const limitDue=()=>retryLimitDue()?recordRetryLimit:completionLimitDue()?recordCompletionLimit:null;
|
|
720
1011
|
function executeEffect(raw) {
|
|
721
1012
|
let v;
|
|
722
1013
|
try {
|
|
@@ -737,36 +1028,77 @@ export function createTaskRunner(options) {
|
|
|
737
1028
|
if(old){need(old.digest===digest(v),'intent_conflict');return Promise.resolve(old.result);}
|
|
738
1029
|
if(restored?.pending?.id===v.id){need(digest(restored.pending)===digest(v),'intent_conflict');return Promise.resolve(status());}
|
|
739
1030
|
need(!busy,'busy');need(v.identity.attempt===attempt,'attempt_mismatch');
|
|
740
|
-
need(stageAllowed(v.kind,state,code),'stage_mismatch');need(
|
|
1031
|
+
need(stageAllowed(v.kind,state,code,priorReview?.verdict),'stage_mismatch');need(effectSlotFree(v.kind,[...cache.values()],calls),'limit_exceeded');
|
|
741
1032
|
if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
|
|
742
1033
|
if(v.kind==='develop'&&bootstrap!==null)bootstrap.assertWriteAuthorized();
|
|
743
1034
|
} catch(error){return Promise.resolve(freeze({outcome:'rejected',code:error.code??'invalid_input'}));}
|
|
1035
|
+
if(v.kind==='develop'&&retryLimitDue()){try{return Promise.resolve(recordRetryLimit());}catch{return Promise.resolve(poison());}}
|
|
1036
|
+
if(v.kind==='complete'&&completionLimitDue()){try{return Promise.resolve(recordCompletionLimit());}catch{return Promise.resolve(poison());}}
|
|
744
1037
|
if(store) {
|
|
745
1038
|
try {
|
|
746
|
-
if(state==='ready')
|
|
747
|
-
...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})}
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
//
|
|
751
|
-
|
|
1039
|
+
if(state==='ready')compareReviewBaseline(withBoundSpecification(captureReviewBaseline({...configToBaseline(metadata),version:original.version,
|
|
1040
|
+
...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
|
|
1041
|
+
!Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
|
|
1042
|
+
original.ignorePolicy?.version===2?original.ignorePolicy:null)),original);
|
|
1043
|
+
// A rejected first delivery has no review package yet. Every later
|
|
1044
|
+
// developer effect must recheck the reviewed tree before dispatch,
|
|
1045
|
+
// except one that redoes a delivery this attempt already made: that
|
|
1046
|
+
// delivery changed the tree on purpose and never became a package, so
|
|
1047
|
+
// it is compared against the baseline when the new package is built,
|
|
1048
|
+
// exactly as a redo at attempt 1 is.
|
|
1049
|
+
else if(reviewPackage!==null&&!(v.kind==='develop'&&state==='blocked'&&code!=='review_package_changed'
|
|
1050
|
+
&&stageAllowed('develop',state,code,priorReview?.verdict)))verifyReviewPackage({root:config.root,baseline:reviewPackage.identity.attempt===attempt?base:attemptBaseline(original,reviewPackage.identity.attempt),
|
|
752
1051
|
checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
|
|
753
|
-
} catch
|
|
1052
|
+
} catch(error){return Promise.resolve(freeze({outcome:'rejected',code:failureCode(error),
|
|
1053
|
+
...(safeReason(error)?{reason:safeReason(error)}:{})}));}
|
|
754
1054
|
try{const record=persist('effect-intent',{effect:v});
|
|
755
1055
|
if(taskMode&&v.kind==='complete')completeEffect={effect:v,digest:record.digest};
|
|
756
1056
|
}catch{return Promise.resolve(poison());}
|
|
757
1057
|
}
|
|
758
1058
|
busy=true;if(v.kind!=='develop')code=null;
|
|
1059
|
+
const packageBefore=reviewPackage;
|
|
759
1060
|
pending=(async()=>{
|
|
760
1061
|
try {await perform(v);}
|
|
761
|
-
catch(error){if(state!=='cancelled'){
|
|
1062
|
+
catch(error){if(state!=='cancelled'){
|
|
1063
|
+
const failure=failureCode(error);
|
|
1064
|
+
const checkOnly=failure==='out_of_scope'&&Array.isArray(error.violations)&&error.violations.length>0
|
|
1065
|
+
&&error.violations.every(item=>item.newFile&&checkNewPaths?.has(item.path));
|
|
1066
|
+
halt(checkOnly||failure==='spec_drift'?'blocked':'unknown',
|
|
1067
|
+
checkOnly?'check_output_out_of_scope':failure,
|
|
1068
|
+
['out_of_scope','unsupported_file','limit_exceeded','package_mismatch','snapshot_changed'].includes(failure)
|
|
1069
|
+
?safeReason(error):null);
|
|
1070
|
+
}}
|
|
762
1071
|
if(poisoned)return status();
|
|
763
|
-
|
|
764
|
-
|
|
1072
|
+
let result=privateStatus();cache.set(v.id,{effect:v,digest:digest(v),result});
|
|
1073
|
+
// A package the journal cannot hold would poison the store after the delivery
|
|
1074
|
+
// was written. Measure the exact checkpoint first; if it (plus room for the
|
|
1075
|
+
// review and completion checkpoints) does not fit, the delivery is redone.
|
|
1076
|
+
if(store&&v.kind==='develop'&&state==='awaiting_review'&&reviewPackage!==packageBefore){
|
|
1077
|
+
const bytes=payloadBytes('effect-checkpoint',{effectId:v.id,checkpoint:frame()});
|
|
1078
|
+
const size=value=>Buffer.byteLength(JSON.stringify(value??null));
|
|
1079
|
+
const reserve=developCheckpointReserve({examinedPathsBytes:size(reviewPaths(reviewPackage)),
|
|
1080
|
+
receiptsBytes:size(receipts),callsBytes:size(calls),writebackBytes:size(learningResult?.writeback)});
|
|
1081
|
+
const budget=JOURNAL_PAYLOAD_LIMIT-reserve;
|
|
1082
|
+
if(bytes>budget){
|
|
1083
|
+
const changed=reviewPackage.changes.filter(change=>change.after).map(change=>change.after);
|
|
1084
|
+
reviewPackage=packageBefore;
|
|
1085
|
+
halt('blocked','develop_package_too_large',boundedReason(`develop_package_too_large: the review checkpoint would be ${bytes} bytes, `
|
|
1086
|
+
+`above ${budget} (journal record limit ${JOURNAL_PAYLOAD_LIMIT} minus ${reserve} kept for the bounded review `
|
|
1087
|
+
+'and completion records); largest changed files: ',largestFiles(changed),
|
|
1088
|
+
'; shrink them or move them out of scope, then resume to redo this attempt'));
|
|
1089
|
+
result=privateStatus();cache.set(v.id,{effect:v,digest:digest(v),result});
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
try{persist('effect-checkpoint',{effectId:v.id,checkpoint:frame()});publication=result;}
|
|
765
1093
|
catch{return poison();}
|
|
1094
|
+
// A block or verdict that leaves no reviewable delivery ends the run now,
|
|
1095
|
+
// so status never invites a resume that could not finish.
|
|
1096
|
+
try{const record=limitDue();return record?record():result;}catch{return poison();}
|
|
766
1097
|
})().finally(()=>{busy=false;pending=null;completeEffect=null;}).then(result=>{
|
|
767
1098
|
if(poisoned)return result;
|
|
768
|
-
try{publishRegisteredReview();
|
|
1099
|
+
try{publishRegisteredReview();}
|
|
769
1100
|
catch{return freeze({...result,code:'review_publication_required'});}
|
|
1101
|
+
return result.state==='unknown'&&reviewResultAbandonable()?freeze({...result,abandonableReviewResult:true}):result;
|
|
770
1102
|
});
|
|
771
1103
|
return pending;
|
|
772
1104
|
}
|
|
@@ -806,8 +1138,9 @@ export function createTaskRunner(options) {
|
|
|
806
1138
|
catch {
|
|
807
1139
|
if(workflowError===null && control('workflow-error')) {
|
|
808
1140
|
const next=controlledState(frame(),'workflow-error',busy||restored?.pending!=null,version);
|
|
809
|
-
({state,code,workflowError}=next);
|
|
810
|
-
|
|
1141
|
+
({state,code,workflowError}=next);reason=next.reason??null;
|
|
1142
|
+
const {reason:oldReason,...currentPublication}=publication;
|
|
1143
|
+
publication=json({...currentPublication,workflowError,...(!busy?{state,code,...(reason?{reason}:{})}:{})},16*1024*1024);
|
|
811
1144
|
}
|
|
812
1145
|
}
|
|
813
1146
|
finally {
|
|
@@ -818,27 +1151,28 @@ export function createTaskRunner(options) {
|
|
|
818
1151
|
return status();
|
|
819
1152
|
}
|
|
820
1153
|
// Read-only content comparison, not completion authority or a JSON operation.
|
|
821
|
-
const inspectFixAssociation=fixPackage=>{
|
|
1154
|
+
const inspectFixAssociation=(fixPackage,evidence=null)=>{
|
|
822
1155
|
need(!busy&&!poisoned,'host_busy');
|
|
823
1156
|
const current=status();
|
|
824
1157
|
need(current.state==='fixture_completed'&¤t.code!=='review_publication_required','qa_fix_parent_not_completed');
|
|
1158
|
+
const known=acceptedFixes.some(item=>item.evidence.reviewPackage.packageDigest===fixPackage.packageDigest);
|
|
825
1159
|
return inspectFixCodeAssociation({root:config.root,
|
|
826
|
-
...(completion?{specsRoot:completion.owner.specsRoot}:{}),
|
|
827
|
-
baseline:base,parentPackage:reviewPackage,
|
|
828
|
-
fixPackages:acceptedFixes.
|
|
829
|
-
?acceptedFixes.map(item=>item.evidence.reviewPackage)
|
|
1160
|
+
...(completion?{specsRoot:completion.owner.specsRoot,...laterOptions(evidence)}:{}),
|
|
1161
|
+
baseline:base,parentPackage:reviewPackage,steps:acceptedFixes.at(-1)?.association.laterDeliveries??[],extend:!known,
|
|
1162
|
+
fixPackages:known?acceptedFixes.map(item=>item.evidence.reviewPackage)
|
|
830
1163
|
:[...acceptedFixes.map(item=>item.evidence.reviewPackage),fixPackage]});
|
|
831
1164
|
};
|
|
832
1165
|
const acceptCompletedFix=raw=>{
|
|
833
1166
|
need(invocationMode&&store&&!busy&&!poisoned,'fix_accept_unavailable');
|
|
834
|
-
const evidence=json(raw,12*1024*1024),association=inspectFixAssociation(evidence.reviewPackage);
|
|
1167
|
+
const evidence=json(raw,12*1024*1024),association=inspectFixAssociation(evidence.reviewPackage,evidence);
|
|
835
1168
|
const existing=acceptedFixes.find(item=>item.evidence.qaSource.testRunId===evidence.qaSource.testRunId);
|
|
836
1169
|
if(existing){need(digest(existing.evidence)===digest(evidence),'fix_evidence_changed');return json(existing,12*1024*1024);}
|
|
837
1170
|
const source=evidence.qaSource;
|
|
838
1171
|
const failure=inspectCmAiQaFailure({specsDir:completion.owner.specsRoot,feature:source.feature,
|
|
839
1172
|
identity:source.identity,packageDigest:source.packageDigest,testRunId:source.testRunId});
|
|
840
1173
|
const record=validateAcceptedFix({record:{evidence,association,qaRound:failure.qaRound},previous:acceptedFixes,
|
|
841
|
-
baseline:base,parentPackage:reviewPackage,feature:taskLearning?.feature});
|
|
1174
|
+
baseline:base,parentPackage:reviewPackage,feature:taskLearning?.feature,resolveSteps:steps=>resolveSteps(steps)});
|
|
1175
|
+
assertJournalFits('qa-fix-accepted',{record},'fix_record_too_large');
|
|
842
1176
|
persist('qa-fix-accepted',{record});acceptedFixes.push(record);
|
|
843
1177
|
return json(record,12*1024*1024);
|
|
844
1178
|
};
|
|
@@ -852,25 +1186,128 @@ export function createTaskRunner(options) {
|
|
|
852
1186
|
const reviseQa=raw=>{
|
|
853
1187
|
need(invocationMode&&store&&!busy&&!poisoned,'qa_revision_unavailable');
|
|
854
1188
|
const record=readQaConfigRevision(raw),current=status();
|
|
855
|
-
|
|
856
|
-
|
|
1189
|
+
// Before the first QA round (the caller checks the QA log) development may
|
|
1190
|
+
// still be in progress, but never with an unresolved effect, after
|
|
1191
|
+
// cancellation, or over completed code that no longer matches its review.
|
|
1192
|
+
if(beforeFirstQaRound(record))need(!['unknown','cancelled'].includes(current.state)
|
|
1193
|
+
&&!(current.state==='fixture_completed'&¤t.code!==null),'qa_revision_not_completed');
|
|
1194
|
+
else need(current.state==='fixture_completed'&¤t.code===null,'qa_revision_not_completed');
|
|
1195
|
+
need((current.packageDigest??null)===record.packageDigest,'package_mismatch');
|
|
857
1196
|
persist('qa-config-revised',{record});return json(record);
|
|
858
1197
|
};
|
|
1198
|
+
// Explicit, journaled continuation after a proper re-approval. Refused unless
|
|
1199
|
+
// everything this run's developer and reviewer see is unchanged; the record
|
|
1200
|
+
// then lets the bound material verify against the re-approved hashes only.
|
|
1201
|
+
const rebindSpecification=raw=>{
|
|
1202
|
+
const refuse=(code,why)=>{throw Object.assign(new Error(code),{code,reason:why});};
|
|
1203
|
+
need(invocationMode&&store&&!busy&&!poisoned,'spec_rebind_unavailable');
|
|
1204
|
+
const value=json(raw);shape(value,['version','reason','at']);need(value.version===1,'invalid_input');
|
|
1205
|
+
if(!Object.hasOwn(original,'specification'))refuse('spec_rebind_unavailable','本运行没有绑定规格材料(旧版运行),无需换绑');
|
|
1206
|
+
const drift=inspectSpecificationDrift(original);
|
|
1207
|
+
if(drift===null)return freeze({outcome:'unchanged'});
|
|
1208
|
+
if(restored?.pending||!specificationLive(state,code))
|
|
1209
|
+
refuse('spec_rebind_unavailable',`运行当前为 ${state}${code?`/${code}`:''},没有待执行的开发、审查或完成,不能换绑`);
|
|
1210
|
+
if(!drift.rebindable)refuse('spec_rebind_refused',describeSpecificationDrift(drift));
|
|
1211
|
+
const record=readSpecificationRebind({version:1,taskId:config.identity.taskId,boundDigest:digest(original.specification),
|
|
1212
|
+
sources:drift.sources,files:drift.files,reason:value.reason,reboundAt:value.at});
|
|
1213
|
+
persist('specification-rebound',{record});
|
|
1214
|
+
return json({outcome:'rebound',record});
|
|
1215
|
+
};
|
|
859
1216
|
const supersedeEvidence=raw=>{
|
|
860
1217
|
need(invocationMode&&store&&!busy&&!poisoned,'supersede_unavailable');
|
|
861
1218
|
const record=readEvidenceSupersession(raw,{feature:taskLearning.feature,
|
|
862
1219
|
taskId:config.identity.taskId,newRunId:config.identity.runId});
|
|
863
1220
|
if(restored?.supersession){need(digest(restored.supersession)===digest(record),'supersede_record_invalid');return json(record);}
|
|
864
1221
|
need(journal.length===1&&state==='ready','supersede_unavailable');
|
|
865
|
-
persist('evidence-superseded',{record});return json(record);
|
|
1222
|
+
persist('evidence-superseded',{record});carriedReview=record.carriedReview??null;return json(record);
|
|
866
1223
|
};
|
|
867
|
-
const
|
|
1224
|
+
const abandonReview=raw=>{
|
|
1225
|
+
try{
|
|
1226
|
+
need(invocationMode&&store&&!busy&&!poisoned&&state==='unknown'
|
|
1227
|
+
&&(restored?.pending?.kind==='review'||reviewResultAbandonable()),'review_abandon_unavailable');
|
|
1228
|
+
const value=json(raw);shape(value,['allowed','reason']);
|
|
1229
|
+
need(value.allowed===true,'review_abandon_authorization_required');
|
|
1230
|
+
need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
|
|
1231
|
+
&&!/[\r\n\0]/.test(value.reason),'review_abandon_reason_required');
|
|
1232
|
+
if(!restored?.pending){
|
|
1233
|
+
// A checkpointed review whose journaled result was never accepted.
|
|
1234
|
+
const binding=readRunnerHistory(journal,metadata,3).reviewResultAbandon;
|
|
1235
|
+
need(binding!==null,'review_abandon_unavailable');
|
|
1236
|
+
persist('review-invocation-abandoned',{...binding,reason:value.reason,at:new Date().toISOString()});
|
|
1237
|
+
const recovered=readRunnerHistory(journal,metadata,3).state;
|
|
1238
|
+
({state,code,sequence,reviewInvocation}=recovered);reason=recovered.reason??null;
|
|
1239
|
+
calls.splice(0,calls.length,...recovered.calls);
|
|
1240
|
+
publication=privateStatus();return status();
|
|
1241
|
+
}
|
|
1242
|
+
const history=readRunnerHistory(journal,metadata,3),last=journal.at(-1);
|
|
1243
|
+
need(history.pending?.id===restored.pending.id&&history.state.state==='unknown'
|
|
1244
|
+
&&history.state.code==='reconciliation_required'
|
|
1245
|
+
&&['review-invocation-registered','review-invocation-started'].includes(last?.payload?.type)
|
|
1246
|
+
&&history.state.reviewInvocation?.registration&&history.state.reviewInvocation.result===null,
|
|
1247
|
+
'review_abandon_unavailable');
|
|
1248
|
+
const registration=journal.findLast(row=>row.payload.type==='review-invocation-registered'
|
|
1249
|
+
&&row.payload.effectId===history.pending.id);
|
|
1250
|
+
const started=last.payload.type==='review-invocation-started'?last:null;
|
|
1251
|
+
need(registration,'review_abandon_unavailable');
|
|
1252
|
+
const contextId=reviewers[0].contexts[attempt-1];
|
|
1253
|
+
need(!reviewRetrySpent(history.state.cache,history.state.calls,attempt,contextId),'review_abandon_budget_exhausted');
|
|
1254
|
+
const fields={effectId:history.pending.id,
|
|
1255
|
+
invocationId:history.state.reviewInvocation.registration.grant.invocationId,
|
|
1256
|
+
registeredDigest:registration.digest,startedDigest:started?.digest??null,
|
|
1257
|
+
reason:value.reason,at:new Date().toISOString()};
|
|
1258
|
+
persist('review-invocation-abandoned',fields);
|
|
1259
|
+
const recovered=readRunnerHistory(journal,metadata,3).state;
|
|
1260
|
+
({state,code,sequence,reviewInvocation}=recovered);calls.push(...recovered.calls.slice(calls.length));
|
|
1261
|
+
publication=privateStatus();return status();
|
|
1262
|
+
}catch(error){return freeze({outcome:'rejected',code:error.code??'review_abandon_unavailable'});}
|
|
1263
|
+
};
|
|
1264
|
+
const abandonEffect=raw=>{
|
|
1265
|
+
try{
|
|
1266
|
+
need(invocationMode&&store&&!busy&&!poisoned&&options.persistence.mode==='resume','effect_abandon_unavailable');
|
|
1267
|
+
const value=json(raw);shape(value,['allowed','reason']);
|
|
1268
|
+
need(value.allowed===true,'effect_abandon_authorization_required');
|
|
1269
|
+
need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
|
|
1270
|
+
&&!/[\r\n\0]/.test(value.reason),'effect_abandon_reason_required');
|
|
1271
|
+
const history=readRunnerHistory(journal,metadata,3),effect=history.pending;
|
|
1272
|
+
need(effect!==null,'effect_abandon_no_pending');
|
|
1273
|
+
need(effect.kind!=='review'||history.pendingAbandonable,'effect_abandon_review_pending');
|
|
1274
|
+
need(['develop','complete','review'].includes(effect.kind),'effect_abandon_unavailable');
|
|
1275
|
+
need(effect.kind!=='develop'||options.providerDevelopment!==true,'effect_abandon_provider_development');
|
|
1276
|
+
need(history.transaction===null&&history.state.taskCommit?.intentDigest==null,'effect_abandon_commit_pending');
|
|
1277
|
+
need(history.state.state==='unknown'&&history.state.code==='reconciliation_required'
|
|
1278
|
+
&&history.pendingAbandonable,'effect_abandon_unavailable');
|
|
1279
|
+
const intent=journal.findLast(row=>row.payload.type==='effect-intent');
|
|
1280
|
+
persist('effect-abandoned',{effectId:effect.id,effectKind:effect.kind,intentDigest:intent.digest,
|
|
1281
|
+
lastRecordDigest:journal.at(-1).digest,reason:value.reason,at:new Date().toISOString()});
|
|
1282
|
+
const recovered=readRunnerHistory(journal,metadata,3).state;
|
|
1283
|
+
({state,code,sequence}=recovered);reason=recovered.reason;restored.pending=null;
|
|
1284
|
+
publication=privateStatus();return status();
|
|
1285
|
+
}catch(error){return freeze({outcome:'rejected',code:error.code??'effect_abandon_unavailable',
|
|
1286
|
+
...(error.code==='effect_abandon_commit_pending'?{reason:'task-commit-intent 已写入,tasks.md 可能已改名或勾选;请核对 tasks.md、提交回执和旧进程后按原提交恢复路径处理。'}:{})});}
|
|
1287
|
+
};
|
|
1288
|
+
const api={reviseQa,supersedeEvidence,rebindSpecification,abandonReview,abandonEffect,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks};
|
|
868
1289
|
if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
|
|
869
1290
|
if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
|
|
1291
|
+
// A terminal reviewer observation is durable even if the host died before
|
|
1292
|
+
// the checkpoint. Finish that same effect from its validated journal bytes.
|
|
1293
|
+
if(restored?.pendingObservedReview){
|
|
1294
|
+
const observed=restored.pendingObservedReview,request=observed.request,result=observed.result;
|
|
1295
|
+
const call={invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
|
|
1296
|
+
requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-authorized',
|
|
1297
|
+
started:true,terminal:'succeeded',requestDigest:request.requestDigest,
|
|
1298
|
+
resultDigest:digest(result.inspection.review),providerThreadId:observed.started};
|
|
1299
|
+
sequence++;calls.push(call);
|
|
1300
|
+
reviewInvocation=json({registration:observed.registration,started:observed.started,result});
|
|
1301
|
+
acceptReview(request,call,result.inspection.review);
|
|
1302
|
+
const effect=restored.pending,response=privateStatus();
|
|
1303
|
+
cache.set(effect.id,{effect,digest:digest(effect),result:response});
|
|
1304
|
+
persist('effect-checkpoint',{effectId:effect.id,checkpoint:frame()});
|
|
1305
|
+
restored.pending=null;publication=response;
|
|
1306
|
+
}
|
|
870
1307
|
return Object.freeze(api);
|
|
871
1308
|
}
|
|
872
1309
|
function configToBaseline(c){
|
|
873
|
-
const scope=Object.hasOwn(c,'taskLearning')
|
|
1310
|
+
const scope=Object.hasOwn(c,'taskLearning')?taskReviewScope(c.scope):c.scope;
|
|
874
1311
|
return {root:c.root,identity:c.identity,scope,requirements:c.requirements,
|
|
875
1312
|
...(c.codeProjectPaths?{codeProjectPaths:c.codeProjectPaths}:{}),
|
|
876
1313
|
...(c.bootstrap?{bootstrapRequirements:c.bootstrap.bootstrapRequirements}:{}),
|