clinkx 1.2.0 → 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.
Files changed (270) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +4 -2
  3. package/clinkx-workflows/dist/architecture-arena/admission.d.ts +16 -0
  4. package/clinkx-workflows/dist/architecture-arena/admission.js +107 -0
  5. package/clinkx-workflows/dist/architecture-arena/admission.js.map +1 -0
  6. package/clinkx-workflows/dist/architecture-arena/contract.d.ts +1368 -0
  7. package/clinkx-workflows/dist/architecture-arena/contract.js +254 -0
  8. package/clinkx-workflows/dist/architecture-arena/contract.js.map +1 -0
  9. package/clinkx-workflows/dist/architecture-arena/runtime.d.ts +53 -0
  10. package/clinkx-workflows/dist/architecture-arena/runtime.js +511 -0
  11. package/clinkx-workflows/dist/architecture-arena/runtime.js.map +1 -0
  12. package/clinkx-workflows/dist/architecture-comparison/admission.d.ts +17 -1
  13. package/clinkx-workflows/dist/architecture-comparison/admission.js +27 -4
  14. package/clinkx-workflows/dist/architecture-comparison/admission.js.map +1 -1
  15. package/clinkx-workflows/dist/architecture-comparison/contract.d.ts +59 -62
  16. package/clinkx-workflows/dist/architecture-comparison/contract.js +4 -21
  17. package/clinkx-workflows/dist/architecture-comparison/contract.js.map +1 -1
  18. package/clinkx-workflows/dist/architecture-comparison/runtime.d.ts +4 -3
  19. package/clinkx-workflows/dist/architecture-comparison/runtime.js +22 -67
  20. package/clinkx-workflows/dist/architecture-comparison/runtime.js.map +1 -1
  21. package/clinkx-workflows/dist/artifacts.d.ts +19 -4
  22. package/clinkx-workflows/dist/artifacts.js +16 -7
  23. package/clinkx-workflows/dist/artifacts.js.map +1 -1
  24. package/clinkx-workflows/dist/backend.d.ts +30 -0
  25. package/clinkx-workflows/dist/clink-client.d.ts +8 -2
  26. package/clinkx-workflows/dist/clink-client.js +4 -2
  27. package/clinkx-workflows/dist/clink-client.js.map +1 -1
  28. package/clinkx-workflows/dist/context-preflight.d.ts +6 -0
  29. package/clinkx-workflows/dist/context-preflight.js.map +1 -1
  30. package/clinkx-workflows/dist/council-execution-policy.d.ts +3 -1
  31. package/clinkx-workflows/dist/council-execution-policy.js +4 -0
  32. package/clinkx-workflows/dist/council-execution-policy.js.map +1 -1
  33. package/clinkx-workflows/dist/dashboard/contracts.d.ts +586 -586
  34. package/clinkx-workflows/dist/dashboard/progress-report-contract.d.ts +28 -28
  35. package/clinkx-workflows/dist/dashboard/session-log-contract.d.ts +32 -32
  36. package/clinkx-workflows/dist/dashboard-ui/assets/index-DRId2DVA.js +119 -0
  37. package/clinkx-workflows/dist/dashboard-ui/assets/style-CHAw57y5.css +1 -0
  38. package/clinkx-workflows/dist/dashboard-ui/index.html +2 -2
  39. package/clinkx-workflows/dist/delegate-signature.d.ts +4 -3
  40. package/clinkx-workflows/dist/delegate-signature.js +4 -3
  41. package/clinkx-workflows/dist/delegate-signature.js.map +1 -1
  42. package/clinkx-workflows/dist/durable-file.d.ts +69 -0
  43. package/clinkx-workflows/dist/durable-file.js +145 -0
  44. package/clinkx-workflows/dist/durable-file.js.map +1 -0
  45. package/clinkx-workflows/dist/engine.d.ts +42 -7
  46. package/clinkx-workflows/dist/engine.js +196 -24
  47. package/clinkx-workflows/dist/engine.js.map +1 -1
  48. package/clinkx-workflows/dist/ping-pong/admission.d.ts +127 -0
  49. package/clinkx-workflows/dist/ping-pong/admission.js +522 -0
  50. package/clinkx-workflows/dist/ping-pong/admission.js.map +1 -0
  51. package/clinkx-workflows/dist/ping-pong/contract.d.ts +2539 -0
  52. package/clinkx-workflows/dist/ping-pong/contract.js +819 -0
  53. package/clinkx-workflows/dist/ping-pong/contract.js.map +1 -0
  54. package/clinkx-workflows/dist/ping-pong/control.d.ts +67 -0
  55. package/clinkx-workflows/dist/ping-pong/control.js +12 -0
  56. package/clinkx-workflows/dist/ping-pong/control.js.map +1 -0
  57. package/clinkx-workflows/dist/ping-pong/runtime-handle.d.ts +24 -0
  58. package/clinkx-workflows/dist/ping-pong/runtime-handle.js +55 -0
  59. package/clinkx-workflows/dist/ping-pong/runtime-handle.js.map +1 -0
  60. package/clinkx-workflows/dist/ping-pong/runtime.d.ts +235 -0
  61. package/clinkx-workflows/dist/ping-pong/runtime.js +1183 -0
  62. package/clinkx-workflows/dist/ping-pong/runtime.js.map +1 -0
  63. package/clinkx-workflows/dist/ping-pong/settle.d.ts +57 -0
  64. package/clinkx-workflows/dist/ping-pong/settle.js +58 -0
  65. package/clinkx-workflows/dist/ping-pong/settle.js.map +1 -0
  66. package/clinkx-workflows/dist/ping-pong/sidecar.d.ts +65 -0
  67. package/clinkx-workflows/dist/ping-pong/sidecar.js +138 -0
  68. package/clinkx-workflows/dist/ping-pong/sidecar.js.map +1 -0
  69. package/clinkx-workflows/dist/plan-review/publication.d.ts +2 -1
  70. package/clinkx-workflows/dist/plan-review/publication.js +5 -6
  71. package/clinkx-workflows/dist/plan-review/publication.js.map +1 -1
  72. package/clinkx-workflows/dist/plan-review/snapshot.d.ts +3 -2
  73. package/clinkx-workflows/dist/plan-review/snapshot.js +8 -8
  74. package/clinkx-workflows/dist/plan-review/snapshot.js.map +1 -1
  75. package/clinkx-workflows/dist/recipe-host.d.ts +315 -0
  76. package/clinkx-workflows/dist/recipe-host.js +183 -0
  77. package/clinkx-workflows/dist/recipe-host.js.map +1 -0
  78. package/clinkx-workflows/dist/recipe-seats.d.ts +96 -0
  79. package/clinkx-workflows/dist/recipe-seats.js +163 -0
  80. package/clinkx-workflows/dist/recipe-seats.js.map +1 -0
  81. package/clinkx-workflows/dist/recipe-shared/evidence.d.ts +67 -0
  82. package/clinkx-workflows/dist/recipe-shared/evidence.js +111 -0
  83. package/clinkx-workflows/dist/recipe-shared/evidence.js.map +1 -0
  84. package/clinkx-workflows/dist/reducers/index.d.ts +9 -1
  85. package/clinkx-workflows/dist/reducers/index.js +30 -0
  86. package/clinkx-workflows/dist/reducers/index.js.map +1 -1
  87. package/clinkx-workflows/dist/run-lock-reclaim.d.ts +44 -0
  88. package/clinkx-workflows/dist/run-lock-reclaim.js +86 -0
  89. package/clinkx-workflows/dist/run-lock-reclaim.js.map +1 -0
  90. package/clinkx-workflows/dist/state-schema.d.ts +11 -0
  91. package/clinkx-workflows/dist/state-schema.js +4 -1
  92. package/clinkx-workflows/dist/state-schema.js.map +1 -1
  93. package/clinkx-workflows/dist/state.d.ts +178 -3
  94. package/clinkx-workflows/dist/state.js +618 -83
  95. package/clinkx-workflows/dist/state.js.map +1 -1
  96. package/clinkx-workflows/dist/transport.d.ts +2 -1
  97. package/clinkx-workflows/dist/transport.js +5 -0
  98. package/clinkx-workflows/dist/transport.js.map +1 -1
  99. package/clinkx-workflows/dist/validators/architecture-arena.d.ts +6 -0
  100. package/clinkx-workflows/dist/validators/architecture-arena.js +16 -0
  101. package/clinkx-workflows/dist/validators/architecture-arena.js.map +1 -0
  102. package/clinkx-workflows/dist/validators/index.js +4 -0
  103. package/clinkx-workflows/dist/validators/index.js.map +1 -1
  104. package/clinkx-workflows/dist/validators/ping-pong.d.ts +6 -0
  105. package/clinkx-workflows/dist/validators/ping-pong.js +10 -0
  106. package/clinkx-workflows/dist/validators/ping-pong.js.map +1 -0
  107. package/clinkx-workflows/dist/workflow-tools.d.ts +51 -5
  108. package/clinkx-workflows/dist/workflow-tools.js +785 -34
  109. package/clinkx-workflows/dist/workflow-tools.js.map +1 -1
  110. package/clinkx-workflows/dist/workflow-verification-contract.d.ts +4 -4
  111. package/clinkx-workflows/templates/architecture-arena/candidate.txt +39 -0
  112. package/clinkx-workflows/templates/architecture-arena/judge.txt +34 -0
  113. package/clinkx-workflows/templates/ping-pong/implement.txt +14 -0
  114. package/clinkx-workflows/templates/ping-pong/remediate.txt +14 -0
  115. package/clinkx-workflows/templates/ping-pong/review.txt +27 -0
  116. package/clinkx-workflows/workflows/architecture-arena.yaml +127 -0
  117. package/clinkx-workflows/workflows/ping-pong.yaml +158 -0
  118. package/dist/context-builder/bundle.js +4 -3
  119. package/dist/context-builder/bundle.js.map +1 -1
  120. package/dist/context-builder/delegate-packet.d.ts +1 -0
  121. package/dist/context-builder/delegate-packet.js +66 -7
  122. package/dist/context-builder/delegate-packet.js.map +1 -1
  123. package/dist/context-builder/delegate-validation.d.ts +12 -3
  124. package/dist/context-builder/delegate-validation.js +23 -13
  125. package/dist/context-builder/delegate-validation.js.map +1 -1
  126. package/dist/context-builder/external-gaps.d.ts +14 -3
  127. package/dist/context-builder/external-gaps.js +124 -18
  128. package/dist/context-builder/external-gaps.js.map +1 -1
  129. package/dist/context-builder/handler.js +108 -191
  130. package/dist/context-builder/handler.js.map +1 -1
  131. package/dist/context-builder/review-coverage.js +27 -1
  132. package/dist/context-builder/review-coverage.js.map +1 -1
  133. package/dist/context-builder/secrets.js +1 -1
  134. package/dist/context-builder/secrets.js.map +1 -1
  135. package/dist/context-builder/versions.d.ts +10 -4
  136. package/dist/context-builder/versions.js +10 -4
  137. package/dist/context-builder/versions.js.map +1 -1
  138. package/dist/context-builder/workflow-runner.js +33 -24
  139. package/dist/context-builder/workflow-runner.js.map +1 -1
  140. package/dist/dashboard-cli.d.ts +2 -0
  141. package/dist/dashboard-cli.js +147 -57
  142. package/dist/dashboard-cli.js.map +1 -1
  143. package/dist/dashboard-companion/client.d.ts +10 -0
  144. package/dist/dashboard-companion/client.js +43 -1
  145. package/dist/dashboard-companion/client.js.map +1 -1
  146. package/dist/dashboard-companion/config.d.ts +19 -1
  147. package/dist/dashboard-companion/config.js +104 -3
  148. package/dist/dashboard-companion/config.js.map +1 -1
  149. package/dist/dashboard-companion/protocol.d.ts +16 -0
  150. package/dist/dashboard-companion/protocol.js +38 -1
  151. package/dist/dashboard-companion/protocol.js.map +1 -1
  152. package/dist/dashboard-companion/workstation-binding.d.ts +69 -0
  153. package/dist/dashboard-companion/workstation-binding.js +192 -0
  154. package/dist/dashboard-companion/workstation-binding.js.map +1 -0
  155. package/dist/dashboard-gateway/admin-cli.d.ts +10 -0
  156. package/dist/dashboard-gateway/admin-cli.js +266 -0
  157. package/dist/dashboard-gateway/admin-cli.js.map +1 -0
  158. package/dist/dashboard-gateway/config.d.ts +50 -0
  159. package/dist/dashboard-gateway/config.js +235 -1
  160. package/dist/dashboard-gateway/config.js.map +1 -1
  161. package/dist/dashboard-gateway/connection-registry.d.ts +100 -0
  162. package/dist/dashboard-gateway/connection-registry.js +228 -0
  163. package/dist/dashboard-gateway/connection-registry.js.map +1 -0
  164. package/dist/dashboard-gateway/control-plane/account-auth.d.ts +78 -0
  165. package/dist/dashboard-gateway/control-plane/account-auth.js +198 -0
  166. package/dist/dashboard-gateway/control-plane/account-auth.js.map +1 -0
  167. package/dist/dashboard-gateway/control-plane/billing.d.ts +264 -0
  168. package/dist/dashboard-gateway/control-plane/billing.js +787 -0
  169. package/dist/dashboard-gateway/control-plane/billing.js.map +1 -0
  170. package/dist/dashboard-gateway/control-plane/contracts.d.ts +1293 -0
  171. package/dist/dashboard-gateway/control-plane/contracts.js +280 -0
  172. package/dist/dashboard-gateway/control-plane/contracts.js.map +1 -0
  173. package/dist/dashboard-gateway/control-plane/cookies.d.ts +13 -0
  174. package/dist/dashboard-gateway/control-plane/cookies.js +46 -0
  175. package/dist/dashboard-gateway/control-plane/cookies.js.map +1 -0
  176. package/dist/dashboard-gateway/control-plane/credentials.d.ts +63 -0
  177. package/dist/dashboard-gateway/control-plane/credentials.js +66 -0
  178. package/dist/dashboard-gateway/control-plane/credentials.js.map +1 -0
  179. package/dist/dashboard-gateway/control-plane/entitlements.d.ts +118 -0
  180. package/dist/dashboard-gateway/control-plane/entitlements.js +329 -0
  181. package/dist/dashboard-gateway/control-plane/entitlements.js.map +1 -0
  182. package/dist/dashboard-gateway/control-plane/errors.d.ts +17 -0
  183. package/dist/dashboard-gateway/control-plane/errors.js +23 -0
  184. package/dist/dashboard-gateway/control-plane/errors.js.map +1 -0
  185. package/dist/dashboard-gateway/control-plane/hosts.d.ts +6 -0
  186. package/dist/dashboard-gateway/control-plane/hosts.js +16 -0
  187. package/dist/dashboard-gateway/control-plane/hosts.js.map +1 -0
  188. package/dist/dashboard-gateway/control-plane/http.d.ts +34 -0
  189. package/dist/dashboard-gateway/control-plane/http.js +331 -0
  190. package/dist/dashboard-gateway/control-plane/http.js.map +1 -0
  191. package/dist/dashboard-gateway/control-plane/schema.d.ts +9 -0
  192. package/dist/dashboard-gateway/control-plane/schema.js +247 -0
  193. package/dist/dashboard-gateway/control-plane/schema.js.map +1 -0
  194. package/dist/dashboard-gateway/control-plane/secrets.d.ts +20 -0
  195. package/dist/dashboard-gateway/control-plane/secrets.js +39 -0
  196. package/dist/dashboard-gateway/control-plane/secrets.js.map +1 -0
  197. package/dist/dashboard-gateway/control-plane/store.d.ts +579 -0
  198. package/dist/dashboard-gateway/control-plane/store.js +1115 -0
  199. package/dist/dashboard-gateway/control-plane/store.js.map +1 -0
  200. package/dist/dashboard-gateway/cookie-boundary.d.ts +60 -0
  201. package/dist/dashboard-gateway/cookie-boundary.js +205 -0
  202. package/dist/dashboard-gateway/cookie-boundary.js.map +1 -0
  203. package/dist/dashboard-gateway/index.js +271 -494
  204. package/dist/dashboard-gateway/index.js.map +1 -1
  205. package/dist/dashboard-gateway/main.js +7 -2
  206. package/dist/dashboard-gateway/main.js.map +1 -1
  207. package/dist/dashboard-gateway/routing.d.ts +43 -0
  208. package/dist/dashboard-gateway/routing.js +65 -0
  209. package/dist/dashboard-gateway/routing.js.map +1 -0
  210. package/dist/dashboard-gateway/tenant-gateway.d.ts +56 -0
  211. package/dist/dashboard-gateway/tenant-gateway.js +989 -0
  212. package/dist/dashboard-gateway/tenant-gateway.js.map +1 -0
  213. package/dist/dashboard-gateway/tenant-main.d.ts +41 -0
  214. package/dist/dashboard-gateway/tenant-main.js +303 -0
  215. package/dist/dashboard-gateway/tenant-main.js.map +1 -0
  216. package/dist/dashboard-gateway/tunnel-errors.d.ts +16 -0
  217. package/dist/dashboard-gateway/tunnel-errors.js +22 -0
  218. package/dist/dashboard-gateway/tunnel-errors.js.map +1 -0
  219. package/dist/dashboard-gateway/tunnel-http.d.ts +21 -0
  220. package/dist/dashboard-gateway/tunnel-http.js +175 -0
  221. package/dist/dashboard-gateway/tunnel-http.js.map +1 -0
  222. package/dist/handler.d.ts +6 -0
  223. package/dist/handler.js +17 -1
  224. package/dist/handler.js.map +1 -1
  225. package/dist/local-clink-backend.d.ts +2 -1
  226. package/dist/local-clink-backend.js +28 -4
  227. package/dist/local-clink-backend.js.map +1 -1
  228. package/dist/parsers/extract.d.ts +19 -1
  229. package/dist/parsers/extract.js +68 -3
  230. package/dist/parsers/extract.js.map +1 -1
  231. package/dist/pipeline.d.ts +17 -1
  232. package/dist/pipeline.js +34 -6
  233. package/dist/pipeline.js.map +1 -1
  234. package/dist/process-group.d.ts +65 -0
  235. package/dist/process-group.js +153 -0
  236. package/dist/process-group.js.map +1 -0
  237. package/dist/progress-report/schema.d.ts +23 -23
  238. package/dist/project-verification/files.js +1 -1
  239. package/dist/project-verification/files.js.map +1 -1
  240. package/dist/project-verification/process.js +23 -44
  241. package/dist/project-verification/process.js.map +1 -1
  242. package/dist/project-verification/service.js +9 -1
  243. package/dist/project-verification/service.js.map +1 -1
  244. package/dist/prompt.d.ts +7 -0
  245. package/dist/prompt.js +18 -1
  246. package/dist/prompt.js.map +1 -1
  247. package/dist/recipe-host/git-trust.d.ts +43 -0
  248. package/dist/recipe-host/git-trust.js +360 -0
  249. package/dist/recipe-host/git-trust.js.map +1 -0
  250. package/dist/recipe-host/git.d.ts +42 -0
  251. package/dist/recipe-host/git.js +207 -0
  252. package/dist/recipe-host/git.js.map +1 -0
  253. package/dist/recipe-host/native-recipe-host.d.ts +127 -0
  254. package/dist/recipe-host/native-recipe-host.js +880 -0
  255. package/dist/recipe-host/native-recipe-host.js.map +1 -0
  256. package/dist/recipe-host/seat-cwd.d.ts +16 -0
  257. package/dist/recipe-host/seat-cwd.js +170 -0
  258. package/dist/recipe-host/seat-cwd.js.map +1 -0
  259. package/dist/runner.d.ts +43 -1
  260. package/dist/runner.js +234 -35
  261. package/dist/runner.js.map +1 -1
  262. package/dist/server.js +9 -1
  263. package/dist/server.js.map +1 -1
  264. package/docs/configuration.md +24 -3
  265. package/docs/engineering-recipes.md +291 -0
  266. package/docs/security.md +84 -0
  267. package/docs/verification/project-checks.md +24 -2
  268. package/package.json +5 -1
  269. package/clinkx-workflows/dist/dashboard-ui/assets/index-BdpmbPps.js +0 -115
  270. package/clinkx-workflows/dist/dashboard-ui/assets/style-Im5i1iAs.css +0 -1
@@ -22,7 +22,7 @@ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
22
22
  import { computeRunHealth } from "./run-health.js";
23
23
  import { loadWorkflow, listWorkflowCatalog } from "./loader.js";
24
24
  import { defaultWorkflowAllowedRoots, WorkflowEngine } from "./engine.js";
25
- import { readRunStateForStatus, reapRunCancelled, WorkflowStateStore } from "./state.js";
25
+ import { readRunStateForStatus, reapRunCancelled, RecipeReopenError, recordRecipeOrphanCancel, WorkflowStateStore, } from "./state.js";
26
26
  import { isTerminalContextBuilderLifecycleStatus, parseContextBuilderLifecycleStateV1, } from "./context-builder-lifecycle-contract.js";
27
27
  import { validateRunId } from "./run-id.js";
28
28
  import { validateDynamicPaths } from "./path-validation.js";
@@ -36,6 +36,7 @@ import { buildRunSummaryOrUndefined, buildFailureRunSummary } from "./run-summar
36
36
  import { extractCard } from "./run-summary/cards/index.js";
37
37
  import { renderWorkflowReceipt } from "./workflow-receipt.js";
38
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";
39
40
  import { resolveWorkflowContextMode, WorkflowContextModeResolverError, } from "./context-mode-resolver.js";
40
41
  import { resolveEffectiveChairmanCall } from "./chairman-knobs.js";
41
42
  import { disabledFinalizerOverrideRejection, effectiveFinalizerEnabled, } from "./delegate-finalizer-policy.js";
@@ -58,8 +59,16 @@ import { ROSTER_NAME_PATTERN, ResolvedRosterSchema, } from "./roster-contract.js
58
59
  import { materializeArchitectureRoutes } from "./architecture-comparison/admission.js";
59
60
  import { ARCHITECTURE_WORKFLOW } from "./architecture-comparison/contract.js";
60
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";
61
65
  import { VERIFIED_REPAIR_WORKFLOW, MAX_REPAIR_RECORD_BYTES, RepairRecordSchema, assertRepairBounded } from "./verified-repair/contract.js";
62
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";
63
72
  import { VerifiedRepairRuntime } from "./verified-repair/runtime.js";
64
73
  import { inspectVerifiedRepairRecord } from "./verified-repair/result.js";
65
74
  import { readWorkflowVerification } from "./workflow-verification.js";
@@ -266,6 +275,442 @@ async function markWorkflowCancelled(store) {
266
275
  logger.warn({ err }, "markCancelled during cancellation handling failed");
267
276
  }
268
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
+ }
269
714
  // Keep in sync with schema.ts model regex and ModelSchema (delegate-validate.ts).
270
715
  const MODEL_OVERRIDE_PATTERN = /^[^\s\u0000-][^\s\u0000]*$/;
271
716
  // Keep in sync with schema.ts effort regex and EffortSchema (delegate-validate.ts).
@@ -286,7 +731,10 @@ function parseInvocationOverride(raw, label, maxLength, pattern) {
286
731
  }
287
732
  return value;
288
733
  }
289
- export function parseMembersOverride(raw, knownCliNames) {
734
+ export function parseMembersOverride(raw, knownCliNames, options) {
735
+ const stanceRequiredFromIndex = options?.stanceRequiredFromIndex === undefined
736
+ ? 3
737
+ : options.stanceRequiredFromIndex;
290
738
  if (raw == null)
291
739
  return undefined;
292
740
  if (!Array.isArray(raw)) {
@@ -341,8 +789,8 @@ export function parseMembersOverride(raw, knownCliNames) {
341
789
  }
342
790
  entry.stance = collapsed;
343
791
  }
344
- else if (i >= 3) {
345
- throw new McpError(ErrorCode.InvalidParams, "stance is required for members at index 3 and above");
792
+ else if (stanceRequiredFromIndex !== null && i >= stanceRequiredFromIndex) {
793
+ throw new McpError(ErrorCode.InvalidParams, `stance is required for members at index ${stanceRequiredFromIndex} and above`);
346
794
  }
347
795
  if (obj["model"] !== undefined) {
348
796
  entry.model = parseInvocationOverride(obj["model"], `members[${i}].model`, 128, MODEL_OVERRIDE_PATTERN);
@@ -392,7 +840,7 @@ function invocationOverrideKnobs(value) {
392
840
  ...(value.effort === undefined ? {} : { effort: value.effort }),
393
841
  };
394
842
  }
395
- 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) {
396
844
  // Structural E5: independent of the optional adapter-capability hook so the
397
845
  // standalone server rejects a disabled-finalizer override too. No-op when
398
846
  // the policy has no enabled delegate (including the no-runner `off` default).
@@ -412,12 +860,17 @@ function validateInvocationOverridesAtAdmission(workflow, definition, parsedMemb
412
860
  const staticChairman = councilWorkflow
413
861
  ? definition.stages[3]?.calls[0]
414
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;
415
868
  for (const [stageIndex, stage] of definition.stages.entries()) {
416
869
  for (const call of stage.calls) {
417
- if (call === staticChairman) {
870
+ if (call === staticChairman || call === recipeDefaultChairman) {
418
871
  continue;
419
872
  }
420
- if (parsedMembers !== undefined && stageIndex < 2) {
873
+ if (councilWorkflow && parsedMembers !== undefined && stageIndex < 2) {
421
874
  continue;
422
875
  }
423
876
  const knobs = invocationOverrideKnobs(call);
@@ -434,6 +887,15 @@ function validateInvocationOverridesAtAdmission(workflow, definition, parsedMemb
434
887
  }
435
888
  }
436
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
+ }
437
899
  if (councilWorkflow && staticChairman !== undefined) {
438
900
  const effectiveChairman = resolveEffectiveChairmanCall({
439
901
  staticCall: staticChairman,
@@ -1376,6 +1838,7 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1376
1838
  catch {
1377
1839
  throw new McpError(ErrorCode.InvalidParams, `Invalid run_id "${runId}". Must match [A-Za-z0-9_-]{1,64}.`);
1378
1840
  }
1841
+ await assertRunIdNotRecipeRun(runId, workflow, options);
1379
1842
  const validatorRegistry = createValidatorRegistry();
1380
1843
  let loaded = loadWorkflow(workflow, {
1381
1844
  templatesRoot: options.templatesRoot ?? getTemplatesPath(),
@@ -1406,6 +1869,8 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1406
1869
  let initialContextPolicy;
1407
1870
  let planReviewAdmission;
1408
1871
  let admittedRosterName;
1872
+ let recipeSeatPlan;
1873
+ let pingPongSettings;
1409
1874
  try {
1410
1875
  let membersRaw = args["members"];
1411
1876
  let chairmanRaw = args["chairman"];
@@ -1421,25 +1886,54 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1421
1886
  chairmanEffortRaw = applied.chairmanEffortRaw;
1422
1887
  suppliedVariables = applied.variables;
1423
1888
  }
1424
- parsedMembers = parseMembersOverride(membersRaw, knownCliNames);
1889
+ parsedMembers = parseMembersOverride(membersRaw, knownCliNames, isRecipeSeatWorkflow(workflow) ? { stanceRequiredFromIndex: null } : undefined);
1425
1890
  parsedChairman = parseChairmanOverride(chairmanRaw, knownCliNames);
1426
1891
  parsedChairmanModel = parseChairmanModelOverride(chairmanModelRaw);
1427
1892
  parsedChairmanEffort = parseChairmanEffortOverride(chairmanEffortRaw);
1428
- if (parsedMembers != null && !COUNCIL_RUNTIME_MEMBER_WORKFLOWS.has(workflow)) {
1893
+ if (parsedMembers != null && !supportsSeatMembers(workflow)) {
1429
1894
  throw new McpError(ErrorCode.InvalidParams, `members parameter is not supported for workflow "${workflow}"`);
1430
1895
  }
1431
- if (parsedChairman != null && !COUNCIL_RUNTIME_MEMBER_WORKFLOWS.has(workflow)) {
1896
+ if (parsedChairman != null && !supportsSeatChairman(workflow)) {
1432
1897
  throw new McpError(ErrorCode.InvalidParams, `chairman parameter is not supported for workflow "${workflow}"`);
1433
1898
  }
1434
- if (parsedChairmanModel != null && !COUNCIL_RUNTIME_MEMBER_WORKFLOWS.has(workflow)) {
1899
+ if (parsedChairmanModel != null && !supportsSeatChairman(workflow)) {
1435
1900
  throw new McpError(ErrorCode.InvalidParams, `chairman_model parameter is not supported for workflow "${workflow}"`);
1436
1901
  }
1437
- if (parsedChairmanEffort != null && !COUNCIL_RUNTIME_MEMBER_WORKFLOWS.has(workflow)) {
1902
+ if (parsedChairmanEffort != null && !supportsSeatChairman(workflow)) {
1438
1903
  throw new McpError(ErrorCode.InvalidParams, `chairman_effort parameter is not supported for workflow "${workflow}"`);
1439
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
+ }
1440
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 };
1441
1913
  try {
1442
- 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
+ }
1443
1937
  loaded = { ...loaded, normalized: materializeVerifiedRepairRoutes(loaded.normalized, resolvedVariables, options.planReviewAvailableCliNames ?? options.availableCliNames, options.validateInvocationOverrides) };
1444
1938
  if (workflow === VERIFIED_REPAIR_WORKFLOW && options.verifiedRepairHost === undefined) {
1445
1939
  throw new Error("verified-repair requires the root host capability");
@@ -1498,7 +1992,7 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1498
1992
  // Caller-supplied cb_delegate only, never the roster-materialized one: a
1499
1993
  // roster preset is Zod-parsed at load, which defaults min_score and erases
1500
1994
  // whether the preset file actually requested it.
1501
- admittedRosterName === undefined ? variables?.["cb_delegate"] : undefined);
1995
+ admittedRosterName === undefined ? variables?.["cb_delegate"] : undefined, recipeSeatPlan);
1502
1996
  // A-7: reject caller context anchors that resolve to the bound plan or any
1503
1997
  // plan-workspace PLAN.md. Pre-mutex, so a rejected request creates no state:
1504
1998
  // the caller must not be able to hand actors a MUTABLE plan alongside the
@@ -1558,12 +2052,20 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1558
2052
  let initializedPlanReview;
1559
2053
  let preparedSnapshot;
1560
2054
  let executionId;
2055
+ let pingPong;
2056
+ let pingPongReserved = false;
1561
2057
  try {
1562
2058
  ownership.throwIfCancelled();
1563
2059
  const runDir = getRunStateDir(runId);
1564
2060
  if (existsSync(runDir)) {
1565
2061
  throw new McpError(ErrorCode.InvalidParams, `run_id ${runId} already has persisted state at ${runDir}`);
1566
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
+ }
1567
2069
  // Read + digest-verify the plan BEFORE composing: the expander inlines
1568
2070
  // the snapshot text, so it must exist by expansion time (D9).
1569
2071
  preparedSnapshot = planReviewPlan === undefined
@@ -1578,6 +2080,7 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1578
2080
  try {
1579
2081
  store = await WorkflowStateStore.create({
1580
2082
  runId,
2083
+ fileWriter: options.fileWriter,
1581
2084
  definition: effectiveDefinition,
1582
2085
  variables: resolvedVariables,
1583
2086
  debugKeepArtifacts: debug,
@@ -1592,6 +2095,20 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1592
2095
  }
1593
2096
  executionId = await ownership.bindStore(store);
1594
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
+ }
1595
2112
  // A-10: the async acknowledgement is a durability boundary. A caller
1596
2113
  // cannot observe `running` until every plan-review snapshot and the
1597
2114
  // strict typed state subtree have committed successfully.
@@ -1649,6 +2166,13 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1649
2166
  else
1650
2167
  await verifiedRepair.finalize(ownership.signal.aborted ? "cancelled" : "failed", err);
1651
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
+ }
1652
2176
  }
1653
2177
  finally {
1654
2178
  await ownership.finish(store);
@@ -1659,7 +2183,7 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1659
2183
  await ownership.finish(store);
1660
2184
  throw new McpError(ErrorCode.InternalError, `Failed to initialize async run ${runId}`);
1661
2185
  }
1662
- 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) => {
1663
2187
  if (err instanceof WorkflowCancellationError) {
1664
2188
  logger.info({ runId }, "workflow run cancelled");
1665
2189
  return;
@@ -1684,6 +2208,15 @@ async function executeRunWorkflow(server, options, args, signal, progressToken)
1684
2208
  ...(resolvedRoster !== undefined
1685
2209
  ? { resolved_roster: resolvedRoster }
1686
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
+ : {}),
1687
2220
  }),
1688
2221
  }],
1689
2222
  };
@@ -1734,11 +2267,11 @@ async function initializePlanReviewRunState(store, plan, definition, prepared) {
1734
2267
  if (!prepared.ok)
1735
2268
  throw prepared.error;
1736
2269
  const contract = plan.admission.execution_contract;
1737
- const snapshot = await persistCanonicalPlanSnapshot(store.runDir, prepared.canonical);
2270
+ const snapshot = await persistCanonicalPlanSnapshot(store.runDir, prepared.canonical, store.fileWriter);
1738
2271
  if (snapshot.absolutePath !== plan.snapshotAbsolutePath) {
1739
2272
  throw new PlanReviewStageError("snapshot", `Snapshot path ${snapshot.absolutePath} does not match the runtime-owned path derived for this run (${plan.snapshotAbsolutePath})`);
1740
2273
  }
1741
- const persistedContract = await writeExecutionContractSnapshot(store.runDir, contract);
2274
+ const persistedContract = await writeExecutionContractSnapshot(store.runDir, contract, store.fileWriter);
1742
2275
  const state = {
1743
2276
  schema_version: "council-plan-review-state-v1",
1744
2277
  execution_contract_path: persistedContract.relPath,
@@ -1797,14 +2330,70 @@ function projectResolvedRosterDelegate(policy, resolvedVariables) {
1797
2330
  };
1798
2331
  }
1799
2332
  /**
1800
- * Requested-value roster projection for council workflows. Call AFTER
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
1801
2387
  * `expandCouncilComposition` / `expandRunWorkflowDefinition`, AFTER
1802
2388
  * `resolveEffectiveChairmanCall` values are on the definition (or passed as
1803
2389
  * parsed chairman knobs), and AFTER `effectiveFinalizerEnabled` can be
1804
2390
  * evaluated from `initialContextPolicy` — and BEFORE `WorkflowStateStore.create()`.
1805
- * `plan-review-receipts` and any non-council workflow return undefined.
2391
+ * `plan-review-receipts` and any other workflow return undefined.
1806
2392
  */
1807
2393
  export function buildResolvedRoster(input) {
2394
+ if (isRecipeSeatWorkflow(input.workflow)) {
2395
+ return buildRecipeResolvedRoster(input);
2396
+ }
1808
2397
  if (!supportsRuntimeMembers(input.workflow)) {
1809
2398
  return undefined;
1810
2399
  }
@@ -1873,14 +2462,16 @@ preparedSnapshot) {
1873
2462
  // string cannot carry. This is the single read — never re-read `plan_file`.
1874
2463
  preparedSnapshot?.ok === true ? preparedSnapshot.canonical : undefined);
1875
2464
  }
1876
- return parsedMembers != null ||
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 ||
1877
2468
  parsedChairman != null ||
1878
2469
  parsedChairmanModel !== undefined ||
1879
- parsedChairmanEffort !== undefined
2470
+ parsedChairmanEffort !== undefined)
1880
2471
  ? expandCouncilComposition(definition, parsedMembers, workflow, parsedChairman, parsedChairmanModel, parsedChairmanEffort)
1881
2472
  : definition;
1882
2473
  }
1883
- 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) {
1884
2475
  let store = preCreatedStore ?? null;
1885
2476
  let backend = null;
1886
2477
  let reporter;
@@ -1905,6 +2496,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
1905
2496
  const resolvedRoster = resolvedRosterForAdmission(workflow, effectiveDefinition, parsedMembers, parsedChairman, parsedChairmanModel, parsedChairmanEffort, initialContextPolicy, resolvedVariables, rosterName);
1906
2497
  store = await WorkflowStateStore.create({
1907
2498
  runId,
2499
+ fileWriter: options.fileWriter,
1908
2500
  definition: effectiveDefinition,
1909
2501
  variables: resolvedVariables,
1910
2502
  debugKeepArtifacts: debug,
@@ -1939,8 +2531,9 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
1939
2531
  ? new WorkflowProgressReporter(server, progressToken, runId, effectiveDefinition)
1940
2532
  : undefined;
1941
2533
  const rpt = reporter; // local const for closure narrowing
2534
+ const baseHooks = storeRef.hooks;
1942
2535
  const hooks = {
1943
- ...storeRef.hooks,
2536
+ ...baseHooks,
1944
2537
  ...(verifiedRepair === undefined ? {} : {
1945
2538
  onRunStateChange: async (event) => {
1946
2539
  if (event.state === "succeeded" || event.state === "failed" || event.state === "cancelled") {
@@ -1980,6 +2573,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
1980
2573
  runId,
1981
2574
  sessionLogGeneration,
1982
2575
  runDir: storeRef.runDir,
2576
+ fileWriter: options.fileWriter,
1983
2577
  signal,
1984
2578
  hooks,
1985
2579
  contextBuilderRunner: verifiedRepair === undefined ? options.contextBuilderRunner : undefined,
@@ -1988,6 +2582,7 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
1988
2582
  commitPreflightContext: storeRef.commitPreflightContext?.bind(storeRef),
1989
2583
  initialContextPolicy,
1990
2584
  verifiedRepair,
2585
+ pingPong,
1991
2586
  ...(options.deriveInvocationAudit === undefined
1992
2587
  ? {}
1993
2588
  : { deriveInvocationAudit: options.deriveInvocationAudit }),
@@ -2040,6 +2635,11 @@ async function runWorkflowDetached(server, options, workflow, runId, resolvedVar
2040
2635
  logger.error({ err: publicationError, runId }, "repair error publication failed; preserving original execution failure");
2041
2636
  }
2042
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
+ }
2043
2643
  if (signal.aborted || error instanceof WorkflowCancellationError) {
2044
2644
  await markWorkflowCancelled(store);
2045
2645
  throw new WorkflowCancellationError();
@@ -2110,6 +2710,14 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
2110
2710
  if (persistedState?.workflowName === VERIFIED_REPAIR_WORKFLOW) {
2111
2711
  throw new McpError(ErrorCode.InvalidParams, "verified-repair mutation cannot be resumed; inspect the retained result and submit a fresh explicit contract");
2112
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
+ }
2113
2721
  if (persistedState != null &&
2114
2722
  isPlanReviewRunState(persistedState) &&
2115
2723
  (persistedState.status === "failed" ||
@@ -2138,6 +2746,7 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
2138
2746
  const resumeOptions = {
2139
2747
  runId,
2140
2748
  debugKeepArtifacts: debug,
2749
+ fileWriter: options.fileWriter,
2141
2750
  };
2142
2751
  store = await WorkflowStateStore.resume(resumeOptions);
2143
2752
  if (store.runState.workflowName === VERIFIED_REPAIR_WORKFLOW) {
@@ -2209,6 +2818,7 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
2209
2818
  validatorRegistry,
2210
2819
  runId,
2211
2820
  runDir: store.runDir,
2821
+ fileWriter: options.fileWriter,
2212
2822
  signal: ownedSignal,
2213
2823
  resume: store.resume,
2214
2824
  contextBuilderRunner: options.contextBuilderRunner,
@@ -2276,6 +2886,7 @@ async function executeResumeWorkflow(server, options, args, signal, progressToke
2276
2886
  runId,
2277
2887
  sessionLogGeneration,
2278
2888
  runDir: store.runDir,
2889
+ fileWriter: options.fileWriter,
2279
2890
  signal: ownedSignal,
2280
2891
  hooks: rpt != null ? hooks : store.hooks,
2281
2892
  resume: store.resume,
@@ -2890,7 +3501,15 @@ async function projectWorkflowRunStatus(options, args, guard) {
2890
3501
  }
2891
3502
  else {
2892
3503
  projection["result_available"] = state.status === "succeeded";
2893
- if (state.status === "succeeded") {
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") {
2894
3513
  const final = state.stages.at(-1);
2895
3514
  const call = final?.calls[0];
2896
3515
  // Cheap size hint without reading contents. Containment (via
@@ -2952,6 +3571,11 @@ async function projectWorkflowRunStatus(options, args, guard) {
2952
3571
  }
2953
3572
  }
2954
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
+ }
2955
3579
  if (state.workflowName === ARCHITECTURE_WORKFLOW) {
2956
3580
  const comparison = await inspectArchitectureComparisonRecord(runDir, runId, includeResult);
2957
3581
  const { result, ...status } = comparison;
@@ -2962,6 +3586,16 @@ async function projectWorkflowRunStatus(options, args, guard) {
2962
3586
  else
2963
3587
  delete projection["result"];
2964
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
+ }
2965
3599
  if (state.workflowName === VERIFIED_REPAIR_WORKFLOW) {
2966
3600
  let inspected = await inspectVerifiedRepairRecord(runDir, runId, includeResult);
2967
3601
  if (inspected.availability === "unrecorded" && lock === "stale_or_absent" && !activeRuns.has(runId)) {
@@ -2997,7 +3631,7 @@ async function projectWorkflowRunStatus(options, args, guard) {
2997
3631
  content: [{ type: "text", text: JSON.stringify(projection) }],
2998
3632
  };
2999
3633
  }
3000
- async function executeCancelWorkflow(_options, args) {
3634
+ async function executeCancelWorkflow(options, args) {
3001
3635
  const runId = args["run_id"];
3002
3636
  if (typeof runId !== "string" || runId === "") {
3003
3637
  throw new McpError(ErrorCode.InvalidParams, 'Missing or invalid "run_id" parameter');
@@ -3020,6 +3654,13 @@ async function executeCancelWorkflow(_options, args) {
3020
3654
  // controller is still in the registry (deleted only in the run's finally).
3021
3655
  // Re-read first so we never claim "cancelling" for an already-done run.
3022
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
+ }
3023
3664
  if (live != null && live.state.status !== "running" && live.state.status !== "pending") {
3024
3665
  return text({ run_id: runId, status: live.state.status, already_terminal: true });
3025
3666
  }
@@ -3035,6 +3676,16 @@ async function executeCancelWorkflow(_options, args) {
3035
3676
  }
3036
3677
  const { state, lock } = read;
3037
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
+ }
3038
3689
  return text({ run_id: runId, status: state.status, already_terminal: true });
3039
3690
  }
3040
3691
  if (lock === "unknown") {
@@ -3050,10 +3701,29 @@ async function executeCancelWorkflow(_options, args) {
3050
3701
  // of truth for ownership: reapRunCancelled acquires it itself (reclaiming a
3051
3702
  // truly stale/dead lock, refusing a live one), closing the TOCTOU where a
3052
3703
  // concurrent resume_workflow could grab the lock between read and reap.
3053
- const outcome = await reapRunCancelled(runId);
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 });
3054
3709
  if (outcome === "cancelled") {
3055
3710
  return text({ run_id: runId, status: "cancelled", reaped: true });
3056
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
+ }
3057
3727
  if (outcome === "locked") {
3058
3728
  // The run is owned by another live worker (or a blocking run): the lock
3059
3729
  // could not be acquired. Refuse without mutating — this process cannot
@@ -3083,17 +3753,22 @@ function executeListWorkflows(options) {
3083
3753
  const effectiveContextDefault = resolveWorkflowContextMode(undefined, contextDefault, preflightEnabled, undefined, options.defaultCurator).effectiveMode;
3084
3754
  const entries = [];
3085
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;
3086
3760
  const def = entry.definition;
3087
3761
  const contextStrategy = deriveContextStrategy(def);
3088
3762
  const runtimeMembers = supportsRuntimeMembers(name);
3763
+ const recipeRules = isRecipeSeatWorkflow(name) ? RECIPE_SEAT_RULES[name] : undefined;
3089
3764
  entries.push({
3090
3765
  name,
3091
3766
  description: def.description,
3092
3767
  version: def.version,
3093
3768
  source: entry.source,
3094
3769
  shadowed_yaml: entry.shadowedYaml,
3095
- supports_members: runtimeMembers,
3096
- supports_chairman: runtimeMembers,
3770
+ supports_members: supportsSeatMembers(name),
3771
+ supports_chairman: supportsSeatChairman(name),
3097
3772
  supports_context_preflight: contextStrategy.supports_context_preflight,
3098
3773
  effective_context_default: name === VERIFIED_REPAIR_WORKFLOW ? "disabled" : effectiveContextDefault,
3099
3774
  fails_on_empty_selection: contextStrategy.fails_on_empty_selection,
@@ -3108,6 +3783,12 @@ function executeListWorkflows(options) {
3108
3783
  members_max: 10,
3109
3784
  members_stance_required_from_index: 3,
3110
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 } : {}),
3111
3792
  ...(entry.path != null ? { path: basename(entry.path) } : {}),
3112
3793
  ...(name === PLAN_REVIEW_RECEIPTS_WORKFLOW
3113
3794
  ? {
@@ -3319,7 +4000,7 @@ const RUN_WORKFLOW_SCHEMA = {
3319
4000
  },
3320
4001
  members: {
3321
4002
  type: "array",
3322
- description: "Optional runtime council member composition override. Accepted only 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.",
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.",
3323
4004
  minItems: 1,
3324
4005
  maxItems: 10,
3325
4006
  items: {
@@ -3354,7 +4035,7 @@ const RUN_WORKFLOW_SCHEMA = {
3354
4035
  },
3355
4036
  chairman: {
3356
4037
  type: "string",
3357
- description: "Optional CLI adapter name override for the council chairman seat. Accepted only for council workflows. Only changes the LLM adapter; the chairman's role and prompt template are preserved.",
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.",
3358
4039
  },
3359
4040
  chairman_model: {
3360
4041
  type: "string",
@@ -3445,6 +4126,64 @@ const CANCEL_WORKFLOW_SCHEMA = {
3445
4126
  required: ["run_id"],
3446
4127
  additionalProperties: false,
3447
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
+ };
3448
4187
  /**
3449
4188
  * Return the workflow tool definitions for tools/list.
3450
4189
  *
@@ -3545,7 +4284,7 @@ export function getWorkflowToolDefinitions(workflowsPath, availableCliNames) {
3545
4284
  return [
3546
4285
  {
3547
4286
  name: "run_workflow",
3548
- 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. 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.`,
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.`,
3549
4288
  inputSchema: runSchema,
3550
4289
  },
3551
4290
  {
@@ -3575,10 +4314,18 @@ export function getWorkflowToolDefinitions(workflowsPath, availableCliNames) {
3575
4314
  },
3576
4315
  {
3577
4316
  name: "cancel_workflow",
3578
- 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.",
3579
4318
  inputSchema: CANCEL_WORKFLOW_SCHEMA,
3580
4319
  annotations: { destructiveHint: true },
3581
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
+ },
3582
4329
  ];
3583
4330
  }
3584
4331
  /** Names of the workflow tools (for dispatch matching). */
@@ -3589,6 +4336,7 @@ export const WORKFLOW_TOOL_NAMES = new Set([
3589
4336
  "workflow_run_status",
3590
4337
  "workflow_run_wait",
3591
4338
  "cancel_workflow",
4339
+ RECIPE_DECIDE_TOOL,
3592
4340
  ]);
3593
4341
  /**
3594
4342
  * Dispatch a workflow tool call.
@@ -3610,6 +4358,8 @@ export async function handleWorkflowToolCall(server, options, name, args, signal
3610
4358
  return await executeWorkflowRunWait(options, args, signal);
3611
4359
  case "cancel_workflow":
3612
4360
  return await executeCancelWorkflow(options, args);
4361
+ case RECIPE_DECIDE_TOOL:
4362
+ return await executeRecipeDecide(options, args);
3613
4363
  default:
3614
4364
  return null;
3615
4365
  }
@@ -3621,8 +4371,9 @@ export async function handleWorkflowToolCall(server, options, name, args, signal
3621
4371
  * Register workflow tools on an MCP Server instance.
3622
4372
  *
3623
4373
  * This is the reusable core extracted from createWorkflowServer().
3624
- * It registers six tools: run_workflow, resume_workflow, list_workflows,
3625
- * workflow_run_status, workflow_run_wait, 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.
3626
4377
  *
3627
4378
  * The `options.createBackend` factory determines how clink calls are
3628
4379
  * dispatched — callers provide either a child-process or in-process backend.