clinkx 1.1.2 → 1.3.0
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/CHANGELOG.md +63 -0
- package/README.md +67 -14
- package/clinkx-workflows/dist/allowed-roots.js +2 -0
- package/clinkx-workflows/dist/allowed-roots.js.map +1 -1
- package/clinkx-workflows/dist/architecture-arena/admission.d.ts +16 -0
- package/clinkx-workflows/dist/architecture-arena/admission.js +107 -0
- package/clinkx-workflows/dist/architecture-arena/admission.js.map +1 -0
- package/clinkx-workflows/dist/architecture-arena/contract.d.ts +1368 -0
- package/clinkx-workflows/dist/architecture-arena/contract.js +254 -0
- package/clinkx-workflows/dist/architecture-arena/contract.js.map +1 -0
- package/clinkx-workflows/dist/architecture-arena/runtime.d.ts +53 -0
- package/clinkx-workflows/dist/architecture-arena/runtime.js +511 -0
- package/clinkx-workflows/dist/architecture-arena/runtime.js.map +1 -0
- package/clinkx-workflows/dist/architecture-comparison/admission.d.ts +17 -1
- package/clinkx-workflows/dist/architecture-comparison/admission.js +27 -4
- package/clinkx-workflows/dist/architecture-comparison/admission.js.map +1 -1
- package/clinkx-workflows/dist/architecture-comparison/contract.d.ts +59 -62
- package/clinkx-workflows/dist/architecture-comparison/contract.js +4 -21
- package/clinkx-workflows/dist/architecture-comparison/contract.js.map +1 -1
- package/clinkx-workflows/dist/architecture-comparison/runtime.d.ts +4 -3
- package/clinkx-workflows/dist/architecture-comparison/runtime.js +22 -67
- package/clinkx-workflows/dist/architecture-comparison/runtime.js.map +1 -1
- package/clinkx-workflows/dist/artifacts.d.ts +19 -4
- package/clinkx-workflows/dist/artifacts.js +16 -7
- package/clinkx-workflows/dist/artifacts.js.map +1 -1
- package/clinkx-workflows/dist/backend.d.ts +30 -0
- package/clinkx-workflows/dist/child-env.d.ts +3 -1
- package/clinkx-workflows/dist/child-env.js +6 -2
- package/clinkx-workflows/dist/child-env.js.map +1 -1
- package/clinkx-workflows/dist/clink-client.d.ts +8 -2
- package/clinkx-workflows/dist/clink-client.js +4 -2
- package/clinkx-workflows/dist/clink-client.js.map +1 -1
- package/clinkx-workflows/dist/config.d.ts +28 -5
- package/clinkx-workflows/dist/config.js +137 -20
- package/clinkx-workflows/dist/config.js.map +1 -1
- package/clinkx-workflows/dist/contained-file.js +9 -0
- package/clinkx-workflows/dist/contained-file.js.map +1 -1
- package/clinkx-workflows/dist/context-preflight.d.ts +6 -0
- package/clinkx-workflows/dist/context-preflight.js.map +1 -1
- package/clinkx-workflows/dist/council-execution-policy.d.ts +3 -1
- package/clinkx-workflows/dist/council-execution-policy.js +4 -0
- package/clinkx-workflows/dist/council-execution-policy.js.map +1 -1
- package/clinkx-workflows/dist/dashboard/contracts.d.ts +586 -586
- package/clinkx-workflows/dist/dashboard/progress-report-contract.d.ts +28 -28
- package/clinkx-workflows/dist/dashboard/session-log-contract.d.ts +32 -32
- package/clinkx-workflows/dist/dashboard/session-log-identity.js +2 -1
- package/clinkx-workflows/dist/dashboard/session-log-identity.js.map +1 -1
- package/clinkx-workflows/dist/dashboard-ui/assets/index-DRId2DVA.js +119 -0
- package/clinkx-workflows/dist/dashboard-ui/assets/style-CHAw57y5.css +1 -0
- package/clinkx-workflows/dist/dashboard-ui/index.html +2 -2
- package/clinkx-workflows/dist/delegate-signature.d.ts +4 -3
- package/clinkx-workflows/dist/delegate-signature.js +4 -3
- package/clinkx-workflows/dist/delegate-signature.js.map +1 -1
- package/clinkx-workflows/dist/durable-file.d.ts +69 -0
- package/clinkx-workflows/dist/durable-file.js +145 -0
- package/clinkx-workflows/dist/durable-file.js.map +1 -0
- package/clinkx-workflows/dist/engine.d.ts +42 -7
- package/clinkx-workflows/dist/engine.js +196 -24
- package/clinkx-workflows/dist/engine.js.map +1 -1
- package/clinkx-workflows/dist/ping-pong/admission.d.ts +127 -0
- package/clinkx-workflows/dist/ping-pong/admission.js +522 -0
- package/clinkx-workflows/dist/ping-pong/admission.js.map +1 -0
- package/clinkx-workflows/dist/ping-pong/contract.d.ts +2539 -0
- package/clinkx-workflows/dist/ping-pong/contract.js +819 -0
- package/clinkx-workflows/dist/ping-pong/contract.js.map +1 -0
- package/clinkx-workflows/dist/ping-pong/control.d.ts +67 -0
- package/clinkx-workflows/dist/ping-pong/control.js +12 -0
- package/clinkx-workflows/dist/ping-pong/control.js.map +1 -0
- package/clinkx-workflows/dist/ping-pong/runtime-handle.d.ts +24 -0
- package/clinkx-workflows/dist/ping-pong/runtime-handle.js +55 -0
- package/clinkx-workflows/dist/ping-pong/runtime-handle.js.map +1 -0
- package/clinkx-workflows/dist/ping-pong/runtime.d.ts +235 -0
- package/clinkx-workflows/dist/ping-pong/runtime.js +1183 -0
- package/clinkx-workflows/dist/ping-pong/runtime.js.map +1 -0
- package/clinkx-workflows/dist/ping-pong/settle.d.ts +57 -0
- package/clinkx-workflows/dist/ping-pong/settle.js +58 -0
- package/clinkx-workflows/dist/ping-pong/settle.js.map +1 -0
- package/clinkx-workflows/dist/ping-pong/sidecar.d.ts +65 -0
- package/clinkx-workflows/dist/ping-pong/sidecar.js +138 -0
- package/clinkx-workflows/dist/ping-pong/sidecar.js.map +1 -0
- package/clinkx-workflows/dist/plan-review/publication.d.ts +2 -1
- package/clinkx-workflows/dist/plan-review/publication.js +5 -6
- package/clinkx-workflows/dist/plan-review/publication.js.map +1 -1
- package/clinkx-workflows/dist/plan-review/snapshot.d.ts +3 -2
- package/clinkx-workflows/dist/plan-review/snapshot.js +8 -8
- package/clinkx-workflows/dist/plan-review/snapshot.js.map +1 -1
- package/clinkx-workflows/dist/recipe-host.d.ts +315 -0
- package/clinkx-workflows/dist/recipe-host.js +183 -0
- package/clinkx-workflows/dist/recipe-host.js.map +1 -0
- package/clinkx-workflows/dist/recipe-seats.d.ts +96 -0
- package/clinkx-workflows/dist/recipe-seats.js +163 -0
- package/clinkx-workflows/dist/recipe-seats.js.map +1 -0
- package/clinkx-workflows/dist/recipe-shared/evidence.d.ts +67 -0
- package/clinkx-workflows/dist/recipe-shared/evidence.js +111 -0
- package/clinkx-workflows/dist/recipe-shared/evidence.js.map +1 -0
- package/clinkx-workflows/dist/reducers/index.d.ts +9 -1
- package/clinkx-workflows/dist/reducers/index.js +30 -0
- package/clinkx-workflows/dist/reducers/index.js.map +1 -1
- package/clinkx-workflows/dist/root-path-validation.d.ts +12 -0
- package/clinkx-workflows/dist/root-path-validation.js +63 -0
- package/clinkx-workflows/dist/root-path-validation.js.map +1 -0
- package/clinkx-workflows/dist/rosters.d.ts +1 -0
- package/clinkx-workflows/dist/rosters.js +16 -6
- package/clinkx-workflows/dist/rosters.js.map +1 -1
- package/clinkx-workflows/dist/run-lock-reclaim.d.ts +44 -0
- package/clinkx-workflows/dist/run-lock-reclaim.js +86 -0
- package/clinkx-workflows/dist/run-lock-reclaim.js.map +1 -0
- package/clinkx-workflows/dist/server.js +5 -2
- package/clinkx-workflows/dist/server.js.map +1 -1
- package/clinkx-workflows/dist/state-schema.d.ts +24 -0
- package/clinkx-workflows/dist/state-schema.js +4 -1
- package/clinkx-workflows/dist/state-schema.js.map +1 -1
- package/clinkx-workflows/dist/state.d.ts +185 -4
- package/clinkx-workflows/dist/state.js +684 -88
- package/clinkx-workflows/dist/state.js.map +1 -1
- package/clinkx-workflows/dist/transport.d.ts +2 -1
- package/clinkx-workflows/dist/transport.js +5 -0
- package/clinkx-workflows/dist/transport.js.map +1 -1
- package/clinkx-workflows/dist/validators/architecture-arena.d.ts +6 -0
- package/clinkx-workflows/dist/validators/architecture-arena.js +16 -0
- package/clinkx-workflows/dist/validators/architecture-arena.js.map +1 -0
- package/clinkx-workflows/dist/validators/index.js +4 -0
- package/clinkx-workflows/dist/validators/index.js.map +1 -1
- package/clinkx-workflows/dist/validators/ping-pong.d.ts +6 -0
- package/clinkx-workflows/dist/validators/ping-pong.js +10 -0
- package/clinkx-workflows/dist/validators/ping-pong.js.map +1 -0
- package/clinkx-workflows/dist/workflow-completion.d.ts +83 -0
- package/clinkx-workflows/dist/workflow-completion.js +250 -0
- package/clinkx-workflows/dist/workflow-completion.js.map +1 -0
- package/clinkx-workflows/dist/workflow-tools.d.ts +53 -6
- package/clinkx-workflows/dist/workflow-tools.js +1123 -65
- package/clinkx-workflows/dist/workflow-tools.js.map +1 -1
- package/clinkx-workflows/dist/workflow-verification-contract.d.ts +4 -4
- package/clinkx-workflows/templates/architecture-arena/candidate.txt +39 -0
- package/clinkx-workflows/templates/architecture-arena/judge.txt +34 -0
- package/clinkx-workflows/templates/ping-pong/implement.txt +14 -0
- package/clinkx-workflows/templates/ping-pong/remediate.txt +14 -0
- package/clinkx-workflows/templates/ping-pong/review.txt +27 -0
- package/clinkx-workflows/workflows/architecture-arena.yaml +127 -0
- package/clinkx-workflows/workflows/ping-pong.yaml +158 -0
- package/dist/allowed-roots.d.ts +1 -1
- package/dist/allowed-roots.js +124 -14
- package/dist/allowed-roots.js.map +1 -1
- package/dist/context-builder/bundle.js +4 -3
- package/dist/context-builder/bundle.js.map +1 -1
- package/dist/context-builder/config.d.ts +1 -0
- package/dist/context-builder/config.js +21 -9
- package/dist/context-builder/config.js.map +1 -1
- package/dist/context-builder/delegate-packet.d.ts +1 -0
- package/dist/context-builder/delegate-packet.js +66 -7
- package/dist/context-builder/delegate-packet.js.map +1 -1
- package/dist/context-builder/delegate-validation.d.ts +12 -3
- package/dist/context-builder/delegate-validation.js +23 -13
- package/dist/context-builder/delegate-validation.js.map +1 -1
- package/dist/context-builder/external-gaps.d.ts +14 -3
- package/dist/context-builder/external-gaps.js +124 -18
- package/dist/context-builder/external-gaps.js.map +1 -1
- package/dist/context-builder/handler.js +108 -191
- package/dist/context-builder/handler.js.map +1 -1
- package/dist/context-builder/mutation-lock.d.ts +4 -0
- package/dist/context-builder/mutation-lock.js +7 -1
- package/dist/context-builder/mutation-lock.js.map +1 -1
- package/dist/context-builder/review-coverage.js +27 -1
- package/dist/context-builder/review-coverage.js.map +1 -1
- package/dist/context-builder/secrets.js +1 -1
- package/dist/context-builder/secrets.js.map +1 -1
- package/dist/context-builder/storage.d.ts +10 -2
- package/dist/context-builder/storage.js +213 -16
- package/dist/context-builder/storage.js.map +1 -1
- package/dist/context-builder/versions.d.ts +10 -4
- package/dist/context-builder/versions.js +10 -4
- package/dist/context-builder/versions.js.map +1 -1
- package/dist/context-builder/workflow-runner.js +33 -24
- package/dist/context-builder/workflow-runner.js.map +1 -1
- package/dist/dashboard-cli.d.ts +8 -0
- package/dist/dashboard-cli.js +155 -86
- package/dist/dashboard-cli.js.map +1 -1
- package/dist/dashboard-companion/client.d.ts +10 -0
- package/dist/dashboard-companion/client.js +43 -1
- package/dist/dashboard-companion/client.js.map +1 -1
- package/dist/dashboard-companion/config.d.ts +19 -1
- package/dist/dashboard-companion/config.js +104 -3
- package/dist/dashboard-companion/config.js.map +1 -1
- package/dist/dashboard-companion/protocol.d.ts +16 -0
- package/dist/dashboard-companion/protocol.js +38 -1
- package/dist/dashboard-companion/protocol.js.map +1 -1
- package/dist/dashboard-companion/workstation-binding.d.ts +69 -0
- package/dist/dashboard-companion/workstation-binding.js +192 -0
- package/dist/dashboard-companion/workstation-binding.js.map +1 -0
- package/dist/dashboard-gateway/admin-cli.d.ts +10 -0
- package/dist/dashboard-gateway/admin-cli.js +266 -0
- package/dist/dashboard-gateway/admin-cli.js.map +1 -0
- package/dist/dashboard-gateway/config.d.ts +50 -0
- package/dist/dashboard-gateway/config.js +235 -1
- package/dist/dashboard-gateway/config.js.map +1 -1
- package/dist/dashboard-gateway/connection-registry.d.ts +100 -0
- package/dist/dashboard-gateway/connection-registry.js +228 -0
- package/dist/dashboard-gateway/connection-registry.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/account-auth.d.ts +78 -0
- package/dist/dashboard-gateway/control-plane/account-auth.js +198 -0
- package/dist/dashboard-gateway/control-plane/account-auth.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/billing.d.ts +264 -0
- package/dist/dashboard-gateway/control-plane/billing.js +787 -0
- package/dist/dashboard-gateway/control-plane/billing.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/contracts.d.ts +1293 -0
- package/dist/dashboard-gateway/control-plane/contracts.js +280 -0
- package/dist/dashboard-gateway/control-plane/contracts.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/cookies.d.ts +13 -0
- package/dist/dashboard-gateway/control-plane/cookies.js +46 -0
- package/dist/dashboard-gateway/control-plane/cookies.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/credentials.d.ts +63 -0
- package/dist/dashboard-gateway/control-plane/credentials.js +66 -0
- package/dist/dashboard-gateway/control-plane/credentials.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/entitlements.d.ts +118 -0
- package/dist/dashboard-gateway/control-plane/entitlements.js +329 -0
- package/dist/dashboard-gateway/control-plane/entitlements.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/errors.d.ts +17 -0
- package/dist/dashboard-gateway/control-plane/errors.js +23 -0
- package/dist/dashboard-gateway/control-plane/errors.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/hosts.d.ts +6 -0
- package/dist/dashboard-gateway/control-plane/hosts.js +16 -0
- package/dist/dashboard-gateway/control-plane/hosts.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/http.d.ts +34 -0
- package/dist/dashboard-gateway/control-plane/http.js +331 -0
- package/dist/dashboard-gateway/control-plane/http.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/schema.d.ts +9 -0
- package/dist/dashboard-gateway/control-plane/schema.js +247 -0
- package/dist/dashboard-gateway/control-plane/schema.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/secrets.d.ts +20 -0
- package/dist/dashboard-gateway/control-plane/secrets.js +39 -0
- package/dist/dashboard-gateway/control-plane/secrets.js.map +1 -0
- package/dist/dashboard-gateway/control-plane/store.d.ts +579 -0
- package/dist/dashboard-gateway/control-plane/store.js +1115 -0
- package/dist/dashboard-gateway/control-plane/store.js.map +1 -0
- package/dist/dashboard-gateway/cookie-boundary.d.ts +60 -0
- package/dist/dashboard-gateway/cookie-boundary.js +205 -0
- package/dist/dashboard-gateway/cookie-boundary.js.map +1 -0
- package/dist/dashboard-gateway/index.js +271 -494
- package/dist/dashboard-gateway/index.js.map +1 -1
- package/dist/dashboard-gateway/main.js +7 -2
- package/dist/dashboard-gateway/main.js.map +1 -1
- package/dist/dashboard-gateway/routing.d.ts +43 -0
- package/dist/dashboard-gateway/routing.js +65 -0
- package/dist/dashboard-gateway/routing.js.map +1 -0
- package/dist/dashboard-gateway/tenant-gateway.d.ts +56 -0
- package/dist/dashboard-gateway/tenant-gateway.js +989 -0
- package/dist/dashboard-gateway/tenant-gateway.js.map +1 -0
- package/dist/dashboard-gateway/tenant-main.d.ts +41 -0
- package/dist/dashboard-gateway/tenant-main.js +303 -0
- package/dist/dashboard-gateway/tenant-main.js.map +1 -0
- package/dist/dashboard-gateway/tunnel-errors.d.ts +16 -0
- package/dist/dashboard-gateway/tunnel-errors.js +22 -0
- package/dist/dashboard-gateway/tunnel-errors.js.map +1 -0
- package/dist/dashboard-gateway/tunnel-http.d.ts +21 -0
- package/dist/dashboard-gateway/tunnel-http.js +175 -0
- package/dist/dashboard-gateway/tunnel-http.js.map +1 -0
- package/dist/handler.d.ts +6 -0
- package/dist/handler.js +17 -1
- package/dist/handler.js.map +1 -1
- package/dist/local-clink-backend.d.ts +2 -1
- package/dist/local-clink-backend.js +28 -4
- package/dist/local-clink-backend.js.map +1 -1
- package/dist/parsers/extract.d.ts +19 -1
- package/dist/parsers/extract.js +68 -3
- package/dist/parsers/extract.js.map +1 -1
- package/dist/pipeline.d.ts +17 -1
- package/dist/pipeline.js +34 -6
- package/dist/pipeline.js.map +1 -1
- package/dist/process-group.d.ts +65 -0
- package/dist/process-group.js +153 -0
- package/dist/process-group.js.map +1 -0
- package/dist/progress-report/schema.d.ts +23 -23
- package/dist/project-verification/files.js +1 -1
- package/dist/project-verification/files.js.map +1 -1
- package/dist/project-verification/process.js +23 -44
- package/dist/project-verification/process.js.map +1 -1
- package/dist/project-verification/service.js +9 -1
- package/dist/project-verification/service.js.map +1 -1
- package/dist/prompt.d.ts +7 -0
- package/dist/prompt.js +18 -1
- package/dist/prompt.js.map +1 -1
- package/dist/recipe-host/git-trust.d.ts +43 -0
- package/dist/recipe-host/git-trust.js +360 -0
- package/dist/recipe-host/git-trust.js.map +1 -0
- package/dist/recipe-host/git.d.ts +42 -0
- package/dist/recipe-host/git.js +207 -0
- package/dist/recipe-host/git.js.map +1 -0
- package/dist/recipe-host/native-recipe-host.d.ts +127 -0
- package/dist/recipe-host/native-recipe-host.js +880 -0
- package/dist/recipe-host/native-recipe-host.js.map +1 -0
- package/dist/recipe-host/seat-cwd.d.ts +16 -0
- package/dist/recipe-host/seat-cwd.js +170 -0
- package/dist/recipe-host/seat-cwd.js.map +1 -0
- package/dist/registry.d.ts +1 -1
- package/dist/registry.js +5 -1
- package/dist/registry.js.map +1 -1
- package/dist/runner.d.ts +43 -1
- package/dist/runner.js +234 -35
- package/dist/runner.js.map +1 -1
- package/dist/server.js +21 -6
- package/dist/server.js.map +1 -1
- package/docs/configuration.md +181 -15
- package/docs/engineering-recipes.md +291 -0
- package/docs/security.md +87 -0
- package/docs/verification/project-checks.md +24 -2
- package/package.json +5 -1
- package/scripts/provider-doctor-core.mjs +21 -5
- package/clinkx-workflows/dist/dashboard-ui/assets/index-BdpmbPps.js +0 -115
- package/clinkx-workflows/dist/dashboard-ui/assets/style-Im5i1iAs.css +0 -1
|
@@ -5,11 +5,12 @@
|
|
|
5
5
|
* - Standalone STDIO server (ClinkSession child process backend)
|
|
6
6
|
* - In-process integration (LocalClinkBackend via root ClinkX)
|
|
7
7
|
*
|
|
8
|
-
* The `registerWorkflowTools()` function registers
|
|
8
|
+
* The `registerWorkflowTools()` function registers six tools on a Server:
|
|
9
9
|
* - run_workflow: start a new workflow execution
|
|
10
10
|
* - resume_workflow: resume a failed/cancelled run
|
|
11
11
|
* - list_workflows: list available workflow definitions
|
|
12
12
|
* - workflow_run_status: read workflow run progress/result
|
|
13
|
+
* - workflow_run_wait: observe local execution settlement
|
|
13
14
|
* - cancel_workflow: cancel a live or orphaned workflow run
|
|
14
15
|
*
|
|
15
16
|
* The caller provides a `createBackend` factory that determines how clink
|
|
@@ -21,7 +22,7 @@ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
|
21
22
|
import { computeRunHealth } from "./run-health.js";
|
|
22
23
|
import { loadWorkflow, listWorkflowCatalog } from "./loader.js";
|
|
23
24
|
import { defaultWorkflowAllowedRoots, WorkflowEngine } from "./engine.js";
|
|
24
|
-
import { readRunStateForStatus, reapRunCancelled, WorkflowStateStore } from "./state.js";
|
|
25
|
+
import { readRunStateForStatus, reapRunCancelled, RecipeReopenError, recordRecipeOrphanCancel, WorkflowStateStore, } from "./state.js";
|
|
25
26
|
import { isTerminalContextBuilderLifecycleStatus, parseContextBuilderLifecycleStateV1, } from "./context-builder-lifecycle-contract.js";
|
|
26
27
|
import { validateRunId } from "./run-id.js";
|
|
27
28
|
import { validateDynamicPaths } from "./path-validation.js";
|
|
@@ -35,6 +36,7 @@ import { buildRunSummaryOrUndefined, buildFailureRunSummary } from "./run-summar
|
|
|
35
36
|
import { extractCard } from "./run-summary/cards/index.js";
|
|
36
37
|
import { renderWorkflowReceipt } from "./workflow-receipt.js";
|
|
37
38
|
import { supportsRuntimeMembers, COUNCIL_RUNTIME_MEMBER_WORKFLOWS, COUNCIL_STAGE_COUNT, expandCouncilComposition } from "./council-expander.js";
|
|
39
|
+
import { RECIPE_SEAT_RULES, expandRecipeSeats, findRecipeDefaultChairmanCall, isAsyncOnlyWorkflow, isRecipeSeatWorkflow, recipeSeatPlanSeats, supportsSeatChairman, supportsSeatMembers, } from "./recipe-seats.js";
|
|
38
40
|
import { resolveWorkflowContextMode, WorkflowContextModeResolverError, } from "./context-mode-resolver.js";
|
|
39
41
|
import { resolveEffectiveChairmanCall } from "./chairman-knobs.js";
|
|
40
42
|
import { disabledFinalizerOverrideRejection, effectiveFinalizerEnabled, } from "./delegate-finalizer-policy.js";
|
|
@@ -51,17 +53,27 @@ import { restorePlanReviewRun, } from "./plan-review/resume.js";
|
|
|
51
53
|
import { PlanReviewStageError } from "./plan-review/stage-error.js";
|
|
52
54
|
import { CouncilPlanReviewErrorSchema, createPlanReviewPublicationError, inspectPlanReviewPublication, } from "./plan-review/publication.js";
|
|
53
55
|
import { validatePlanReviewCallBindings, validatePlanReviewPreparedInputPolicy, } from "./plan-review/runtime-policy.js";
|
|
54
|
-
import { ContainedFilePolicyError, readContainedRelativeFile, } from "./contained-file.js";
|
|
56
|
+
import { ContainedFileChangedError, ContainedFilePolicyError, readContainedRelativeFile, } from "./contained-file.js";
|
|
55
57
|
import { createDashboardRunReader } from "./dashboard/read-model.js";
|
|
56
58
|
import { ROSTER_NAME_PATTERN, ResolvedRosterSchema, } from "./roster-contract.js";
|
|
57
59
|
import { materializeArchitectureRoutes } from "./architecture-comparison/admission.js";
|
|
58
60
|
import { ARCHITECTURE_WORKFLOW } from "./architecture-comparison/contract.js";
|
|
59
61
|
import { inspectArchitectureComparisonRecord } from "./architecture-comparison/runtime.js";
|
|
62
|
+
import { materializeArchitectureArena } from "./architecture-arena/admission.js";
|
|
63
|
+
import { ARENA_WORKFLOW } from "./architecture-arena/contract.js";
|
|
64
|
+
import { inspectArchitectureArenaRecord } from "./architecture-arena/runtime.js";
|
|
60
65
|
import { VERIFIED_REPAIR_WORKFLOW, MAX_REPAIR_RECORD_BYTES, RepairRecordSchema, assertRepairBounded } from "./verified-repair/contract.js";
|
|
61
66
|
import { materializeVerifiedRepairRoutes, repairRoutesFromVariables } from "./verified-repair/admission.js";
|
|
67
|
+
import { PING_PONG_WORKFLOW, PP_MAX_AUDIT_REQUESTS, PP_MAX_FINDINGS_PER_ROUND, PP_MAX_NOTE_CHARS, PpDecisionInputSchema, RECIPE_DECIDE_TOOL, applyDecisionToDraft, checkDecisionCompleteness, decisionDigest, nextPhaseForDecision, projectRecipeStatusBlock, terminalStopDraft, } from "./ping-pong/contract.js";
|
|
68
|
+
import { RecipeStateCapacityError, isSidecarRecipeWorkflow, readRecipeState, recipeSidecarPresence, } from "./ping-pong/sidecar.js";
|
|
69
|
+
import { applyPingPongContextRebase, assertPingPongContextBaseline, materializePingPong, PP_IMPLEMENTER_SEAT, pingPongContextBaselinePaths, planPingPongContextRebase, withPingPongAdmissionFacts, } from "./ping-pong/admission.js";
|
|
70
|
+
import { PingPongRuntime } from "./ping-pong/runtime.js";
|
|
71
|
+
import { assertRecipeHostAvailable, isRootOnlyWorkflow } from "./recipe-host.js";
|
|
62
72
|
import { VerifiedRepairRuntime } from "./verified-repair/runtime.js";
|
|
63
73
|
import { inspectVerifiedRepairRecord } from "./verified-repair/result.js";
|
|
64
74
|
import { readWorkflowVerification } from "./workflow-verification.js";
|
|
75
|
+
import { readSessionLogGeneration } from "./dashboard/session-log-identity.js";
|
|
76
|
+
import { WorkflowCompletionRegistry, inspectPublication, persistedIdentityFailure, WORKFLOW_WAIT_BUDGET_MS, } from "./workflow-completion.js";
|
|
65
77
|
async function inspectLegacyWorkflowSessionLogGeneration(runDir, runId) {
|
|
66
78
|
try {
|
|
67
79
|
const result = await createDashboardRunReader().inspectGeneration?.(dirname(runDir), runId);
|
|
@@ -104,6 +116,7 @@ function createPreflightOnlyBackend(advertisedCliNames) {
|
|
|
104
116
|
// Admission control
|
|
105
117
|
// ---------------------------------------------------------------------------
|
|
106
118
|
const activeRuns = new Map();
|
|
119
|
+
const completions = new WorkflowCompletionRegistry();
|
|
107
120
|
/**
|
|
108
121
|
* Number of workflow tool handlers currently executing in the standalone
|
|
109
122
|
* registration path. This includes non-run tools such as status/list/cancel;
|
|
@@ -173,6 +186,9 @@ function releaseMutex(runId) {
|
|
|
173
186
|
/** Own setup before its first await, and keep that ownership through cleanup. */
|
|
174
187
|
function acquireWorkflowRun(runId, options, requestSignal) {
|
|
175
188
|
acquireMutex(runId, options);
|
|
189
|
+
// Bound lazily: a request rejected before it owns state never becomes an
|
|
190
|
+
// execution, so it cannot displace a settled one or consume a retained slot.
|
|
191
|
+
const owner = completions.owner(runId, getRunStateDir(runId));
|
|
176
192
|
const controller = new AbortController();
|
|
177
193
|
const signal = requestSignal === undefined
|
|
178
194
|
? controller.signal
|
|
@@ -201,6 +217,15 @@ function acquireWorkflowRun(runId, options, requestSignal) {
|
|
|
201
217
|
if (requestSignal === undefined)
|
|
202
218
|
cancelRegistry.set(runId, controller);
|
|
203
219
|
return {
|
|
220
|
+
get executionId() { return owner.entry?.executionId; },
|
|
221
|
+
bindStore: async (store) => {
|
|
222
|
+
// Register first, so a pin on the previous execution already fails as
|
|
223
|
+
// identity_changed while this execution's id is being persisted.
|
|
224
|
+
const entry = owner.bind(store);
|
|
225
|
+
await store.bindExecution(entry.executionId);
|
|
226
|
+
completions.markStamped(entry);
|
|
227
|
+
return entry.executionId;
|
|
228
|
+
},
|
|
204
229
|
signal,
|
|
205
230
|
throwIfCancelled: () => {
|
|
206
231
|
if (signal.aborted)
|
|
@@ -215,6 +240,14 @@ function acquireWorkflowRun(runId, options, requestSignal) {
|
|
|
215
240
|
catch (err) {
|
|
216
241
|
logger.warn({ err }, "backend.terminate() failed during cleanup");
|
|
217
242
|
}
|
|
243
|
+
try {
|
|
244
|
+
await store?.flush?.();
|
|
245
|
+
if (owner.entry !== undefined)
|
|
246
|
+
await completions.recordPublication(owner.entry);
|
|
247
|
+
}
|
|
248
|
+
catch (err) {
|
|
249
|
+
logger.warn({ err }, "workflow publication identity unavailable during cleanup");
|
|
250
|
+
}
|
|
218
251
|
try {
|
|
219
252
|
await store?.close();
|
|
220
253
|
}
|
|
@@ -226,6 +259,8 @@ function acquireWorkflowRun(runId, options, requestSignal) {
|
|
|
226
259
|
cancelRegistry.delete(runId);
|
|
227
260
|
releaseMutex(runId);
|
|
228
261
|
shutdownCoordinator.unregister(handle);
|
|
262
|
+
if (owner.entry !== undefined)
|
|
263
|
+
completions.settle(owner.entry);
|
|
229
264
|
complete();
|
|
230
265
|
}
|
|
231
266
|
},
|
|
@@ -240,6 +275,442 @@ async function markWorkflowCancelled(store) {
|
|
|
240
275
|
logger.warn({ err }, "markCancelled during cancellation handling failed");
|
|
241
276
|
}
|
|
242
277
|
}
|
|
278
|
+
// ---------------------------------------------------------------------------
|
|
279
|
+
// Recipe control plane (ping-pong; CONTRACTS 0-2, 0-7)
|
|
280
|
+
// ---------------------------------------------------------------------------
|
|
281
|
+
/**
|
|
282
|
+
* Run-ID recycling guard (CONTRACTS 0-7): a start may not name an existing
|
|
283
|
+
* recipe run (a pause is terminal `succeeded`, which a blocking start would
|
|
284
|
+
* otherwise recycle), and a worktree recipe start may not reuse an existing
|
|
285
|
+
* `${CLINKX_HOME}/workspaces/<run_id>`. Pre-mutex and pre-state.
|
|
286
|
+
*/
|
|
287
|
+
async function assertRunIdNotRecipeRun(runId, workflow, options) {
|
|
288
|
+
let existing = null;
|
|
289
|
+
try {
|
|
290
|
+
existing = await readRunStateForStatus(runId);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
// Unreadable state: the sidecar probe below still decides recipe-ness.
|
|
294
|
+
}
|
|
295
|
+
if (isSidecarRecipeWorkflow(existing?.state.workflowName) ||
|
|
296
|
+
await recipeSidecarPresence(getRunStateDir(runId)) === "present") {
|
|
297
|
+
throw new McpError(ErrorCode.InvalidParams, `run_id ${runId} names an existing recipe run; recipe run ids are never recycled. Use a new run_id.`);
|
|
298
|
+
}
|
|
299
|
+
// Host availability itself (1-10, assertRecipeHostAvailable) is the recipe
|
|
300
|
+
// admission's check; without a host there are no workspaces to collide with.
|
|
301
|
+
if (isSidecarRecipeWorkflow(workflow) && options.recipeHost !== undefined) {
|
|
302
|
+
await options.recipeHost.assertRunWorkspacesAbsent(runId);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Pre-state host admission for ping-pong (1-8..1-10, 3-12): workspace grant,
|
|
307
|
+
* baseline = HEAD of the workflows workspace root (uncommitted changes are
|
|
308
|
+
* excluded and disclosed), acceptance manifests present, context anchors
|
|
309
|
+
* inside the repository and present at the baseline (D-B), then the
|
|
310
|
+
* exclusive workspace reservation last. The reserved run dir names the
|
|
311
|
+
* implementer worktree, onto which `cb_roots`/`cb_focus_paths` are rebased;
|
|
312
|
+
* nothing stats it here (it exists only after `initialize`). Every failure
|
|
313
|
+
* is -32602 with nothing persisted.
|
|
314
|
+
*/
|
|
315
|
+
async function admitPingPongHost(host, runId, variables, settings, signal) {
|
|
316
|
+
try {
|
|
317
|
+
await host.assertWorkspaceGrant();
|
|
318
|
+
await host.assertRunWorkspacesAbsent(runId);
|
|
319
|
+
const repoRoot = resolveWorkspaceRoot();
|
|
320
|
+
const baselineCommit = await host.resolveBaseline(repoRoot, "HEAD", signal);
|
|
321
|
+
// The worktree is created from the pinned commit, not the checkout: an
|
|
322
|
+
// untracked or uncommitted acceptance input would vanish there.
|
|
323
|
+
if (host.assertBaselineFiles === undefined) {
|
|
324
|
+
throw new Error("the recipe host cannot verify acceptance inputs in the baseline commit");
|
|
325
|
+
}
|
|
326
|
+
await host.assertBaselineFiles(repoRoot, baselineCommit, [
|
|
327
|
+
settings.acceptanceManifest,
|
|
328
|
+
...(settings.copyPreparationManifest !== undefined ? [settings.copyPreparationManifest] : []),
|
|
329
|
+
...settings.acceptanceInputs,
|
|
330
|
+
], signal);
|
|
331
|
+
const uncommittedChangesExcluded = await host.hasUncommittedChanges?.(repoRoot, signal) ?? false;
|
|
332
|
+
if (host.repositoryToplevel === undefined || host.describeBaselinePaths === undefined) {
|
|
333
|
+
throw new Error("the recipe host cannot root context preflight in the baseline worktree");
|
|
334
|
+
}
|
|
335
|
+
const contextPlan = planPingPongContextRebase(variables, {
|
|
336
|
+
toplevel: await host.repositoryToplevel(repoRoot, signal),
|
|
337
|
+
workspaceRoot: repoRoot,
|
|
338
|
+
cwd: process.cwd(),
|
|
339
|
+
});
|
|
340
|
+
assertPingPongContextBaseline(contextPlan, await host.describeBaselinePaths(repoRoot, baselineCommit, pingPongContextBaselinePaths(contextPlan), signal), baselineCommit);
|
|
341
|
+
const now = new Date();
|
|
342
|
+
const reservedRunDir = await host.reserveRunWorkspaces(runId);
|
|
343
|
+
try {
|
|
344
|
+
// createWorkspace names the seat `<reserved run dir>/implementer`; the
|
|
345
|
+
// runtime refuses to start if the created path differs.
|
|
346
|
+
const rebased = applyPingPongContextRebase(variables, contextPlan, join(reservedRunDir, PP_IMPLEMENTER_SEAT));
|
|
347
|
+
return withPingPongAdmissionFacts(rebased.variables, settings, {
|
|
348
|
+
repoRoot,
|
|
349
|
+
baselineCommit,
|
|
350
|
+
uncommittedChangesExcluded,
|
|
351
|
+
now,
|
|
352
|
+
contextRoots: rebased.contextRoots,
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
await host.releaseUnadmittedRun?.(runId)?.catch((releaseError) => {
|
|
357
|
+
logger.warn({ err: releaseError, runId }, "failed to release an unadmitted recipe workspace reservation");
|
|
358
|
+
});
|
|
359
|
+
throw error;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
if (error instanceof McpError)
|
|
364
|
+
throw error;
|
|
365
|
+
throw new McpError(ErrorCode.InvalidParams, `ping-pong admission failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
function recipeControlError(code, reason, message, data = {}) {
|
|
369
|
+
return new McpError(code, `${reason}: ${message}`, { reason, ...data });
|
|
370
|
+
}
|
|
371
|
+
function decisionReceiptText(receipt) {
|
|
372
|
+
return { content: [{ type: "text", text: JSON.stringify(receipt) }] };
|
|
373
|
+
}
|
|
374
|
+
function findDecisionRecord(state, executionId, revision) {
|
|
375
|
+
return state.decisions.find((record) => record.source_execution_id === executionId && record.source_revision === revision);
|
|
376
|
+
}
|
|
377
|
+
/** Replay rule (0-2 step 2): same digest -> stored receipt, different digest -> conflict. */
|
|
378
|
+
function replayOrConflict(record, digest) {
|
|
379
|
+
if (record === undefined)
|
|
380
|
+
return undefined;
|
|
381
|
+
if (record.decision_digest !== digest) {
|
|
382
|
+
throw recipeControlError(ErrorCode.InvalidParams, "conflicting_decision", `a different decision was already applied to execution ${record.source_execution_id} revision ${record.source_revision}`, { applied_receipt: record.receipt });
|
|
383
|
+
}
|
|
384
|
+
return decisionReceiptText({ ...record.receipt, replayed: true });
|
|
385
|
+
}
|
|
386
|
+
function recipeReopenToMcpError(error, runId) {
|
|
387
|
+
switch (error.reason) {
|
|
388
|
+
case "run_busy":
|
|
389
|
+
return recipeControlError(ErrorCode.InvalidRequest, "run_busy", `run ${runId} is active or settling; retry later`, { retryable: true });
|
|
390
|
+
case "not_found":
|
|
391
|
+
return recipeControlError(ErrorCode.InvalidParams, "run_not_found", `run ${runId} not found`);
|
|
392
|
+
case "not_recipe":
|
|
393
|
+
return recipeControlError(ErrorCode.InvalidParams, "not_recipe_run", `run ${runId} is not a ${PING_PONG_WORKFLOW} run`);
|
|
394
|
+
case "not_awaiting_decision":
|
|
395
|
+
return recipeControlError(ErrorCode.InvalidParams, "not_awaiting_decision", error.message, {
|
|
396
|
+
...(error.current !== undefined
|
|
397
|
+
? { current_phase: error.current.phase, current_revision: error.current.revision, current_status: error.current.status }
|
|
398
|
+
: {}),
|
|
399
|
+
});
|
|
400
|
+
case "integrity":
|
|
401
|
+
return recipeControlError(ErrorCode.InvalidParams, "recipe_state_unavailable", error.message);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/** Per-run mutex + async cap, mapping a same-run owner to the retryable `run_busy`. */
|
|
405
|
+
function acquireRecipeControlRun(runId, options) {
|
|
406
|
+
if (activeRuns.has(runId)) {
|
|
407
|
+
throw recipeControlError(ErrorCode.InvalidRequest, "run_busy", `run ${runId} is active or settling; retry later`, { retryable: true });
|
|
408
|
+
}
|
|
409
|
+
// Cap full and shutdown keep their existing fail-fast InvalidRequest.
|
|
410
|
+
return acquireWorkflowRun(runId, options);
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* 0-2 step 5 for a decision whose next phase is `stopped`, or a deadline
|
|
414
|
+
* expiry: one terminal sidecar write carrying the decision record, then the
|
|
415
|
+
* matching terminal state.json, in one critical section.
|
|
416
|
+
*/
|
|
417
|
+
async function commitTerminalDecision(store, source, input, newExecutionId, draft, stopReason) {
|
|
418
|
+
const record = buildDecisionRecord(source, input, newExecutionId, "stopped", stopReason);
|
|
419
|
+
const committed = await store.commitRecipeTerminal({ ...draft, decisions: [...source.decisions, record] });
|
|
420
|
+
return { receipt: record.receipt, record, committed };
|
|
421
|
+
}
|
|
422
|
+
function buildDecisionRecord(source, input, newExecutionId, nextPhase, stopReason) {
|
|
423
|
+
const newRevision = source.revision + 1;
|
|
424
|
+
const receipt = {
|
|
425
|
+
run_id: source.run_id,
|
|
426
|
+
execution_id: newExecutionId,
|
|
427
|
+
revision: newRevision,
|
|
428
|
+
phase: nextPhase,
|
|
429
|
+
...(nextPhase === "stopped" ? { outcome: "stopped", stop_reason: stopReason } : {}),
|
|
430
|
+
replayed: false,
|
|
431
|
+
};
|
|
432
|
+
return {
|
|
433
|
+
source_execution_id: input.executionId,
|
|
434
|
+
source_revision: input.revision,
|
|
435
|
+
decision_digest: input.digest,
|
|
436
|
+
decision: input.decision,
|
|
437
|
+
new_execution_id: newExecutionId,
|
|
438
|
+
new_revision: newRevision,
|
|
439
|
+
next_phase: nextPhase,
|
|
440
|
+
...(stopReason !== undefined ? { stop_reason: stopReason } : {}),
|
|
441
|
+
recorded_at: new Date().toISOString(),
|
|
442
|
+
receipt,
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* `workflow_recipe_decide` (CONTRACTS 0-2). Processing order, first failure
|
|
447
|
+
* wins, nothing written before step 5:
|
|
448
|
+
* 1. structural validation -> -32602 (plus the host/runtime capability);
|
|
449
|
+
* 2. replay lookup by (run_id, execution_id, revision) BEFORE any phase,
|
|
450
|
+
* revision, deadline or admission check;
|
|
451
|
+
* 3. admission through acquireWorkflowRun (same-run owner -> retryable
|
|
452
|
+
* InvalidRequest run_busy; cap full -> InvalidRequest);
|
|
453
|
+
* 4. under run.lock (reopen): replay re-check, stale/not-awaiting, then
|
|
454
|
+
* the wall deadline (a late decision, complete or not, is terminalized
|
|
455
|
+
* as a control execution), then completeness;
|
|
456
|
+
* 5. reopen as a new execution (state running, new id bound and persisted),
|
|
457
|
+
* ONE sidecar write with the decision record, then hand off to the
|
|
458
|
+
* runtime (detached) and return the receipt.
|
|
459
|
+
*/
|
|
460
|
+
async function executeRecipeDecide(options, args) {
|
|
461
|
+
// 1. Structural.
|
|
462
|
+
const parsed = PpDecisionInputSchema.safeParse(args);
|
|
463
|
+
if (!parsed.success) {
|
|
464
|
+
throw recipeControlError(ErrorCode.InvalidParams, "invalid_decision", parsed.error.issues.slice(0, 5).map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; "));
|
|
465
|
+
}
|
|
466
|
+
const { run_id: runId, execution_id: executionId, revision, decision } = parsed.data;
|
|
467
|
+
if (options.recipeHost === undefined) {
|
|
468
|
+
throw recipeControlError(ErrorCode.InvalidParams, "recipe_host_unavailable", `${RECIPE_DECIDE_TOOL} requires the root recipe host; the standalone workflow server cannot run recipes`);
|
|
469
|
+
}
|
|
470
|
+
const runtime = options.pingPongRuntime;
|
|
471
|
+
if (runtime === undefined) {
|
|
472
|
+
throw recipeControlError(ErrorCode.InvalidParams, "recipe_runtime_unavailable", `${RECIPE_DECIDE_TOOL} requires the ${PING_PONG_WORKFLOW} runtime, which this server does not provide`);
|
|
473
|
+
}
|
|
474
|
+
const digest = decisionDigest(decision);
|
|
475
|
+
const decisionInput = { executionId, revision, decision, digest };
|
|
476
|
+
// 2. Replay lookup: no slot, no lock, no write.
|
|
477
|
+
const runDir = getRunStateDir(runId);
|
|
478
|
+
const unlocked = await readRecipeState(runDir);
|
|
479
|
+
if (unlocked.kind === "read") {
|
|
480
|
+
const replay = replayOrConflict(findDecisionRecord(unlocked.state, executionId, revision), digest);
|
|
481
|
+
if (replay !== undefined)
|
|
482
|
+
return replay;
|
|
483
|
+
}
|
|
484
|
+
// 3. Admission.
|
|
485
|
+
const ownership = acquireRecipeControlRun(runId, options);
|
|
486
|
+
let store;
|
|
487
|
+
let handedOff = false;
|
|
488
|
+
try {
|
|
489
|
+
// 4. Locked validation.
|
|
490
|
+
try {
|
|
491
|
+
store = await WorkflowStateStore.reopen({ runId, fileWriter: options.fileWriter });
|
|
492
|
+
}
|
|
493
|
+
catch (error) {
|
|
494
|
+
if (error instanceof RecipeReopenError) {
|
|
495
|
+
// A decision applied by another process after our unlocked read.
|
|
496
|
+
if (error.reason === "not_awaiting_decision") {
|
|
497
|
+
const reread = await readRecipeState(runDir);
|
|
498
|
+
if (reread.kind === "read") {
|
|
499
|
+
const replay = replayOrConflict(findDecisionRecord(reread.state, executionId, revision), digest);
|
|
500
|
+
if (replay !== undefined)
|
|
501
|
+
return replay;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
throw recipeReopenToMcpError(error, runId);
|
|
505
|
+
}
|
|
506
|
+
throw error;
|
|
507
|
+
}
|
|
508
|
+
const source = store.recipeState;
|
|
509
|
+
const replay = replayOrConflict(findDecisionRecord(source, executionId, revision), digest);
|
|
510
|
+
if (replay !== undefined)
|
|
511
|
+
return replay;
|
|
512
|
+
const published = store.runState.executionId;
|
|
513
|
+
if (published !== executionId || source.execution_id !== executionId || source.revision !== revision) {
|
|
514
|
+
throw recipeControlError(ErrorCode.InvalidParams, "stale_decision", `decision targets execution ${executionId} revision ${revision}; the run awaits execution ${published ?? "(unbound)"} revision ${source.revision}`, { current_revision: source.revision, ...(published !== undefined ? { current_execution_id: published } : {}) });
|
|
515
|
+
}
|
|
516
|
+
if (source.unresolved_operations > 0) {
|
|
517
|
+
// inv. 23 defense in depth: a pause is only published with every seat
|
|
518
|
+
// exit confirmed; a checkpoint with unresolved operations never starts
|
|
519
|
+
// another writer.
|
|
520
|
+
throw recipeControlError(ErrorCode.InvalidParams, "recovery_required", `run ${runId} records ${source.unresolved_operations} unresolved operation(s); no decision can start another round. Cancel the run and inspect its worktrees.`, { unresolved_operations: source.unresolved_operations });
|
|
521
|
+
}
|
|
522
|
+
const deadlineExpired = Date.parse(source.deadline_at) <= Date.now();
|
|
523
|
+
const completeness = deadlineExpired ? { ok: true } : checkDecisionCompleteness(source.pending_findings, decision);
|
|
524
|
+
if (!completeness.ok) {
|
|
525
|
+
throw recipeControlError(ErrorCode.InvalidParams, "decision_incomplete", (decision.stop
|
|
526
|
+
? `a stop may list each pending finding id at most once across admit/reject`
|
|
527
|
+
: `every pending finding id must appear exactly once across admit/reject`) +
|
|
528
|
+
(completeness.unknown.length > 0 ? `; unknown: ${completeness.unknown.join(", ")}` : "") +
|
|
529
|
+
(completeness.duplicate.length > 0 ? `; duplicate: ${completeness.duplicate.join(", ")}` : "") +
|
|
530
|
+
(completeness.missing.length > 0 ? `; missing: ${completeness.missing.join(", ")}` : ""), { unknown: completeness.unknown, duplicate: completeness.duplicate, missing: completeness.missing });
|
|
531
|
+
}
|
|
532
|
+
// 5. Commit as a new execution.
|
|
533
|
+
await store.beginRecipeExecution();
|
|
534
|
+
const newExecutionId = await ownership.bindStore(store);
|
|
535
|
+
let commit;
|
|
536
|
+
if (deadlineExpired) {
|
|
537
|
+
commit = await commitTerminalDecision(store, source, decisionInput, newExecutionId, terminalStopDraft(source, "deadline_exceeded"), "deadline_exceeded");
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
const transition = nextPhaseForDecision(source, decision);
|
|
541
|
+
const draft = applyDecisionToDraft(source, decision, transition);
|
|
542
|
+
if (transition.phase === "stopped") {
|
|
543
|
+
commit = await commitTerminalDecision(store, source, decisionInput, newExecutionId, draft, transition.stopReason);
|
|
544
|
+
}
|
|
545
|
+
else {
|
|
546
|
+
const record = buildDecisionRecord(source, decisionInput, newExecutionId, transition.phase);
|
|
547
|
+
try {
|
|
548
|
+
const committed = await store.commitRecipeState({ ...draft, decisions: [...source.decisions, record] });
|
|
549
|
+
commit = { receipt: record.receipt, record, committed };
|
|
550
|
+
}
|
|
551
|
+
catch (error) {
|
|
552
|
+
if (!(error instanceof RecipeStateCapacityError))
|
|
553
|
+
throw error;
|
|
554
|
+
// 0-4: no room for another non-terminal write; the terminal reserve
|
|
555
|
+
// still holds the decision record.
|
|
556
|
+
commit = await commitTerminalDecision(store, source, decisionInput, newExecutionId, terminalStopDraft(source, "evidence_capacity"), "evidence_capacity");
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (commit.committed.outcome === undefined) {
|
|
561
|
+
// Hand off: the detached continuation owns the fence from here.
|
|
562
|
+
handedOff = true;
|
|
563
|
+
const ownedStore = store;
|
|
564
|
+
const continuation = {
|
|
565
|
+
runId,
|
|
566
|
+
runDir: ownedStore.runDir,
|
|
567
|
+
store: ownedStore,
|
|
568
|
+
executionId: newExecutionId,
|
|
569
|
+
recipeState: commit.committed,
|
|
570
|
+
decision: commit.record,
|
|
571
|
+
signal: ownership.signal,
|
|
572
|
+
setBackend: ownership.setBackend,
|
|
573
|
+
createBackend: options.createBackend,
|
|
574
|
+
};
|
|
575
|
+
void (async () => {
|
|
576
|
+
let failure;
|
|
577
|
+
try {
|
|
578
|
+
await runtime.continueAfterDecision(continuation);
|
|
579
|
+
}
|
|
580
|
+
catch (error) {
|
|
581
|
+
failure = error;
|
|
582
|
+
}
|
|
583
|
+
try {
|
|
584
|
+
await settleRecipeExecution(ownedStore, ownership.signal, failure);
|
|
585
|
+
}
|
|
586
|
+
finally {
|
|
587
|
+
await ownership.finish(ownedStore);
|
|
588
|
+
}
|
|
589
|
+
})().catch((error) => {
|
|
590
|
+
// Nothing awaits this once the receipt is returned, so an escaped
|
|
591
|
+
// settlement or cleanup rejection would otherwise be unhandled.
|
|
592
|
+
logger.error({ err: error, runId }, `${RECIPE_DECIDE_TOOL} detached continuation failed after the receipt`);
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
return decisionReceiptText(commit.receipt);
|
|
596
|
+
}
|
|
597
|
+
catch (error) {
|
|
598
|
+
// After step 5 started (state reopened), an in-process failure fails the
|
|
599
|
+
// new execution; the paused checkpoint is not restored (Recovery).
|
|
600
|
+
if (store !== undefined && !handedOff) {
|
|
601
|
+
const status = store.runState.status;
|
|
602
|
+
if (status === "running" || status === "pending") {
|
|
603
|
+
await store.markFailed(`${RECIPE_DECIDE_TOOL} failed after reopening the run: ${error instanceof Error ? error.message : String(error)}`, "permanent").catch(() => { });
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
throw error;
|
|
607
|
+
}
|
|
608
|
+
finally {
|
|
609
|
+
if (!handedOff)
|
|
610
|
+
await ownership.finish(store);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Owner-side settlement of a recipe execution whose runtime returned or threw
|
|
615
|
+
* with `state.json` still active: an aborted execution ends `cancelled`
|
|
616
|
+
* whether the runtime threw or returned normally; anything else ends
|
|
617
|
+
* `failed`. `mark*` applies D1 in one critical section: a terminal sidecar
|
|
618
|
+
* this execution already committed decides the status (so a cancel that lost
|
|
619
|
+
* the race to `qualified` settles `succeeded`), and a non-terminal one is
|
|
620
|
+
* terminalized before the state. If that sidecar record fails, state stays
|
|
621
|
+
* active and the orphaned run is recovered later.
|
|
622
|
+
*/
|
|
623
|
+
export async function settleRecipeExecution(store, signal, failure) {
|
|
624
|
+
const status = store.runState.status;
|
|
625
|
+
if (status !== "running" && status !== "pending")
|
|
626
|
+
return;
|
|
627
|
+
const cancelled = signal.aborted || failure instanceof WorkflowCancellationError;
|
|
628
|
+
if (cancelled) {
|
|
629
|
+
await markWorkflowCancelled(store);
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
const message = failure === undefined
|
|
633
|
+
? `${PING_PONG_WORKFLOW} runtime returned without a terminal state`
|
|
634
|
+
: failure instanceof Error ? failure.message : String(failure);
|
|
635
|
+
await store.markFailed(message, carriedFailureClass(failure) ?? "permanent").catch((markError) => {
|
|
636
|
+
logger.warn({ err: markError }, "markFailed after ping-pong execution failure failed");
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Paused cancel (CONTRACTS 0-7): a control execution. reopen() binds a new
|
|
641
|
+
* execution id, then sidecar `stopped(cancelled)` and state `cancelled` are
|
|
642
|
+
* written in one critical section, then the normal fence. Earlier pins see
|
|
643
|
+
* identity_changed. Returns undefined when the run is not paused after all.
|
|
644
|
+
*/
|
|
645
|
+
async function cancelPausedRecipeRun(options, runId) {
|
|
646
|
+
let ownership;
|
|
647
|
+
try {
|
|
648
|
+
ownership = acquireRecipeControlRun(runId, options);
|
|
649
|
+
}
|
|
650
|
+
catch (error) {
|
|
651
|
+
// Same-run owner, a full admission cap, or shutdown: nothing changed, and
|
|
652
|
+
// the paused run stays cancellable later.
|
|
653
|
+
if (error instanceof McpError && error.code === ErrorCode.InvalidRequest) {
|
|
654
|
+
return { run_id: runId, status: "running", cancellable: false, reason: "run_busy", retryable: true };
|
|
655
|
+
}
|
|
656
|
+
throw error;
|
|
657
|
+
}
|
|
658
|
+
let store;
|
|
659
|
+
try {
|
|
660
|
+
try {
|
|
661
|
+
store = await WorkflowStateStore.reopen({ runId, fileWriter: options.fileWriter });
|
|
662
|
+
}
|
|
663
|
+
catch (error) {
|
|
664
|
+
if (error instanceof RecipeReopenError) {
|
|
665
|
+
if (error.reason === "run_busy")
|
|
666
|
+
return { run_id: runId, status: "running", cancellable: false, reason: "run_busy", retryable: true };
|
|
667
|
+
if (error.reason === "not_awaiting_decision" || error.reason === "not_recipe")
|
|
668
|
+
return undefined;
|
|
669
|
+
}
|
|
670
|
+
throw error;
|
|
671
|
+
}
|
|
672
|
+
const source = store.recipeState;
|
|
673
|
+
await store.beginRecipeExecution();
|
|
674
|
+
const executionId = await ownership.bindStore(store);
|
|
675
|
+
await store.commitRecipeTerminal(terminalStopDraft(source, "cancelled", { outcome: "cancelled", effectsStopped: source.unresolved_operations === 0 }));
|
|
676
|
+
return { run_id: runId, status: "cancelled", execution_id: executionId };
|
|
677
|
+
}
|
|
678
|
+
catch (error) {
|
|
679
|
+
if (store !== undefined) {
|
|
680
|
+
const status = store.runState.status;
|
|
681
|
+
if (status === "running" || status === "pending")
|
|
682
|
+
await markWorkflowCancelled(store);
|
|
683
|
+
}
|
|
684
|
+
throw error;
|
|
685
|
+
}
|
|
686
|
+
finally {
|
|
687
|
+
await ownership.finish(store);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Status `recipe` block (CONTRACTS 0-7): accepted only when the sidecar's
|
|
692
|
+
* execution_id equals the projected state's executionId, re-read up to the
|
|
693
|
+
* bounded retry. Unpinned: a mismatch or unreadable sidecar omits the block.
|
|
694
|
+
* Pinned (guarded) reads fail closed through the same changed-file path as
|
|
695
|
+
* the state fingerprint.
|
|
696
|
+
*/
|
|
697
|
+
async function projectRecipeBlock(runDir, state, pinned) {
|
|
698
|
+
let last;
|
|
699
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
700
|
+
last = await readRecipeState(runDir);
|
|
701
|
+
if (last.kind === "absent")
|
|
702
|
+
return undefined;
|
|
703
|
+
if (last.kind === "read" && state.executionId !== undefined && last.state.execution_id === state.executionId) {
|
|
704
|
+
return projectRecipeStatusBlock(last.state);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
if (pinned) {
|
|
708
|
+
throw new ContainedFileChangedError(last?.kind === "invalid"
|
|
709
|
+
? "recipe sidecar is unreadable for a pinned status read"
|
|
710
|
+
: "recipe sidecar does not belong to the projected execution");
|
|
711
|
+
}
|
|
712
|
+
return undefined;
|
|
713
|
+
}
|
|
243
714
|
// Keep in sync with schema.ts model regex and ModelSchema (delegate-validate.ts).
|
|
244
715
|
const MODEL_OVERRIDE_PATTERN = /^[^\s\u0000-][^\s\u0000]*$/;
|
|
245
716
|
// Keep in sync with schema.ts effort regex and EffortSchema (delegate-validate.ts).
|
|
@@ -260,7 +731,10 @@ function parseInvocationOverride(raw, label, maxLength, pattern) {
|
|
|
260
731
|
}
|
|
261
732
|
return value;
|
|
262
733
|
}
|
|
263
|
-
export function parseMembersOverride(raw, knownCliNames) {
|
|
734
|
+
export function parseMembersOverride(raw, knownCliNames, options) {
|
|
735
|
+
const stanceRequiredFromIndex = options?.stanceRequiredFromIndex === undefined
|
|
736
|
+
? 3
|
|
737
|
+
: options.stanceRequiredFromIndex;
|
|
264
738
|
if (raw == null)
|
|
265
739
|
return undefined;
|
|
266
740
|
if (!Array.isArray(raw)) {
|
|
@@ -315,8 +789,8 @@ export function parseMembersOverride(raw, knownCliNames) {
|
|
|
315
789
|
}
|
|
316
790
|
entry.stance = collapsed;
|
|
317
791
|
}
|
|
318
|
-
else if (i >=
|
|
319
|
-
throw new McpError(ErrorCode.InvalidParams,
|
|
792
|
+
else if (stanceRequiredFromIndex !== null && i >= stanceRequiredFromIndex) {
|
|
793
|
+
throw new McpError(ErrorCode.InvalidParams, `stance is required for members at index ${stanceRequiredFromIndex} and above`);
|
|
320
794
|
}
|
|
321
795
|
if (obj["model"] !== undefined) {
|
|
322
796
|
entry.model = parseInvocationOverride(obj["model"], `members[${i}].model`, 128, MODEL_OVERRIDE_PATTERN);
|
|
@@ -366,7 +840,7 @@ function invocationOverrideKnobs(value) {
|
|
|
366
840
|
...(value.effort === undefined ? {} : { effort: value.effort }),
|
|
367
841
|
};
|
|
368
842
|
}
|
|
369
|
-
function validateInvocationOverridesAtAdmission(workflow, definition, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort, initialContextPolicy, resolvedVariables, validate, callerDelegateRaw) {
|
|
843
|
+
function validateInvocationOverridesAtAdmission(workflow, definition, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort, initialContextPolicy, resolvedVariables, validate, callerDelegateRaw, recipeSeatPlan) {
|
|
370
844
|
// Structural E5: independent of the optional adapter-capability hook so the
|
|
371
845
|
// standalone server rejects a disabled-finalizer override too. No-op when
|
|
372
846
|
// the policy has no enabled delegate (including the no-runner `off` default).
|
|
@@ -386,12 +860,17 @@ function validateInvocationOverridesAtAdmission(workflow, definition, parsedMemb
|
|
|
386
860
|
const staticChairman = councilWorkflow
|
|
387
861
|
? definition.stages[3]?.calls[0]
|
|
388
862
|
: undefined;
|
|
863
|
+
// A recipe's default chairman call is validated through the effective
|
|
864
|
+
// chairman seat in the plan, never with its raw static pins.
|
|
865
|
+
const recipeDefaultChairman = recipeSeatPlan !== undefined
|
|
866
|
+
? findRecipeDefaultChairmanCall(definition)
|
|
867
|
+
: undefined;
|
|
389
868
|
for (const [stageIndex, stage] of definition.stages.entries()) {
|
|
390
869
|
for (const call of stage.calls) {
|
|
391
|
-
if (call === staticChairman) {
|
|
870
|
+
if (call === staticChairman || call === recipeDefaultChairman) {
|
|
392
871
|
continue;
|
|
393
872
|
}
|
|
394
|
-
if (parsedMembers !== undefined && stageIndex < 2) {
|
|
873
|
+
if (councilWorkflow && parsedMembers !== undefined && stageIndex < 2) {
|
|
395
874
|
continue;
|
|
396
875
|
}
|
|
397
876
|
const knobs = invocationOverrideKnobs(call);
|
|
@@ -408,6 +887,15 @@ function validateInvocationOverridesAtAdmission(workflow, definition, parsedMemb
|
|
|
408
887
|
}
|
|
409
888
|
}
|
|
410
889
|
}
|
|
890
|
+
if (recipeSeatPlan !== undefined) {
|
|
891
|
+
const recipeChairman = recipeSeatPlanSeats(recipeSeatPlan).chairman;
|
|
892
|
+
if (recipeChairman !== undefined) {
|
|
893
|
+
const knobs = invocationOverrideKnobs(recipeChairman);
|
|
894
|
+
if (knobs !== undefined) {
|
|
895
|
+
validate(recipeChairman.cli_name, knobs);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
}
|
|
411
899
|
if (councilWorkflow && staticChairman !== undefined) {
|
|
412
900
|
const effectiveChairman = resolveEffectiveChairmanCall({
|
|
413
901
|
staticCall: staticChairman,
|
|
@@ -1124,18 +1612,22 @@ function appendDuplicateReplayBlock(content, store) {
|
|
|
1124
1612
|
});
|
|
1125
1613
|
}
|
|
1126
1614
|
/**
|
|
1127
|
-
* Trailing additive
|
|
1128
|
-
* roster
|
|
1129
|
-
*
|
|
1130
|
-
*
|
|
1615
|
+
* Trailing additive identity block, always last: the admission-time
|
|
1616
|
+
* requested-value roster (omitted for non-council, plan-review, or pre-roster
|
|
1617
|
+
* state) and the execution_id bound to this request (omitted when the request
|
|
1618
|
+
* was rejected before it owned state). No block when neither is present.
|
|
1619
|
+
* Defensive optional access: partial store mocks may omit runState.
|
|
1131
1620
|
*/
|
|
1132
|
-
function
|
|
1621
|
+
function appendIdentityBlock(content, store, executionId) {
|
|
1133
1622
|
const resolvedRoster = store?.runState?.resolvedRoster;
|
|
1134
|
-
if (resolvedRoster === undefined)
|
|
1623
|
+
if (resolvedRoster === undefined && executionId === undefined)
|
|
1135
1624
|
return;
|
|
1136
1625
|
content.push({
|
|
1137
1626
|
type: "text",
|
|
1138
|
-
text: JSON.stringify({
|
|
1627
|
+
text: JSON.stringify({
|
|
1628
|
+
...(resolvedRoster !== undefined ? { resolved_roster: resolvedRoster } : {}),
|
|
1629
|
+
...(executionId !== undefined ? { execution_id: executionId } : {}),
|
|
1630
|
+
}),
|
|
1139
1631
|
});
|
|
1140
1632
|
}
|
|
1141
1633
|
// ---------------------------------------------------------------------------
|
|
@@ -1346,6 +1838,7 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1346
1838
|
catch {
|
|
1347
1839
|
throw new McpError(ErrorCode.InvalidParams, `Invalid run_id "${runId}". Must match [A-Za-z0-9_-]{1,64}.`);
|
|
1348
1840
|
}
|
|
1841
|
+
await assertRunIdNotRecipeRun(runId, workflow, options);
|
|
1349
1842
|
const validatorRegistry = createValidatorRegistry();
|
|
1350
1843
|
let loaded = loadWorkflow(workflow, {
|
|
1351
1844
|
templatesRoot: options.templatesRoot ?? getTemplatesPath(),
|
|
@@ -1376,6 +1869,8 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1376
1869
|
let initialContextPolicy;
|
|
1377
1870
|
let planReviewAdmission;
|
|
1378
1871
|
let admittedRosterName;
|
|
1872
|
+
let recipeSeatPlan;
|
|
1873
|
+
let pingPongSettings;
|
|
1379
1874
|
try {
|
|
1380
1875
|
let membersRaw = args["members"];
|
|
1381
1876
|
let chairmanRaw = args["chairman"];
|
|
@@ -1391,25 +1886,54 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1391
1886
|
chairmanEffortRaw = applied.chairmanEffortRaw;
|
|
1392
1887
|
suppliedVariables = applied.variables;
|
|
1393
1888
|
}
|
|
1394
|
-
parsedMembers = parseMembersOverride(membersRaw, knownCliNames);
|
|
1889
|
+
parsedMembers = parseMembersOverride(membersRaw, knownCliNames, isRecipeSeatWorkflow(workflow) ? { stanceRequiredFromIndex: null } : undefined);
|
|
1395
1890
|
parsedChairman = parseChairmanOverride(chairmanRaw, knownCliNames);
|
|
1396
1891
|
parsedChairmanModel = parseChairmanModelOverride(chairmanModelRaw);
|
|
1397
1892
|
parsedChairmanEffort = parseChairmanEffortOverride(chairmanEffortRaw);
|
|
1398
|
-
if (parsedMembers != null && !
|
|
1893
|
+
if (parsedMembers != null && !supportsSeatMembers(workflow)) {
|
|
1399
1894
|
throw new McpError(ErrorCode.InvalidParams, `members parameter is not supported for workflow "${workflow}"`);
|
|
1400
1895
|
}
|
|
1401
|
-
if (parsedChairman != null && !
|
|
1896
|
+
if (parsedChairman != null && !supportsSeatChairman(workflow)) {
|
|
1402
1897
|
throw new McpError(ErrorCode.InvalidParams, `chairman parameter is not supported for workflow "${workflow}"`);
|
|
1403
1898
|
}
|
|
1404
|
-
if (parsedChairmanModel != null && !
|
|
1899
|
+
if (parsedChairmanModel != null && !supportsSeatChairman(workflow)) {
|
|
1405
1900
|
throw new McpError(ErrorCode.InvalidParams, `chairman_model parameter is not supported for workflow "${workflow}"`);
|
|
1406
1901
|
}
|
|
1407
|
-
if (parsedChairmanEffort != null && !
|
|
1902
|
+
if (parsedChairmanEffort != null && !supportsSeatChairman(workflow)) {
|
|
1408
1903
|
throw new McpError(ErrorCode.InvalidParams, `chairman_effort parameter is not supported for workflow "${workflow}"`);
|
|
1409
1904
|
}
|
|
1905
|
+
if (isRecipeSeatWorkflow(workflow)) {
|
|
1906
|
+
// D-R4 seat mapping; throws -32602 before any run state exists.
|
|
1907
|
+
recipeSeatPlan = recipeSeatPlanForAdmission(workflow, loaded.normalized, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort);
|
|
1908
|
+
}
|
|
1410
1909
|
resolvedVariables = validateVariables(suppliedVariables, loaded.definition.variables);
|
|
1910
|
+
// Without an injected runner no preflight can append bundle copies, so
|
|
1911
|
+
// the freeze cap needs no reserved slots.
|
|
1912
|
+
const freezeAdmission = { preflightAvailable: options.contextBuilderRunner != null };
|
|
1411
1913
|
try {
|
|
1412
|
-
loaded = { ...loaded, normalized: materializeArchitectureRoutes(loaded.normalized, resolvedVariables, options.planReviewAvailableCliNames ?? options.availableCliNames, options.validateInvocationOverrides) };
|
|
1914
|
+
loaded = { ...loaded, normalized: materializeArchitectureRoutes(loaded.normalized, resolvedVariables, options.planReviewAvailableCliNames ?? options.availableCliNames, options.validateInvocationOverrides, freezeAdmission) };
|
|
1915
|
+
// Enforce exactly what list_workflows advertises (root_only / async_only),
|
|
1916
|
+
// for every recipe that declares it, not only ping-pong.
|
|
1917
|
+
if (isRootOnlyWorkflow(workflow))
|
|
1918
|
+
assertRecipeHostAvailable(workflow, options);
|
|
1919
|
+
if (isAsyncOnlyWorkflow(workflow) && args["async"] !== true) {
|
|
1920
|
+
throw new Error(`${workflow} requires async:true (it pauses for workflow_recipe_decide)`);
|
|
1921
|
+
}
|
|
1922
|
+
if (workflow === ARENA_WORKFLOW) {
|
|
1923
|
+
// 2-3/2-4: n author calls and the judge route are materialized from
|
|
1924
|
+
// the admitted seat plan before any state; the plan (stance included)
|
|
1925
|
+
// rides in a server-owned variable so resume never re-parses input.
|
|
1926
|
+
const arena = materializeArchitectureArena(loaded.normalized, resolvedVariables, recipeSeatPlan, freezeAdmission);
|
|
1927
|
+
loaded = { ...loaded, normalized: arena.definition };
|
|
1928
|
+
resolvedVariables = arena.variables;
|
|
1929
|
+
}
|
|
1930
|
+
if (workflow === PING_PONG_WORKFLOW) {
|
|
1931
|
+
// 3-1/3-12: fixed (n,k) topology and seat plan before any state.
|
|
1932
|
+
const pingPong = materializePingPong(loaded.normalized, resolvedVariables, recipeSeatPlan?.workflow === PING_PONG_WORKFLOW ? recipeSeatPlan : undefined);
|
|
1933
|
+
loaded = { ...loaded, normalized: pingPong.definition };
|
|
1934
|
+
resolvedVariables = pingPong.variables;
|
|
1935
|
+
pingPongSettings = pingPong.settings;
|
|
1936
|
+
}
|
|
1413
1937
|
loaded = { ...loaded, normalized: materializeVerifiedRepairRoutes(loaded.normalized, resolvedVariables, options.planReviewAvailableCliNames ?? options.availableCliNames, options.validateInvocationOverrides) };
|
|
1414
1938
|
if (workflow === VERIFIED_REPAIR_WORKFLOW && options.verifiedRepairHost === undefined) {
|
|
1415
1939
|
throw new Error("verified-repair requires the root host capability");
|
|
@@ -1468,7 +1992,7 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1468
1992
|
// Caller-supplied cb_delegate only, never the roster-materialized one: a
|
|
1469
1993
|
// roster preset is Zod-parsed at load, which defaults min_score and erases
|
|
1470
1994
|
// whether the preset file actually requested it.
|
|
1471
|
-
admittedRosterName === undefined ? variables?.["cb_delegate"] : undefined);
|
|
1995
|
+
admittedRosterName === undefined ? variables?.["cb_delegate"] : undefined, recipeSeatPlan);
|
|
1472
1996
|
// A-7: reject caller context anchors that resolve to the bound plan or any
|
|
1473
1997
|
// plan-workspace PLAN.md. Pre-mutex, so a rejected request creates no state:
|
|
1474
1998
|
// the caller must not be able to hand actors a MUTABLE plan alongside the
|
|
@@ -1527,12 +2051,21 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1527
2051
|
let effectiveDefinition;
|
|
1528
2052
|
let initializedPlanReview;
|
|
1529
2053
|
let preparedSnapshot;
|
|
2054
|
+
let executionId;
|
|
2055
|
+
let pingPong;
|
|
2056
|
+
let pingPongReserved = false;
|
|
1530
2057
|
try {
|
|
1531
2058
|
ownership.throwIfCancelled();
|
|
1532
2059
|
const runDir = getRunStateDir(runId);
|
|
1533
2060
|
if (existsSync(runDir)) {
|
|
1534
2061
|
throw new McpError(ErrorCode.InvalidParams, `run_id ${runId} already has persisted state at ${runDir}`);
|
|
1535
2062
|
}
|
|
2063
|
+
if (pingPongSettings !== undefined) {
|
|
2064
|
+
// Grant, baseline and workspace reservation BEFORE state: any failure
|
|
2065
|
+
// is -32602 with nothing persisted (the reservation is released).
|
|
2066
|
+
resolvedVariables = await admitPingPongHost(options.recipeHost, runId, resolvedVariables, pingPongSettings, ownership.signal);
|
|
2067
|
+
pingPongReserved = true;
|
|
2068
|
+
}
|
|
1536
2069
|
// Read + digest-verify the plan BEFORE composing: the expander inlines
|
|
1537
2070
|
// the snapshot text, so it must exist by expansion time (D9).
|
|
1538
2071
|
preparedSnapshot = planReviewPlan === undefined
|
|
@@ -1547,6 +2080,7 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1547
2080
|
try {
|
|
1548
2081
|
store = await WorkflowStateStore.create({
|
|
1549
2082
|
runId,
|
|
2083
|
+
fileWriter: options.fileWriter,
|
|
1550
2084
|
definition: effectiveDefinition,
|
|
1551
2085
|
variables: resolvedVariables,
|
|
1552
2086
|
debugKeepArtifacts: debug,
|
|
@@ -1559,7 +2093,22 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1559
2093
|
catch (err) {
|
|
1560
2094
|
throw new McpError(ErrorCode.InternalError, `Failed to initialize async run ${runId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1561
2095
|
}
|
|
2096
|
+
executionId = await ownership.bindStore(store);
|
|
1562
2097
|
ownership.throwIfCancelled();
|
|
2098
|
+
if (pingPongSettings !== undefined) {
|
|
2099
|
+
// The ack is a durability boundary: the implementer worktree exists
|
|
2100
|
+
// and the sidecar is `admitted` with its acceptance pins.
|
|
2101
|
+
const wait = options.pingPongRuntime?.verificationWait;
|
|
2102
|
+
pingPong = new PingPongRuntime({
|
|
2103
|
+
store, host: options.recipeHost, runId, runDir: store.runDir, variables: resolvedVariables,
|
|
2104
|
+
...(wait !== undefined ? { verificationWaitMs: wait.waitMs, verificationPollMs: wait.pollMs } : {}),
|
|
2105
|
+
...(options.pingPongRuntime?.clock !== undefined
|
|
2106
|
+
? { now: options.pingPongRuntime.clock.now, monotonicNowMs: options.pingPongRuntime.clock.monotonicNowMs }
|
|
2107
|
+
: {}),
|
|
2108
|
+
});
|
|
2109
|
+
await pingPong.initialize(ownership.signal);
|
|
2110
|
+
ownership.throwIfCancelled();
|
|
2111
|
+
}
|
|
1563
2112
|
// A-10: the async acknowledgement is a durability boundary. A caller
|
|
1564
2113
|
// cannot observe `running` until every plan-review snapshot and the
|
|
1565
2114
|
// strict typed state subtree have committed successfully.
|
|
@@ -1574,7 +2123,9 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1574
2123
|
await markWorkflowCancelled(store);
|
|
1575
2124
|
throw new WorkflowCancellationError();
|
|
1576
2125
|
}
|
|
1577
|
-
|
|
2126
|
+
// Once bound (plan-review init, or a failed id stamp), the run owns a
|
|
2127
|
+
// persisted record: terminalize it and disclose the bound identity.
|
|
2128
|
+
if (store !== undefined && ownership.executionId !== undefined) {
|
|
1578
2129
|
try {
|
|
1579
2130
|
await markWorkflowFailed(store, runId, err);
|
|
1580
2131
|
}
|
|
@@ -1601,6 +2152,8 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1601
2152
|
summary: failureSummary,
|
|
1602
2153
|
debugBlock: debug ? buildErrorDebugBlock(runId, store) : undefined,
|
|
1603
2154
|
});
|
|
2155
|
+
// Bound even if persisting the id then failed: the entry exists.
|
|
2156
|
+
appendIdentityBlock(content, store, ownership.executionId);
|
|
1604
2157
|
return { content, isError: true };
|
|
1605
2158
|
}
|
|
1606
2159
|
throw err;
|
|
@@ -1613,17 +2166,24 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1613
2166
|
else
|
|
1614
2167
|
await verifiedRepair.finalize(ownership.signal.aborted ? "cancelled" : "failed", err);
|
|
1615
2168
|
}
|
|
2169
|
+
if (pingPongReserved && store === undefined) {
|
|
2170
|
+
// Nothing persisted: release the reservation this host recorded
|
|
2171
|
+
// (identity-bound; refused and left in place on any mismatch).
|
|
2172
|
+
await options.recipeHost.releaseUnadmittedRun?.(runId)?.catch((removeError) => {
|
|
2173
|
+
logger.warn({ err: removeError, runId }, "failed to release an unadmitted recipe workspace reservation");
|
|
2174
|
+
});
|
|
2175
|
+
}
|
|
1616
2176
|
}
|
|
1617
2177
|
finally {
|
|
1618
2178
|
await ownership.finish(store);
|
|
1619
2179
|
}
|
|
1620
2180
|
}
|
|
1621
2181
|
}
|
|
1622
|
-
if (store === undefined || effectiveDefinition === undefined) {
|
|
2182
|
+
if (store === undefined || effectiveDefinition === undefined || executionId === undefined) {
|
|
1623
2183
|
await ownership.finish(store);
|
|
1624
2184
|
throw new McpError(ErrorCode.InternalError, `Failed to initialize async run ${runId}`);
|
|
1625
2185
|
}
|
|
1626
|
-
void runWorkflowDetached(server, options, workflow, runId, resolvedVariables, debug, receipt, validatorRegistry, loaded, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort, true, ownership, undefined, store, effectiveDefinition, undefined, initializedPlanReview, initialContextPolicy, admittedRosterName, verifiedRepair).catch((err) => {
|
|
2186
|
+
void runWorkflowDetached(server, options, workflow, runId, resolvedVariables, debug, receipt, validatorRegistry, loaded, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort, true, ownership, undefined, store, effectiveDefinition, undefined, initializedPlanReview, initialContextPolicy, admittedRosterName, verifiedRepair, pingPong).catch((err) => {
|
|
1627
2187
|
if (err instanceof WorkflowCancellationError) {
|
|
1628
2188
|
logger.info({ runId }, "workflow run cancelled");
|
|
1629
2189
|
return;
|
|
@@ -1640,6 +2200,7 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1640
2200
|
type: "text",
|
|
1641
2201
|
text: JSON.stringify({
|
|
1642
2202
|
run_id: runId,
|
|
2203
|
+
execution_id: executionId,
|
|
1643
2204
|
status: "running",
|
|
1644
2205
|
...(duplicateOfFailedRun !== undefined
|
|
1645
2206
|
? { duplicate_of_failed_run: duplicateOfFailedRun }
|
|
@@ -1647,6 +2208,15 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
|
|
|
1647
2208
|
...(resolvedRoster !== undefined
|
|
1648
2209
|
? { resolved_roster: resolvedRoster }
|
|
1649
2210
|
: {}),
|
|
2211
|
+
...(pingPong !== undefined
|
|
2212
|
+
? {
|
|
2213
|
+
recipe: {
|
|
2214
|
+
baseline_commit: pingPong.admission.baseline_commit,
|
|
2215
|
+
// HEAD was pinned: uncommitted changes in the source checkout are not in the candidate.
|
|
2216
|
+
baseline_uncommitted_changes_excluded: pingPong.admission.baseline_uncommitted_changes_excluded,
|
|
2217
|
+
},
|
|
2218
|
+
}
|
|
2219
|
+
: {}),
|
|
1650
2220
|
}),
|
|
1651
2221
|
}],
|
|
1652
2222
|
};
|
|
@@ -1697,11 +2267,11 @@ async function initializePlanReviewRunState(store, plan, definition, prepared) {
|
|
|
1697
2267
|
if (!prepared.ok)
|
|
1698
2268
|
throw prepared.error;
|
|
1699
2269
|
const contract = plan.admission.execution_contract;
|
|
1700
|
-
const snapshot = await persistCanonicalPlanSnapshot(store.runDir, prepared.canonical);
|
|
2270
|
+
const snapshot = await persistCanonicalPlanSnapshot(store.runDir, prepared.canonical, store.fileWriter);
|
|
1701
2271
|
if (snapshot.absolutePath !== plan.snapshotAbsolutePath) {
|
|
1702
2272
|
throw new PlanReviewStageError("snapshot", `Snapshot path ${snapshot.absolutePath} does not match the runtime-owned path derived for this run (${plan.snapshotAbsolutePath})`);
|
|
1703
2273
|
}
|
|
1704
|
-
const persistedContract = await writeExecutionContractSnapshot(store.runDir, contract);
|
|
2274
|
+
const persistedContract = await writeExecutionContractSnapshot(store.runDir, contract, store.fileWriter);
|
|
1705
2275
|
const state = {
|
|
1706
2276
|
schema_version: "council-plan-review-state-v1",
|
|
1707
2277
|
execution_contract_path: persistedContract.relPath,
|
|
@@ -1760,14 +2330,70 @@ function projectResolvedRosterDelegate(policy, resolvedVariables) {
|
|
|
1760
2330
|
};
|
|
1761
2331
|
}
|
|
1762
2332
|
/**
|
|
1763
|
-
*
|
|
2333
|
+
* D-R4 seat plan for a recipe workflow from the parsed seat parameters and
|
|
2334
|
+
* the workflow's optional default chairman call. Pure; throws `-32602`.
|
|
2335
|
+
*/
|
|
2336
|
+
export function recipeSeatPlanForAdmission(workflow, definition, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort) {
|
|
2337
|
+
if (!isRecipeSeatWorkflow(workflow)) {
|
|
2338
|
+
throw new McpError(ErrorCode.InvalidParams, `workflow "${workflow}" is not a recipe workflow`);
|
|
2339
|
+
}
|
|
2340
|
+
const defaultChairman = RECIPE_SEAT_RULES[workflow].chairman === "required"
|
|
2341
|
+
? findRecipeDefaultChairmanCall(definition)
|
|
2342
|
+
: undefined;
|
|
2343
|
+
return expandRecipeSeats(workflow, {
|
|
2344
|
+
members: parsedMembers,
|
|
2345
|
+
chairman: parsedChairman,
|
|
2346
|
+
chairmanModel: parsedChairmanModel,
|
|
2347
|
+
chairmanEffort: parsedChairmanEffort,
|
|
2348
|
+
...(defaultChairman !== undefined ? { defaultChairman } : {}),
|
|
2349
|
+
});
|
|
2350
|
+
}
|
|
2351
|
+
/**
|
|
2352
|
+
* Recipe `resolved_roster`: the same requested-value shape as councils.
|
|
2353
|
+
* `members` lists the caller's seats in `members` order (index = caller
|
|
2354
|
+
* index); the per-recipe role of each index is the D-R4 mapping. Recipes have
|
|
2355
|
+
* no separate cross-review stage, so `reviewers` is empty. `chairman` is the
|
|
2356
|
+
* effective judge/selector/integrator, or `{}` for ping-pong. As for
|
|
2357
|
+
* councils, `provider_spawns` counts one spawn per projected seat; recipes
|
|
2358
|
+
* that loop rounds spawn their seats once per round on top of that.
|
|
2359
|
+
*/
|
|
2360
|
+
function buildRecipeResolvedRoster(input) {
|
|
2361
|
+
const plan = recipeSeatPlanForAdmission(input.workflow, input.definition, input.parsedMembers, input.parsedChairman, input.parsedChairmanModel, input.parsedChairmanEffort);
|
|
2362
|
+
const seats = recipeSeatPlanSeats(plan);
|
|
2363
|
+
const members = seats.members.map((seat) => projectResolvedRosterSeat(seat, seat.index, seat.stance !== undefined));
|
|
2364
|
+
const chairman = seats.chairman;
|
|
2365
|
+
const delegate = projectResolvedRosterDelegate(input.initialContextPolicy, input.resolvedVariables);
|
|
2366
|
+
const preflightCalls = delegate.enabled === true
|
|
2367
|
+
? 1 + (delegate.finalizer.effective_enabled ? 1 : 0)
|
|
2368
|
+
: 0;
|
|
2369
|
+
return ResolvedRosterSchema.parse({
|
|
2370
|
+
...(input.rosterName !== undefined ? { roster: input.rosterName } : {}),
|
|
2371
|
+
members,
|
|
2372
|
+
reviewers: [],
|
|
2373
|
+
chairman: chairman === undefined
|
|
2374
|
+
? {}
|
|
2375
|
+
: {
|
|
2376
|
+
cli_name: chairman.cli_name,
|
|
2377
|
+
...(chairman.model !== undefined ? { model: chairman.model } : {}),
|
|
2378
|
+
...(chairman.effort !== undefined ? { effort: chairman.effort } : {}),
|
|
2379
|
+
},
|
|
2380
|
+
delegate,
|
|
2381
|
+
provider_spawns: members.length + (chairman === undefined ? 0 : 1),
|
|
2382
|
+
preflight_calls: preflightCalls,
|
|
2383
|
+
});
|
|
2384
|
+
}
|
|
2385
|
+
/**
|
|
2386
|
+
* Requested-value roster projection for council and recipe workflows. Call AFTER
|
|
1764
2387
|
* `expandCouncilComposition` / `expandRunWorkflowDefinition`, AFTER
|
|
1765
2388
|
* `resolveEffectiveChairmanCall` values are on the definition (or passed as
|
|
1766
2389
|
* parsed chairman knobs), and AFTER `effectiveFinalizerEnabled` can be
|
|
1767
2390
|
* evaluated from `initialContextPolicy` — and BEFORE `WorkflowStateStore.create()`.
|
|
1768
|
-
* `plan-review-receipts` and any
|
|
2391
|
+
* `plan-review-receipts` and any other workflow return undefined.
|
|
1769
2392
|
*/
|
|
1770
2393
|
export function buildResolvedRoster(input) {
|
|
2394
|
+
if (isRecipeSeatWorkflow(input.workflow)) {
|
|
2395
|
+
return buildRecipeResolvedRoster(input);
|
|
2396
|
+
}
|
|
1771
2397
|
if (!supportsRuntimeMembers(input.workflow)) {
|
|
1772
2398
|
return undefined;
|
|
1773
2399
|
}
|
|
@@ -1836,14 +2462,16 @@ preparedSnapshot) {
|
|
|
1836
2462
|
// string cannot carry. This is the single read — never re-read `plan_file`.
|
|
1837
2463
|
preparedSnapshot?.ok === true ? preparedSnapshot.canonical : undefined);
|
|
1838
2464
|
}
|
|
1839
|
-
|
|
2465
|
+
// Recipe seats never rewrite the definition: the recipe runtime dispatches
|
|
2466
|
+
// its seats from the admission seat plan, not from static stages.
|
|
2467
|
+
return supportsRuntimeMembers(workflow) && (parsedMembers != null ||
|
|
1840
2468
|
parsedChairman != null ||
|
|
1841
2469
|
parsedChairmanModel !== undefined ||
|
|
1842
|
-
parsedChairmanEffort !== undefined
|
|
2470
|
+
parsedChairmanEffort !== undefined)
|
|
1843
2471
|
? expandCouncilComposition(definition, parsedMembers, workflow, parsedChairman, parsedChairmanModel, parsedChairmanEffort)
|
|
1844
2472
|
: definition;
|
|
1845
2473
|
}
|
|
1846
|
-
async function runWorkflowDetached(server, options, workflow, runId, resolvedVariables, debug, receipt, validatorRegistry, loaded, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort, isAsync, ownership, progressToken, preCreatedStore, preExpandedDefinition, planReviewPlan, preInitializedPlanReview, initialContextPolicy, rosterName, verifiedRepair) {
|
|
2474
|
+
async function runWorkflowDetached(server, options, workflow, runId, resolvedVariables, debug, receipt, validatorRegistry, loaded, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort, isAsync, ownership, progressToken, preCreatedStore, preExpandedDefinition, planReviewPlan, preInitializedPlanReview, initialContextPolicy, rosterName, verifiedRepair, pingPong) {
|
|
1847
2475
|
let store = preCreatedStore ?? null;
|
|
1848
2476
|
let backend = null;
|
|
1849
2477
|
let reporter;
|
|
@@ -1868,6 +2496,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
1868
2496
|
const resolvedRoster = resolvedRosterForAdmission(workflow, effectiveDefinition, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort, initialContextPolicy, resolvedVariables, rosterName);
|
|
1869
2497
|
store = await WorkflowStateStore.create({
|
|
1870
2498
|
runId,
|
|
2499
|
+
fileWriter: options.fileWriter,
|
|
1871
2500
|
definition: effectiveDefinition,
|
|
1872
2501
|
variables: resolvedVariables,
|
|
1873
2502
|
debugKeepArtifacts: debug,
|
|
@@ -1877,6 +2506,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
1877
2506
|
...(rosterName !== undefined ? { rosterName } : {}),
|
|
1878
2507
|
});
|
|
1879
2508
|
}
|
|
2509
|
+
await ownership.bindStore(store);
|
|
1880
2510
|
ownership.throwIfCancelled();
|
|
1881
2511
|
releaseLifecycleBinding = options.contextBuilderLifecycleRouter?.bind(runId, store);
|
|
1882
2512
|
// A-5/A-6: snapshot + contract + typed subtree land here — after state
|
|
@@ -1901,8 +2531,9 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
1901
2531
|
? new WorkflowProgressReporter(server, progressToken, runId, effectiveDefinition)
|
|
1902
2532
|
: undefined;
|
|
1903
2533
|
const rpt = reporter; // local const for closure narrowing
|
|
2534
|
+
const baseHooks = storeRef.hooks;
|
|
1904
2535
|
const hooks = {
|
|
1905
|
-
...
|
|
2536
|
+
...baseHooks,
|
|
1906
2537
|
...(verifiedRepair === undefined ? {} : {
|
|
1907
2538
|
onRunStateChange: async (event) => {
|
|
1908
2539
|
if (event.state === "succeeded" || event.state === "failed" || event.state === "cancelled") {
|
|
@@ -1942,6 +2573,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
1942
2573
|
runId,
|
|
1943
2574
|
sessionLogGeneration,
|
|
1944
2575
|
runDir: storeRef.runDir,
|
|
2576
|
+
fileWriter: options.fileWriter,
|
|
1945
2577
|
signal,
|
|
1946
2578
|
hooks,
|
|
1947
2579
|
contextBuilderRunner: verifiedRepair === undefined ? options.contextBuilderRunner : undefined,
|
|
@@ -1950,6 +2582,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
1950
2582
|
commitPreflightContext: storeRef.commitPreflightContext?.bind(storeRef),
|
|
1951
2583
|
initialContextPolicy,
|
|
1952
2584
|
verifiedRepair,
|
|
2585
|
+
pingPong,
|
|
1953
2586
|
...(options.deriveInvocationAudit === undefined
|
|
1954
2587
|
? {}
|
|
1955
2588
|
: { deriveInvocationAudit: options.deriveInvocationAudit }),
|
|
@@ -1986,7 +2619,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
1986
2619
|
debugBlock: debug ? buildDebugBlock(runId, result, store) : undefined,
|
|
1987
2620
|
});
|
|
1988
2621
|
appendDuplicateReplayBlock(content, store);
|
|
1989
|
-
|
|
2622
|
+
appendIdentityBlock(content, store, ownership.executionId);
|
|
1990
2623
|
return { content };
|
|
1991
2624
|
}
|
|
1992
2625
|
catch (error) {
|
|
@@ -2002,6 +2635,11 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
2002
2635
|
logger.error({ err: publicationError, runId }, "repair error publication failed; preserving original execution failure");
|
|
2003
2636
|
}
|
|
2004
2637
|
}
|
|
2638
|
+
if (pingPong !== undefined && store !== null) {
|
|
2639
|
+
// No-op when the engine already settled the run; otherwise mark* orders
|
|
2640
|
+
// the sidecar before state.json in one critical section.
|
|
2641
|
+
await settleRecipeExecution(store, signal, error);
|
|
2642
|
+
}
|
|
2005
2643
|
if (signal.aborted || error instanceof WorkflowCancellationError) {
|
|
2006
2644
|
await markWorkflowCancelled(store);
|
|
2007
2645
|
throw new WorkflowCancellationError();
|
|
@@ -2039,7 +2677,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
2039
2677
|
debugBlock: debug && store != null ? buildErrorDebugBlock(runId, store) : undefined,
|
|
2040
2678
|
});
|
|
2041
2679
|
appendDuplicateReplayBlock(content, store);
|
|
2042
|
-
|
|
2680
|
+
appendIdentityBlock(content, store, ownership.executionId);
|
|
2043
2681
|
return { content, isError: true };
|
|
2044
2682
|
}
|
|
2045
2683
|
finally {
|
|
@@ -2053,18 +2691,9 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
|
|
|
2053
2691
|
}
|
|
2054
2692
|
}
|
|
2055
2693
|
async function executeResumeWorkflow(server, options, args, signal, progressToken) {
|
|
2056
|
-
const runId = args
|
|
2694
|
+
const runId = runIdArg(args);
|
|
2057
2695
|
const debug = args["debug"] === true;
|
|
2058
2696
|
const receipt = args["receipt"] === true;
|
|
2059
|
-
if (typeof runId !== "string" || runId === "") {
|
|
2060
|
-
throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid "run_id" parameter');
|
|
2061
|
-
}
|
|
2062
|
-
try {
|
|
2063
|
-
validateRunId(runId);
|
|
2064
|
-
}
|
|
2065
|
-
catch {
|
|
2066
|
-
throw new McpError(ErrorCode.InvalidParams, `Invalid run_id "${runId}". Must match [A-Za-z0-9_-]{1,64}.`);
|
|
2067
|
-
}
|
|
2068
2697
|
// Plan-review terminal state is authoritative even while the detached run's
|
|
2069
2698
|
// finally still owns the in-process mutex. Read it before duplicate-run
|
|
2070
2699
|
// arbitration so terminal-before-cleanup never leaks as "already running".
|
|
@@ -2081,6 +2710,14 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
|
|
|
2081
2710
|
if (persistedState?.workflowName === VERIFIED_REPAIR_WORKFLOW) {
|
|
2082
2711
|
throw new McpError(ErrorCode.InvalidParams, "verified-repair mutation cannot be resumed; inspect the retained result and submit a fresh explicit contract");
|
|
2083
2712
|
}
|
|
2713
|
+
// CONTRACTS 0-7: recipe runs are never generically resumed. Fail closed: a
|
|
2714
|
+
// sidecar probe error, or a recipe workflow name, rejects even when the
|
|
2715
|
+
// state pre-read above failed. The store-level resume() repeats the check
|
|
2716
|
+
// under the lock.
|
|
2717
|
+
if (isSidecarRecipeWorkflow(persistedState?.workflowName) ||
|
|
2718
|
+
await recipeSidecarPresence(getRunStateDir(runId)) === "present") {
|
|
2719
|
+
throw new McpError(ErrorCode.InvalidParams, `Run ${runId} is a recipe run and cannot be resumed; decide a paused run with ${RECIPE_DECIDE_TOOL}, stop it with cancel_workflow, or start a new run.`);
|
|
2720
|
+
}
|
|
2084
2721
|
if (persistedState != null &&
|
|
2085
2722
|
isPlanReviewRunState(persistedState) &&
|
|
2086
2723
|
(persistedState.status === "failed" ||
|
|
@@ -2109,6 +2746,7 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
|
|
|
2109
2746
|
const resumeOptions = {
|
|
2110
2747
|
runId,
|
|
2111
2748
|
debugKeepArtifacts: debug,
|
|
2749
|
+
fileWriter: options.fileWriter,
|
|
2112
2750
|
};
|
|
2113
2751
|
store = await WorkflowStateStore.resume(resumeOptions);
|
|
2114
2752
|
if (store.runState.workflowName === VERIFIED_REPAIR_WORKFLOW) {
|
|
@@ -2117,6 +2755,7 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
|
|
|
2117
2755
|
// Open this attempt before classifying an abort during reconstruction;
|
|
2118
2756
|
// otherwise a prior terminal record would suppress markCancelled.
|
|
2119
2757
|
await store.beginResumeAttempt();
|
|
2758
|
+
await ownership.bindStore(store);
|
|
2120
2759
|
ownership.throwIfCancelled();
|
|
2121
2760
|
releaseLifecycleBinding = options.contextBuilderLifecycleRouter?.bind(runId, store);
|
|
2122
2761
|
const validatorRegistry = createValidatorRegistry();
|
|
@@ -2179,6 +2818,7 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
|
|
|
2179
2818
|
validatorRegistry,
|
|
2180
2819
|
runId,
|
|
2181
2820
|
runDir: store.runDir,
|
|
2821
|
+
fileWriter: options.fileWriter,
|
|
2182
2822
|
signal: ownedSignal,
|
|
2183
2823
|
resume: store.resume,
|
|
2184
2824
|
contextBuilderRunner: options.contextBuilderRunner,
|
|
@@ -2246,6 +2886,7 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
|
|
|
2246
2886
|
runId,
|
|
2247
2887
|
sessionLogGeneration,
|
|
2248
2888
|
runDir: store.runDir,
|
|
2889
|
+
fileWriter: options.fileWriter,
|
|
2249
2890
|
signal: ownedSignal,
|
|
2250
2891
|
hooks: rpt != null ? hooks : store.hooks,
|
|
2251
2892
|
resume: store.resume,
|
|
@@ -2293,16 +2934,27 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
|
|
|
2293
2934
|
summary,
|
|
2294
2935
|
debugBlock: debug ? buildDebugBlock(runId, result, store) : undefined,
|
|
2295
2936
|
});
|
|
2937
|
+
appendIdentityBlock(content, null, ownership.executionId);
|
|
2296
2938
|
return { content };
|
|
2297
2939
|
}
|
|
2298
2940
|
catch (error) {
|
|
2941
|
+
// Only a bound attempt owns the persisted record. Before bind, a failed
|
|
2942
|
+
// beginResumeAttempt leaves in-memory state "pending" while disk still
|
|
2943
|
+
// holds the settled run's terminal bytes; persisting it would displace
|
|
2944
|
+
// that settled execution.
|
|
2945
|
+
const owned = ownership.executionId !== undefined;
|
|
2299
2946
|
if (ownedSignal.aborted || error instanceof WorkflowCancellationError) {
|
|
2300
|
-
|
|
2947
|
+
if (owned)
|
|
2948
|
+
await markWorkflowCancelled(store);
|
|
2301
2949
|
throw new WorkflowCancellationError();
|
|
2302
2950
|
}
|
|
2951
|
+
// A verified-repair store is never bound: this is the pre-mutex rejection
|
|
2952
|
+
// reached when that read failed, so report it the same way (-32602).
|
|
2953
|
+
if (!owned && store?.runState.workflowName === VERIFIED_REPAIR_WORKFLOW)
|
|
2954
|
+
throw error;
|
|
2303
2955
|
// Persist a terminal "failed" record for post-admission setup failures.
|
|
2304
2956
|
// Idempotent: won't clobber an engine-emitted terminal status.
|
|
2305
|
-
if (store != null) {
|
|
2957
|
+
if (owned && store != null) {
|
|
2306
2958
|
try {
|
|
2307
2959
|
await markWorkflowFailed(store, runId, error);
|
|
2308
2960
|
}
|
|
@@ -2328,6 +2980,7 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
|
|
|
2328
2980
|
summary: failureSummary,
|
|
2329
2981
|
debugBlock: debug && store != null ? buildErrorDebugBlock(runId, store) : undefined,
|
|
2330
2982
|
});
|
|
2983
|
+
appendIdentityBlock(content, null, ownership.executionId);
|
|
2331
2984
|
return { content, isError: true };
|
|
2332
2985
|
}
|
|
2333
2986
|
finally {
|
|
@@ -2428,9 +3081,18 @@ function parseLifecycleForStatus(value) {
|
|
|
2428
3081
|
return undefined;
|
|
2429
3082
|
}
|
|
2430
3083
|
}
|
|
2431
|
-
|
|
3084
|
+
function expectedExecutionId(args) {
|
|
3085
|
+
const expected = args["expected_execution_id"];
|
|
3086
|
+
if (expected === undefined)
|
|
3087
|
+
return undefined;
|
|
3088
|
+
if (typeof expected !== "string" || expected.length === 0 || expected.length > 128) {
|
|
3089
|
+
throw new McpError(ErrorCode.InvalidParams, "expected_execution_id must be a nonempty string of at most 128 characters");
|
|
3090
|
+
}
|
|
3091
|
+
return expected;
|
|
3092
|
+
}
|
|
3093
|
+
/** Shared by resume and pinned/unpinned status/wait, preserving their existing messages. */
|
|
3094
|
+
function runIdArg(args) {
|
|
2432
3095
|
const runId = args["run_id"];
|
|
2433
|
-
const includeResult = args["include_result"] === true;
|
|
2434
3096
|
if (typeof runId !== "string" || runId === "") {
|
|
2435
3097
|
throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid "run_id" parameter');
|
|
2436
3098
|
}
|
|
@@ -2440,12 +3102,242 @@ async function executeWorkflowRunStatus(options, args) {
|
|
|
2440
3102
|
catch {
|
|
2441
3103
|
throw new McpError(ErrorCode.InvalidParams, `Invalid run_id "${runId}". Must match [A-Za-z0-9_-]{1,64}.`);
|
|
2442
3104
|
}
|
|
2443
|
-
|
|
3105
|
+
return runId;
|
|
3106
|
+
}
|
|
3107
|
+
function identityError(runId, reason) {
|
|
3108
|
+
return {
|
|
3109
|
+
isError: true,
|
|
3110
|
+
content: [{ type: "text", text: JSON.stringify({ run_id: runId, error: reason }) }],
|
|
3111
|
+
};
|
|
3112
|
+
}
|
|
3113
|
+
/**
|
|
3114
|
+
* Project status for one bound execution and fence it. A settled execution is
|
|
3115
|
+
* fenced on the digest of the exact state bytes the projection parsed (one
|
|
3116
|
+
* state.json read on the success path); an active one only on provenance and
|
|
3117
|
+
* directory incarnation, since it legitimately republishes state.
|
|
3118
|
+
*/
|
|
3119
|
+
async function projectGuardedStatus(options, args, entry) {
|
|
3120
|
+
const wasSettled = entry.settled;
|
|
3121
|
+
const wasStamped = entry.stamped;
|
|
3122
|
+
const guard = {};
|
|
3123
|
+
let result;
|
|
3124
|
+
try {
|
|
3125
|
+
result = await projectWorkflowRunStatus(options, args, guard);
|
|
3126
|
+
}
|
|
3127
|
+
catch (error) {
|
|
3128
|
+
const reread = wasSettled ? (await inspectPublication(entry.runDir))?.fingerprint ?? null : undefined;
|
|
3129
|
+
const failure = await completions.check(entry, reread);
|
|
3130
|
+
if (failure !== undefined)
|
|
3131
|
+
return { failure };
|
|
3132
|
+
if (error instanceof ContainedFileChangedError) {
|
|
3133
|
+
return { failure: wasSettled ? "identity_unavailable" : "state_read_unstable" };
|
|
3134
|
+
}
|
|
3135
|
+
throw error;
|
|
3136
|
+
}
|
|
3137
|
+
const failure = await completions.check(entry, wasSettled ? guard.stateDigest ?? null : undefined);
|
|
3138
|
+
if (failure !== undefined)
|
|
3139
|
+
return { failure };
|
|
3140
|
+
// Another process sharing the state dir can resume the run in place, which
|
|
3141
|
+
// keeps the directory incarnation; only the persisted id shows the change.
|
|
3142
|
+
if (wasStamped && guard.executionId !== entry.executionId) {
|
|
3143
|
+
return { failure: typeof guard.executionId === "string" ? "identity_changed" : "identity_unavailable" };
|
|
3144
|
+
}
|
|
3145
|
+
return { result };
|
|
3146
|
+
}
|
|
3147
|
+
async function executeWorkflowRunStatus(options, args) {
|
|
3148
|
+
const expected = expectedExecutionId(args);
|
|
3149
|
+
if (expected === undefined)
|
|
3150
|
+
return projectWorkflowRunStatus(options, args);
|
|
3151
|
+
const runId = runIdArg(args);
|
|
3152
|
+
const selected = completions.select(getRunStateDir(runId), expected);
|
|
3153
|
+
if (selected === "identity_unavailable") {
|
|
3154
|
+
const persisted = await projectPersistedSettledStatus(options, args, runId, expected);
|
|
3155
|
+
return "failure" in persisted ? identityError(runId, persisted.failure) : persisted.result;
|
|
3156
|
+
}
|
|
3157
|
+
if (typeof selected === "string")
|
|
3158
|
+
return identityError(runId, selected);
|
|
3159
|
+
if (selected === undefined)
|
|
3160
|
+
return identityError(runId, "identity_unavailable");
|
|
3161
|
+
const release = completions.retain(selected);
|
|
3162
|
+
try {
|
|
3163
|
+
const before = await completions.check(selected);
|
|
3164
|
+
if (before !== undefined)
|
|
3165
|
+
return identityError(runId, before);
|
|
3166
|
+
const fenced = await projectGuardedStatus(options, args, selected);
|
|
3167
|
+
return "failure" in fenced ? identityError(runId, fenced.failure) : fenced.result;
|
|
3168
|
+
}
|
|
3169
|
+
finally {
|
|
3170
|
+
release();
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
async function executeWorkflowRunWait(options, args, signal) {
|
|
3174
|
+
const started = Date.now();
|
|
3175
|
+
const runId = runIdArg(args);
|
|
3176
|
+
const expected = expectedExecutionId(args);
|
|
3177
|
+
const selected = completions.select(getRunStateDir(runId), expected);
|
|
3178
|
+
let outcome;
|
|
3179
|
+
let entry;
|
|
3180
|
+
let persistedExecutionId;
|
|
3181
|
+
const release = typeof selected === "object" ? completions.retain(selected) : undefined;
|
|
3182
|
+
const respond = (projection = { run_id: runId }) => {
|
|
3183
|
+
if (signal.aborted)
|
|
3184
|
+
throw new WorkflowCancellationError();
|
|
3185
|
+
return {
|
|
3186
|
+
content: [{
|
|
3187
|
+
type: "text",
|
|
3188
|
+
text: JSON.stringify({
|
|
3189
|
+
...projection,
|
|
3190
|
+
wait: {
|
|
3191
|
+
outcome,
|
|
3192
|
+
...(entry !== undefined ? { execution_id: entry.executionId } : {}),
|
|
3193
|
+
...(persistedExecutionId !== undefined ? { execution_id: persistedExecutionId } : {}),
|
|
3194
|
+
budget_ms: WORKFLOW_WAIT_BUDGET_MS,
|
|
3195
|
+
elapsed_ms: Math.max(0, Date.now() - started),
|
|
3196
|
+
},
|
|
3197
|
+
}),
|
|
3198
|
+
}],
|
|
3199
|
+
};
|
|
3200
|
+
};
|
|
3201
|
+
try {
|
|
3202
|
+
if (selected === "identity_unavailable" && expected !== undefined) {
|
|
3203
|
+
// No local record: settled only if state.json proves this execution ended.
|
|
3204
|
+
const persisted = await projectPersistedSettledStatus(options, { run_id: runId }, runId, expected);
|
|
3205
|
+
if (signal.aborted)
|
|
3206
|
+
throw new WorkflowCancellationError();
|
|
3207
|
+
if ("failure" in persisted) {
|
|
3208
|
+
outcome = persisted.failure;
|
|
3209
|
+
return respond();
|
|
3210
|
+
}
|
|
3211
|
+
outcome = "settled";
|
|
3212
|
+
persistedExecutionId = expected;
|
|
3213
|
+
return respond(JSON.parse(persisted.result.content[0].text));
|
|
3214
|
+
}
|
|
3215
|
+
if (typeof selected === "string")
|
|
3216
|
+
outcome = selected;
|
|
3217
|
+
else if (selected === undefined)
|
|
3218
|
+
outcome = "not_owned";
|
|
3219
|
+
else {
|
|
3220
|
+
entry = selected;
|
|
3221
|
+
outcome = await completions.wait(entry, signal);
|
|
3222
|
+
const failure = await completions.check(entry);
|
|
3223
|
+
if (failure !== undefined)
|
|
3224
|
+
outcome = failure;
|
|
3225
|
+
}
|
|
3226
|
+
if (signal.aborted)
|
|
3227
|
+
throw new WorkflowCancellationError();
|
|
3228
|
+
// Never inspect a replacement or unreadable state after provenance fails.
|
|
3229
|
+
if (outcome === "identity_changed" || outcome === "identity_unavailable")
|
|
3230
|
+
return respond();
|
|
3231
|
+
// Metadata only: the result body is fetched separately through the guarded status tool.
|
|
3232
|
+
if (entry !== undefined) {
|
|
3233
|
+
const fenced = await projectGuardedStatus(options, { run_id: runId }, entry);
|
|
3234
|
+
if (signal.aborted)
|
|
3235
|
+
throw new WorkflowCancellationError();
|
|
3236
|
+
if ("failure" in fenced) {
|
|
3237
|
+
// An unstable active read is a normal re-arm, never a hard error.
|
|
3238
|
+
outcome = fenced.failure === "state_read_unstable" ? "budget_elapsed" : fenced.failure;
|
|
3239
|
+
return respond();
|
|
3240
|
+
}
|
|
3241
|
+
return respond(JSON.parse(fenced.result.content[0].text));
|
|
3242
|
+
}
|
|
3243
|
+
const status = await projectWorkflowRunStatus(options, { run_id: runId });
|
|
3244
|
+
const projection = JSON.parse(status.content[0].text);
|
|
3245
|
+
if (projection["status"] === "not_found")
|
|
3246
|
+
outcome = "not_found";
|
|
3247
|
+
else if (projection["status"] === "orphaned")
|
|
3248
|
+
outcome = "orphaned";
|
|
3249
|
+
if (signal.aborted)
|
|
3250
|
+
throw new WorkflowCancellationError();
|
|
3251
|
+
return respond(projection);
|
|
3252
|
+
}
|
|
3253
|
+
finally {
|
|
3254
|
+
release?.();
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
/**
|
|
3258
|
+
* A pin with no local record (bound by an earlier process, or evicted here) is
|
|
3259
|
+
* resolved from the executionId persisted in state.json. The id, terminal
|
|
3260
|
+
* status and released run.lock are checked on the exact bytes the projection
|
|
3261
|
+
* then renders. After the projection a second contained read must return the
|
|
3262
|
+
* same bytes with the lock still released, the directory incarnation must be
|
|
3263
|
+
* unchanged, and no local execution may have bound the run dir; otherwise the
|
|
3264
|
+
* read fails closed, since a foreign resume keeps the generation.
|
|
3265
|
+
*/
|
|
3266
|
+
async function projectPersistedSettledStatus(options, args, runId, expected) {
|
|
3267
|
+
const runDir = getRunStateDir(runId);
|
|
3268
|
+
const latest = completions.select(runDir);
|
|
3269
|
+
if (latest !== undefined && !latest.settled)
|
|
3270
|
+
return { failure: "identity_changed" };
|
|
3271
|
+
const before = await readSessionLogGeneration(runDir);
|
|
3272
|
+
if (before.kind !== "available")
|
|
3273
|
+
return { failure: "identity_unavailable" };
|
|
3274
|
+
const guard = { persistedExecutionId: expected };
|
|
3275
|
+
let result;
|
|
3276
|
+
let projectionError;
|
|
3277
|
+
try {
|
|
3278
|
+
result = await projectWorkflowRunStatus(options, args, guard);
|
|
3279
|
+
}
|
|
3280
|
+
catch (error) {
|
|
3281
|
+
// Unreadable, oversized, malformed or persistently changing state.
|
|
3282
|
+
if (guard.persistedIdentity === undefined)
|
|
3283
|
+
return { failure: "identity_unavailable" };
|
|
3284
|
+
projectionError = error;
|
|
3285
|
+
}
|
|
3286
|
+
if (guard.persistedIdentity !== "matched")
|
|
3287
|
+
return { failure: guard.persistedIdentity ?? "identity_unavailable" };
|
|
3288
|
+
let reread;
|
|
3289
|
+
try {
|
|
3290
|
+
reread = await readRunStateForStatus(runId, true);
|
|
3291
|
+
}
|
|
3292
|
+
catch {
|
|
3293
|
+
return { failure: "identity_unavailable" };
|
|
3294
|
+
}
|
|
3295
|
+
if (reread == null)
|
|
3296
|
+
return { failure: "identity_unavailable" };
|
|
3297
|
+
// Same rule as the first check: only a different stamped id is a change.
|
|
3298
|
+
const rereadId = reread.state.executionId;
|
|
3299
|
+
if (typeof rereadId === "string" && rereadId !== expected)
|
|
3300
|
+
return { failure: "identity_changed" };
|
|
3301
|
+
if (reread.stateDigest !== guard.stateDigest || reread.lock !== "stale_or_absent") {
|
|
3302
|
+
return { failure: "identity_unavailable" };
|
|
3303
|
+
}
|
|
3304
|
+
const after = await readSessionLogGeneration(runDir);
|
|
3305
|
+
// A new local bind supersedes the pin; mere eviction of `latest` does not.
|
|
3306
|
+
const current = completions.select(runDir);
|
|
3307
|
+
if (current !== undefined && current !== latest)
|
|
3308
|
+
return { failure: "identity_changed" };
|
|
3309
|
+
if (after.kind !== "available")
|
|
3310
|
+
return { failure: "identity_unavailable" };
|
|
3311
|
+
if (after.sessionLogGeneration !== before.sessionLogGeneration)
|
|
3312
|
+
return { failure: "identity_changed" };
|
|
3313
|
+
if (result !== undefined)
|
|
3314
|
+
return { result };
|
|
3315
|
+
// Same mapping as the in-memory settled path: a racing contained read fails closed.
|
|
3316
|
+
if (projectionError instanceof ContainedFileChangedError)
|
|
3317
|
+
return { failure: "identity_unavailable" };
|
|
3318
|
+
throw projectionError;
|
|
3319
|
+
}
|
|
3320
|
+
async function projectWorkflowRunStatus(options, args, guard) {
|
|
3321
|
+
const runId = runIdArg(args);
|
|
3322
|
+
const includeResult = args["include_result"] === true;
|
|
3323
|
+
const read = await readRunStateForStatus(runId, guard !== undefined);
|
|
2444
3324
|
if (read == null) {
|
|
3325
|
+
if (guard?.persistedExecutionId !== undefined)
|
|
3326
|
+
guard.persistedIdentity = "identity_unavailable";
|
|
2445
3327
|
return {
|
|
2446
3328
|
content: [{ type: "text", text: JSON.stringify({ status: "not_found", run_id: runId }) }],
|
|
2447
3329
|
};
|
|
2448
3330
|
}
|
|
3331
|
+
if (guard !== undefined) {
|
|
3332
|
+
guard.stateDigest = read.stateDigest;
|
|
3333
|
+
guard.executionId = read.state.executionId;
|
|
3334
|
+
}
|
|
3335
|
+
if (guard?.persistedExecutionId !== undefined) {
|
|
3336
|
+
// Checked before any further I/O, on the bytes this projection renders.
|
|
3337
|
+
guard.persistedIdentity = persistedIdentityFailure(read.state, read.lock, runId, guard.persistedExecutionId) ?? "matched";
|
|
3338
|
+
if (guard.persistedIdentity !== "matched")
|
|
3339
|
+
return { content: [] };
|
|
3340
|
+
}
|
|
2449
3341
|
const { state, lock } = read;
|
|
2450
3342
|
const status = (state.status === "running" || state.status === "pending") && lock === "stale_or_absent"
|
|
2451
3343
|
? "orphaned"
|
|
@@ -2609,7 +3501,15 @@ async function executeWorkflowRunStatus(options, args) {
|
|
|
2609
3501
|
}
|
|
2610
3502
|
else {
|
|
2611
3503
|
projection["result_available"] = state.status === "succeeded";
|
|
2612
|
-
|
|
3504
|
+
const pingPongWithoutRecord = state.workflowName === PING_PONG_WORKFLOW &&
|
|
3505
|
+
state.stages.at(-1)?.calls[0]?.outputInline == null &&
|
|
3506
|
+
state.stages.at(-1)?.calls[0]?.outputPath == null;
|
|
3507
|
+
if (state.status === "succeeded" && pingPongWithoutRecord) {
|
|
3508
|
+
// A pause (or a stop before the terminal record stage) publishes a
|
|
3509
|
+
// terminal envelope with no final output; the recipe block carries it.
|
|
3510
|
+
projection["result_available"] = false;
|
|
3511
|
+
}
|
|
3512
|
+
else if (state.status === "succeeded") {
|
|
2613
3513
|
const final = state.stages.at(-1);
|
|
2614
3514
|
const call = final?.calls[0];
|
|
2615
3515
|
// Cheap size hint without reading contents. Containment (via
|
|
@@ -2671,6 +3571,11 @@ async function executeWorkflowRunStatus(options, args) {
|
|
|
2671
3571
|
}
|
|
2672
3572
|
}
|
|
2673
3573
|
}
|
|
3574
|
+
if (state.workflowName === PING_PONG_WORKFLOW) {
|
|
3575
|
+
const recipe = await projectRecipeBlock(runDir, state, guard !== undefined);
|
|
3576
|
+
if (recipe !== undefined)
|
|
3577
|
+
projection["recipe"] = recipe;
|
|
3578
|
+
}
|
|
2674
3579
|
if (state.workflowName === ARCHITECTURE_WORKFLOW) {
|
|
2675
3580
|
const comparison = await inspectArchitectureComparisonRecord(runDir, runId, includeResult);
|
|
2676
3581
|
const { result, ...status } = comparison;
|
|
@@ -2681,6 +3586,16 @@ async function executeWorkflowRunStatus(options, args) {
|
|
|
2681
3586
|
else
|
|
2682
3587
|
delete projection["result"];
|
|
2683
3588
|
}
|
|
3589
|
+
if (state.workflowName === ARENA_WORKFLOW) {
|
|
3590
|
+
const comparison = await inspectArchitectureArenaRecord(runDir, runId, includeResult);
|
|
3591
|
+
const { result, ...status } = comparison;
|
|
3592
|
+
projection["comparison"] = status;
|
|
3593
|
+
projection["result_available"] = status["status"] === "complete" || status["status"] === "incomplete";
|
|
3594
|
+
if (result !== undefined)
|
|
3595
|
+
projection["result"] = result;
|
|
3596
|
+
else
|
|
3597
|
+
delete projection["result"];
|
|
3598
|
+
}
|
|
2684
3599
|
if (state.workflowName === VERIFIED_REPAIR_WORKFLOW) {
|
|
2685
3600
|
let inspected = await inspectVerifiedRepairRecord(runDir, runId, includeResult);
|
|
2686
3601
|
if (inspected.availability === "unrecorded" && lock === "stale_or_absent" && !activeRuns.has(runId)) {
|
|
@@ -2716,7 +3631,7 @@ async function executeWorkflowRunStatus(options, args) {
|
|
|
2716
3631
|
content: [{ type: "text", text: JSON.stringify(projection) }],
|
|
2717
3632
|
};
|
|
2718
3633
|
}
|
|
2719
|
-
async function executeCancelWorkflow(
|
|
3634
|
+
async function executeCancelWorkflow(options, args) {
|
|
2720
3635
|
const runId = args["run_id"];
|
|
2721
3636
|
if (typeof runId !== "string" || runId === "") {
|
|
2722
3637
|
throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid "run_id" parameter');
|
|
@@ -2739,6 +3654,13 @@ async function executeCancelWorkflow(_options, args) {
|
|
|
2739
3654
|
// controller is still in the registry (deleted only in the run's finally).
|
|
2740
3655
|
// Re-read first so we never claim "cancelling" for an already-done run.
|
|
2741
3656
|
const live = await readRunStateForStatus(runId);
|
|
3657
|
+
if (live != null && live.state.workflowName === PING_PONG_WORKFLOW && live.state.status === "succeeded" &&
|
|
3658
|
+
activeRuns.has(runId)) {
|
|
3659
|
+
// A control owner (decide or paused cancel) holds a paused recipe run:
|
|
3660
|
+
// its outcome is not yet known, so the caller must retry, never read a
|
|
3661
|
+
// stale pause as terminal.
|
|
3662
|
+
return text({ run_id: runId, status: "running", cancellable: false, reason: "run_busy", retryable: true });
|
|
3663
|
+
}
|
|
2742
3664
|
if (live != null && live.state.status !== "running" && live.state.status !== "pending") {
|
|
2743
3665
|
return text({ run_id: runId, status: live.state.status, already_terminal: true });
|
|
2744
3666
|
}
|
|
@@ -2754,6 +3676,16 @@ async function executeCancelWorkflow(_options, args) {
|
|
|
2754
3676
|
}
|
|
2755
3677
|
const { state, lock } = read;
|
|
2756
3678
|
if (state.status !== "running" && state.status !== "pending") {
|
|
3679
|
+
if (state.workflowName === PING_PONG_WORKFLOW && state.status === "succeeded") {
|
|
3680
|
+
const recipe = await readRecipeState(getRunStateDir(runId));
|
|
3681
|
+
if (recipe.kind === "read" && recipe.state.phase === "awaiting_decision") {
|
|
3682
|
+
const paused = await cancelPausedRecipeRun(options, runId);
|
|
3683
|
+
if (paused !== undefined)
|
|
3684
|
+
return text(paused);
|
|
3685
|
+
const reread = await readRunStateForStatus(runId);
|
|
3686
|
+
return text({ run_id: runId, status: reread?.state.status ?? state.status, already_terminal: true });
|
|
3687
|
+
}
|
|
3688
|
+
}
|
|
2757
3689
|
return text({ run_id: runId, status: state.status, already_terminal: true });
|
|
2758
3690
|
}
|
|
2759
3691
|
if (lock === "unknown") {
|
|
@@ -2769,10 +3701,29 @@ async function executeCancelWorkflow(_options, args) {
|
|
|
2769
3701
|
// of truth for ownership: reapRunCancelled acquires it itself (reclaiming a
|
|
2770
3702
|
// truly stale/dead lock, refusing a live one), closing the TOCTOU where a
|
|
2771
3703
|
// concurrent resume_workflow could grab the lock between read and reap.
|
|
2772
|
-
|
|
3704
|
+
// Recipe orphans record their unresolved operations under the same lock
|
|
3705
|
+
// before the terminal write (CONTRACTS 0-7); other runs are unchanged.
|
|
3706
|
+
const outcome = state.workflowName === PING_PONG_WORKFLOW
|
|
3707
|
+
? await reapRunCancelled(runId, { beforeWrite: recordRecipeOrphanCancel, fileWriter: options.fileWriter })
|
|
3708
|
+
: await reapRunCancelled(runId, { fileWriter: options.fileWriter });
|
|
2773
3709
|
if (outcome === "cancelled") {
|
|
2774
3710
|
return text({ run_id: runId, status: "cancelled", reaped: true });
|
|
2775
3711
|
}
|
|
3712
|
+
if (outcome === "settled") {
|
|
3713
|
+
// The orphan's own execution had already committed a terminal recipe
|
|
3714
|
+
// outcome; that outcome, not the cancel, decided its status (D1).
|
|
3715
|
+
const settled = await readRunStateForStatus(runId);
|
|
3716
|
+
return text({ run_id: runId, status: settled?.state.status ?? "unknown", reaped: true, settled_by: "recipe_state" });
|
|
3717
|
+
}
|
|
3718
|
+
if (outcome === "recipe_state_unavailable") {
|
|
3719
|
+
return text({
|
|
3720
|
+
run_id: runId,
|
|
3721
|
+
status: state.status,
|
|
3722
|
+
cancellable: false,
|
|
3723
|
+
recipe_state: "unavailable",
|
|
3724
|
+
error: `The recipe-state.json of run_id "${runId}" could not be read or its terminal cancel could not be recorded; nothing was written. Repair or inspect recipe-state.json and the run's worktrees, then retry.`,
|
|
3725
|
+
});
|
|
3726
|
+
}
|
|
2776
3727
|
if (outcome === "locked") {
|
|
2777
3728
|
// The run is owned by another live worker (or a blocking run): the lock
|
|
2778
3729
|
// could not be acquired. Refuse without mutating — this process cannot
|
|
@@ -2802,17 +3753,22 @@ function executeListWorkflows(options) {
|
|
|
2802
3753
|
const effectiveContextDefault = resolveWorkflowContextMode(undefined, contextDefault, preflightEnabled, undefined, options.defaultCurator).effectiveMode;
|
|
2803
3754
|
const entries = [];
|
|
2804
3755
|
for (const [name, entry] of workflows) {
|
|
3756
|
+
const rootOnly = isRootOnlyWorkflow(name);
|
|
3757
|
+
// Without the root recipe host run_workflow rejects it; keep it out of discovery.
|
|
3758
|
+
if (rootOnly && options.recipeHost === undefined)
|
|
3759
|
+
continue;
|
|
2805
3760
|
const def = entry.definition;
|
|
2806
3761
|
const contextStrategy = deriveContextStrategy(def);
|
|
2807
3762
|
const runtimeMembers = supportsRuntimeMembers(name);
|
|
3763
|
+
const recipeRules = isRecipeSeatWorkflow(name) ? RECIPE_SEAT_RULES[name] : undefined;
|
|
2808
3764
|
entries.push({
|
|
2809
3765
|
name,
|
|
2810
3766
|
description: def.description,
|
|
2811
3767
|
version: def.version,
|
|
2812
3768
|
source: entry.source,
|
|
2813
3769
|
shadowed_yaml: entry.shadowedYaml,
|
|
2814
|
-
supports_members:
|
|
2815
|
-
supports_chairman:
|
|
3770
|
+
supports_members: supportsSeatMembers(name),
|
|
3771
|
+
supports_chairman: supportsSeatChairman(name),
|
|
2816
3772
|
supports_context_preflight: contextStrategy.supports_context_preflight,
|
|
2817
3773
|
effective_context_default: name === VERIFIED_REPAIR_WORKFLOW ? "disabled" : effectiveContextDefault,
|
|
2818
3774
|
fails_on_empty_selection: contextStrategy.fails_on_empty_selection,
|
|
@@ -2827,6 +3783,12 @@ function executeListWorkflows(options) {
|
|
|
2827
3783
|
members_max: 10,
|
|
2828
3784
|
members_stance_required_from_index: 3,
|
|
2829
3785
|
} : {}),
|
|
3786
|
+
...(recipeRules !== undefined ? {
|
|
3787
|
+
members_min: recipeRules.membersMin,
|
|
3788
|
+
members_max: recipeRules.membersMax,
|
|
3789
|
+
} : {}),
|
|
3790
|
+
...(isAsyncOnlyWorkflow(name) ? { async_only: true } : {}),
|
|
3791
|
+
...(rootOnly ? { root_only: true } : {}),
|
|
2830
3792
|
...(entry.path != null ? { path: basename(entry.path) } : {}),
|
|
2831
3793
|
...(name === PLAN_REVIEW_RECEIPTS_WORKFLOW
|
|
2832
3794
|
? {
|
|
@@ -3028,7 +3990,7 @@ const RUN_WORKFLOW_SCHEMA = {
|
|
|
3028
3990
|
async: {
|
|
3029
3991
|
type: "boolean",
|
|
3030
3992
|
default: false,
|
|
3031
|
-
description: "When true, start
|
|
3993
|
+
description: "When true, start detached and return {run_id, execution_id, status:'running'} immediately. Prefer workflow_run_wait for local completion, then workflow_run_status with expected_execution_id and include_result:true; status polling remains available for recovery. When false (blocking), the final content block carries execution_id once the run owned state.",
|
|
3032
3994
|
},
|
|
3033
3995
|
roster: {
|
|
3034
3996
|
type: "string",
|
|
@@ -3038,7 +4000,7 @@ const RUN_WORKFLOW_SCHEMA = {
|
|
|
3038
4000
|
},
|
|
3039
4001
|
members: {
|
|
3040
4002
|
type: "array",
|
|
3041
|
-
description: "Optional runtime council member composition override. Accepted
|
|
4003
|
+
description: "Optional runtime council member composition override. Accepted for council workflows (council-default, council-answer, council-code-review, council-debug, council-discover, council-plan-review). Each entry specifies a CLI adapter, an optional analytical stance, and optional requested model/effort values whose support is adapter-declared. Seats at indices 0-2 may omit stance (inherits default); seats at indices 3-9 MUST provide stance. When provided, both the member stage (stage 0) and reviewer stage (stage 1) are expanded to match the specified count and CLI mapping. Reviewer stances are NOT inherited — reviewers keep their default review lens. Also accepted (and required) for recipe workflows, which map seats without stage expansion and never require stance: architecture-arena (2-4 authors; stance = exploration direction) and ping-pong (members[0] implementer, members[1..] reviewers; 2-5; stance is rejected on every ping-pong seat). Recipe workflows reject roster.",
|
|
3042
4004
|
minItems: 1,
|
|
3043
4005
|
maxItems: 10,
|
|
3044
4006
|
items: {
|
|
@@ -3073,7 +4035,7 @@ const RUN_WORKFLOW_SCHEMA = {
|
|
|
3073
4035
|
},
|
|
3074
4036
|
chairman: {
|
|
3075
4037
|
type: "string",
|
|
3076
|
-
description: "Optional CLI adapter name override for the council chairman seat. Accepted
|
|
4038
|
+
description: "Optional CLI adapter name override for the council chairman seat. Accepted for council workflows and for the recipe workflow architecture-arena (judge); rejected for ping-pong. A recipe without a workflow default chairman requires it. Only changes the LLM adapter; the chairman's role and prompt template are preserved.",
|
|
3077
4039
|
},
|
|
3078
4040
|
chairman_model: {
|
|
3079
4041
|
type: "string",
|
|
@@ -3121,6 +4083,12 @@ const LIST_WORKFLOWS_SCHEMA = {
|
|
|
3121
4083
|
properties: {},
|
|
3122
4084
|
additionalProperties: false,
|
|
3123
4085
|
};
|
|
4086
|
+
const EXECUTION_ID_SCHEMA = {
|
|
4087
|
+
type: "string",
|
|
4088
|
+
minLength: 1,
|
|
4089
|
+
maxLength: 128,
|
|
4090
|
+
description: "Opaque execution identity (also persisted in run state) returned by run_workflow (async ack or trailing sync block), resume_workflow, or a bare wait. A fence, not a capability: it grants nothing and only makes reads fail closed (identity_changed/identity_unavailable) if they would observe a different execution.",
|
|
4091
|
+
};
|
|
3124
4092
|
const WORKFLOW_RUN_STATUS_SCHEMA = {
|
|
3125
4093
|
type: "object",
|
|
3126
4094
|
properties: {
|
|
@@ -3128,6 +4096,7 @@ const WORKFLOW_RUN_STATUS_SCHEMA = {
|
|
|
3128
4096
|
type: "string",
|
|
3129
4097
|
pattern: "^[A-Za-z0-9_-]{1,64}$",
|
|
3130
4098
|
},
|
|
4099
|
+
expected_execution_id: EXECUTION_ID_SCHEMA,
|
|
3131
4100
|
include_result: {
|
|
3132
4101
|
type: "boolean",
|
|
3133
4102
|
default: false,
|
|
@@ -3137,6 +4106,15 @@ const WORKFLOW_RUN_STATUS_SCHEMA = {
|
|
|
3137
4106
|
required: ["run_id"],
|
|
3138
4107
|
additionalProperties: false,
|
|
3139
4108
|
};
|
|
4109
|
+
const WORKFLOW_RUN_WAIT_SCHEMA = {
|
|
4110
|
+
type: "object",
|
|
4111
|
+
properties: {
|
|
4112
|
+
run_id: { type: "string", pattern: "^[A-Za-z0-9_-]{1,64}$" },
|
|
4113
|
+
expected_execution_id: EXECUTION_ID_SCHEMA,
|
|
4114
|
+
},
|
|
4115
|
+
required: ["run_id"],
|
|
4116
|
+
additionalProperties: false,
|
|
4117
|
+
};
|
|
3140
4118
|
const CANCEL_WORKFLOW_SCHEMA = {
|
|
3141
4119
|
type: "object",
|
|
3142
4120
|
properties: {
|
|
@@ -3148,6 +4126,64 @@ const CANCEL_WORKFLOW_SCHEMA = {
|
|
|
3148
4126
|
required: ["run_id"],
|
|
3149
4127
|
additionalProperties: false,
|
|
3150
4128
|
};
|
|
4129
|
+
const FINDING_ID_JSON_PATTERN = "^R[1-8]-S[1-4]-([1-9]|1[0-9]|2[0-4])$";
|
|
4130
|
+
const RECIPE_DECIDE_SCHEMA = {
|
|
4131
|
+
type: "object",
|
|
4132
|
+
properties: {
|
|
4133
|
+
run_id: { type: "string", pattern: "^[A-Za-z0-9_-]{1,64}$" },
|
|
4134
|
+
execution_id: {
|
|
4135
|
+
type: "string",
|
|
4136
|
+
minLength: 1,
|
|
4137
|
+
maxLength: 128,
|
|
4138
|
+
description: "The execution that published the pause (recipe.execution_id in workflow_run_status).",
|
|
4139
|
+
},
|
|
4140
|
+
revision: {
|
|
4141
|
+
type: "integer",
|
|
4142
|
+
minimum: 1,
|
|
4143
|
+
description: "The paused sidecar revision (recipe.revision in workflow_run_status).",
|
|
4144
|
+
},
|
|
4145
|
+
decision: {
|
|
4146
|
+
type: "object",
|
|
4147
|
+
properties: {
|
|
4148
|
+
admit: {
|
|
4149
|
+
type: "array",
|
|
4150
|
+
maxItems: PP_MAX_FINDINGS_PER_ROUND,
|
|
4151
|
+
items: {
|
|
4152
|
+
type: "object",
|
|
4153
|
+
properties: {
|
|
4154
|
+
id: { type: "string", pattern: FINDING_ID_JSON_PATTERN },
|
|
4155
|
+
rationale: { type: "string", minLength: 1, maxLength: PP_MAX_NOTE_CHARS },
|
|
4156
|
+
},
|
|
4157
|
+
required: ["id", "rationale"],
|
|
4158
|
+
additionalProperties: false,
|
|
4159
|
+
},
|
|
4160
|
+
},
|
|
4161
|
+
reject: {
|
|
4162
|
+
type: "array",
|
|
4163
|
+
maxItems: PP_MAX_FINDINGS_PER_ROUND,
|
|
4164
|
+
items: {
|
|
4165
|
+
type: "object",
|
|
4166
|
+
properties: {
|
|
4167
|
+
id: { type: "string", pattern: FINDING_ID_JSON_PATTERN },
|
|
4168
|
+
reason: { type: "string", minLength: 1, maxLength: PP_MAX_NOTE_CHARS },
|
|
4169
|
+
},
|
|
4170
|
+
required: ["id", "reason"],
|
|
4171
|
+
additionalProperties: false,
|
|
4172
|
+
},
|
|
4173
|
+
},
|
|
4174
|
+
audit_requests: {
|
|
4175
|
+
type: "array",
|
|
4176
|
+
maxItems: PP_MAX_AUDIT_REQUESTS,
|
|
4177
|
+
items: { type: "string", minLength: 1, maxLength: PP_MAX_NOTE_CHARS },
|
|
4178
|
+
},
|
|
4179
|
+
stop: { type: "boolean", default: false },
|
|
4180
|
+
},
|
|
4181
|
+
additionalProperties: false,
|
|
4182
|
+
},
|
|
4183
|
+
},
|
|
4184
|
+
required: ["run_id", "execution_id", "revision", "decision"],
|
|
4185
|
+
additionalProperties: false,
|
|
4186
|
+
};
|
|
3151
4187
|
/**
|
|
3152
4188
|
* Return the workflow tool definitions for tools/list.
|
|
3153
4189
|
*
|
|
@@ -3248,13 +4284,14 @@ export function getWorkflowToolDefinitions(workflowsPath, availableCliNames) {
|
|
|
3248
4284
|
return [
|
|
3249
4285
|
{
|
|
3250
4286
|
name: "run_workflow",
|
|
3251
|
-
description: `Start a new multi-stage workflow execution.${workflowSuffix}\nAccepts optional \`members\` and \`chairman\` parameters for council workflows (council-default, council-answer, council-code-review, council-debug, council-discover, council-plan-review) to override member/reviewer composition and chairman CLI adapter at runtime. Council runs include a \`resolved_roster\` of requested seat and delegate values (no provenance) on the async ack, a trailing sync content block, and workflow_run_status.`,
|
|
4287
|
+
description: `Start a new multi-stage workflow execution.${workflowSuffix}\nAccepts optional \`members\` and \`chairman\` parameters for council workflows (council-default, council-answer, council-code-review, council-debug, council-discover, council-plan-review) to override member/reviewer composition and chairman CLI adapter at runtime, and for the recipe workflows architecture-arena and ping-pong (root server only, async:true) to name their seats (see members). Council and recipe runs include a \`resolved_roster\` of requested seat and delegate values (no provenance) on the async ack, a trailing sync content block, and workflow_run_status. Blocking runs end with one trailing identity block {resolved_roster?, execution_id?}; execution_id is present once the run owned state, absent when rejected before that.`,
|
|
3252
4288
|
inputSchema: runSchema,
|
|
3253
4289
|
},
|
|
3254
4290
|
{
|
|
3255
4291
|
name: "resume_workflow",
|
|
3256
4292
|
description: "Resume a previously failed or cancelled workflow from its last checkpoint. " +
|
|
3257
|
-
"Requires the original run_id and matching child config."
|
|
4293
|
+
"Requires the original run_id and matching child config. " +
|
|
4294
|
+
"Once the resume owns the run, the final content block is {execution_id} for this attempt; pin workflow_run_wait/workflow_run_status to it. A resume rejected before then returns no execution_id and leaves the previous execution observable.",
|
|
3258
4295
|
inputSchema: RESUME_WORKFLOW_SCHEMA,
|
|
3259
4296
|
},
|
|
3260
4297
|
{
|
|
@@ -3265,16 +4302,30 @@ export function getWorkflowToolDefinitions(workflowsPath, availableCliNames) {
|
|
|
3265
4302
|
},
|
|
3266
4303
|
{
|
|
3267
4304
|
name: "workflow_run_status",
|
|
3268
|
-
description: "Read-only status/progress of a workflow run. The full result is included only with include_result:true. Generic workflows preserve succeeded-final-call behavior; plan-review-receipts reports marker-driven availability and bytes independently of terminal status, with body-blind default polling. Every found run also carries a top-level `health` block {classification: \"ok\"|\"degraded\", reasons: string[]} computed read-time from persisted data — a run can be status:\"succeeded\" yet degraded when on_failure:continue swallowed failed calls or context preflight was partial/degraded (reasons: failed_calls_in_succeeded_run, context_partial, context_lifecycle_failed, coverage_degraded, delegate_fallback_used, context_external_gaps — the finalizer reported evidence gaps outside the delegate packet under external_gap_policy:\"degrade\", so conclusions depending on them are conditional). When a context-builder lifecycle snapshot is persisted, the `context` block additionally includes `lifecycle_status` and `coverage` {policy, status, required, selected, missing}. A parsed snapshot also projects `context.delegate.finalizer` {effective_enabled, execution_status, score?}; `score` is present only for a succeeded finalizer that recorded one, and the finalizer key is omitted when the lifecycle is missing, unparseable, or those fields are absent. While context preflight is still running (non-terminal lifecycle, no committed context yet) the `context` block is absent and a top-level `context_progress` {phase, status, updated_at, counts} reports scan progress instead. Found council runs also include a top-level `resolved_roster` of requested seat and delegate values (no provenance) when the run persisted one; older runs omit the key. Architecture comparisons additionally project comparison completeness and retained record availability independently of run execution status. Every found run has a separately versioned verification projection of historical inspected-at evidence; it establishes neither current source/runtime applicability nor owner acceptance.",
|
|
4305
|
+
description: "Read-only status/progress of a workflow run. The full result is included only with include_result:true. Generic workflows preserve succeeded-final-call behavior; plan-review-receipts reports marker-driven availability and bytes independently of terminal status, with body-blind default polling. Every found run also carries a top-level `health` block {classification: \"ok\"|\"degraded\", reasons: string[]} computed read-time from persisted data — a run can be status:\"succeeded\" yet degraded when on_failure:continue swallowed failed calls or context preflight was partial/degraded (reasons: failed_calls_in_succeeded_run, context_partial, context_lifecycle_failed, coverage_degraded, delegate_fallback_used, context_external_gaps — the finalizer reported evidence gaps outside the delegate packet under external_gap_policy:\"degrade\", so conclusions depending on them are conditional). When a context-builder lifecycle snapshot is persisted, the `context` block additionally includes `lifecycle_status` and `coverage` {policy, status, required, selected, missing}. A parsed snapshot also projects `context.delegate.finalizer` {effective_enabled, execution_status, score?}; `score` is present only for a succeeded finalizer that recorded one, and the finalizer key is omitted when the lifecycle is missing, unparseable, or those fields are absent. While context preflight is still running (non-terminal lifecycle, no committed context yet) the `context` block is absent and a top-level `context_progress` {phase, status, updated_at, counts} reports scan progress instead. Found council runs also include a top-level `resolved_roster` of requested seat and delegate values (no provenance) when the run persisted one; older runs omit the key. Architecture comparisons additionally project comparison completeness and retained record availability independently of run execution status. Every found run has a separately versioned verification projection of historical inspected-at evidence; it establishes neither current source/runtime applicability nor owner acceptance. With expected_execution_id the response is fenced to that execution: a mismatch is isError {run_id, error:\"identity_changed\"|\"identity_unavailable\"} with no result, and an active execution whose state kept changing through every bounded reread is isError {run_id, error:\"state_read_unstable\"} — retryable; re-issue the same pinned call after a short backoff.",
|
|
3269
4306
|
inputSchema: WORKFLOW_RUN_STATUS_SCHEMA,
|
|
3270
4307
|
annotations: { readOnlyHint: true },
|
|
3271
4308
|
},
|
|
4309
|
+
{
|
|
4310
|
+
name: "workflow_run_wait",
|
|
4311
|
+
description: "Observe one local workflow execution through its cleanup fence for at most 30 seconds. Returns metadata status plus wait.outcome and execution_id; wait.budget_ms is the configured budget, not the time waited (see elapsed_ms). Re-arm budget_elapsed with the same identity; a persistently unstable state read on an active execution also re-arms as budget_elapsed, without projection. not_owned, orphaned and not_found return immediately: no local execution is witnessable here yet or any longer (a request still admitting has not bound one). expected_execution_id is a fence, not a capability. The settled fingerprint covers state.json bytes only, not result files. Cancellation detaches observation only. Unpinned foreign/historical state is not witnessed settlement; a pin whose execution reached terminal state settles from persisted state (e.g. after a restart). Fetch final results via workflow_run_status with expected_execution_id (it may return the retryable error state_read_unstable for an active execution; re-issue the same pinned call).",
|
|
4312
|
+
inputSchema: WORKFLOW_RUN_WAIT_SCHEMA,
|
|
4313
|
+
annotations: { readOnlyHint: true },
|
|
4314
|
+
},
|
|
3272
4315
|
{
|
|
3273
4316
|
name: "cancel_workflow",
|
|
3274
|
-
description: "Cancel a workflow run by run_id. Aborts a live in-process async run (returns status:'cancelling'; poll workflow_run_status until it reaches terminal 'cancelled'). Reaps an orphaned/no-live-worker run to terminal 'cancelled' (reaped:true). Refuses a lock-held run owned by another live worker or a blocking run (cancellable:false). Idempotent; not_found and already_terminal are soft results.",
|
|
4317
|
+
description: "Cancel a workflow run by run_id. Aborts a live in-process async run (returns status:'cancelling'; poll workflow_run_status until it reaches a terminal status, usually 'cancelled'). Reaps an orphaned/no-live-worker run to terminal 'cancelled' (reaped:true). Refuses a lock-held run owned by another live worker or a blocking run (cancellable:false). Idempotent; not_found and already_terminal are soft results. Recipe runs (ping-pong): the first committed terminal outcome wins, so a cancel that arrives after the execution already recorded its outcome settles with that outcome's status: a 'cancelling' run may end 'succeeded' (or 'failed'), and an orphan reap may report it with settled_by:'recipe_state'. An orphan whose recipe-state.json is unreadable is refused with recipe_state:'unavailable' and left unchanged.",
|
|
3275
4318
|
inputSchema: CANCEL_WORKFLOW_SCHEMA,
|
|
3276
4319
|
annotations: { destructiveHint: true },
|
|
3277
4320
|
},
|
|
4321
|
+
{
|
|
4322
|
+
name: RECIPE_DECIDE_TOOL,
|
|
4323
|
+
description: "Decide a paused ping-pong recipe run (recipe.awaiting_decision in workflow_run_status). Bind the call to the pausing execution_id and recipe revision, and list every pending finding id exactly once across admit[{id, rationale}] and reject[{id, reason}] (<= 300 chars each); optional audit_requests (<= 3) go to the next review packet; stop:true ends the run and may leave pending ids unlisted (recorded as unresolved findings). A decision at or past the run's deadline_at (status recipe.deadline_expired) stops it deadline_exceeded, whether or not it is complete. Admitted findings start the next remediation round while rounds remain; no admits with every reviewer signed off starts final verification; otherwise the run stops with a closed stop_reason. Returns {run_id, execution_id, revision, phase, outcome?, stop_reason?, replayed}: the NEW execution to pin workflow_run_wait/status to. Repeating the same decision returns the stored receipt with replayed:true; a different decision for the same execution/revision is rejected (conflicting_decision), as are stale, incomplete and not-awaiting decisions (-32602). A run that is still active is a retryable InvalidRequest (run_busy). Finding text in status is untrusted data. Root server only.",
|
|
4324
|
+
inputSchema: RECIPE_DECIDE_SCHEMA,
|
|
4325
|
+
// Destructive: it rewrites the paused run's state and sidecar as a new
|
|
4326
|
+
// execution (MCP's false means additive-only). Idempotent via replay.
|
|
4327
|
+
annotations: { destructiveHint: true, idempotentHint: true },
|
|
4328
|
+
},
|
|
3278
4329
|
];
|
|
3279
4330
|
}
|
|
3280
4331
|
/** Names of the workflow tools (for dispatch matching). */
|
|
@@ -3283,7 +4334,9 @@ export const WORKFLOW_TOOL_NAMES = new Set([
|
|
|
3283
4334
|
"resume_workflow",
|
|
3284
4335
|
"list_workflows",
|
|
3285
4336
|
"workflow_run_status",
|
|
4337
|
+
"workflow_run_wait",
|
|
3286
4338
|
"cancel_workflow",
|
|
4339
|
+
RECIPE_DECIDE_TOOL,
|
|
3287
4340
|
]);
|
|
3288
4341
|
/**
|
|
3289
4342
|
* Dispatch a workflow tool call.
|
|
@@ -3301,8 +4354,12 @@ export async function handleWorkflowToolCall(server, options, name, args, signal
|
|
|
3301
4354
|
return executeListWorkflows(options);
|
|
3302
4355
|
case "workflow_run_status":
|
|
3303
4356
|
return await executeWorkflowRunStatus(options, args);
|
|
4357
|
+
case "workflow_run_wait":
|
|
4358
|
+
return await executeWorkflowRunWait(options, args, signal);
|
|
3304
4359
|
case "cancel_workflow":
|
|
3305
4360
|
return await executeCancelWorkflow(options, args);
|
|
4361
|
+
case RECIPE_DECIDE_TOOL:
|
|
4362
|
+
return await executeRecipeDecide(options, args);
|
|
3306
4363
|
default:
|
|
3307
4364
|
return null;
|
|
3308
4365
|
}
|
|
@@ -3314,8 +4371,9 @@ export async function handleWorkflowToolCall(server, options, name, args, signal
|
|
|
3314
4371
|
* Register workflow tools on an MCP Server instance.
|
|
3315
4372
|
*
|
|
3316
4373
|
* This is the reusable core extracted from createWorkflowServer().
|
|
3317
|
-
* It registers
|
|
3318
|
-
* workflow_run_status, cancel_workflow
|
|
4374
|
+
* It registers seven tools: run_workflow, resume_workflow, list_workflows,
|
|
4375
|
+
* workflow_run_status, workflow_run_wait, cancel_workflow,
|
|
4376
|
+
* workflow_recipe_decide.
|
|
3319
4377
|
*
|
|
3320
4378
|
* The `options.createBackend` factory determines how clink calls are
|
|
3321
4379
|
* dispatched — callers provide either a child-process or in-process backend.
|