wicked-crew 0.17.0 → 0.18.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 (547) hide show
  1. package/README.md +71 -18
  2. package/adapters/web-source.lock +1314 -0
  3. package/dist/api/audit.d.ts +5 -0
  4. package/dist/api/audit.d.ts.map +1 -1
  5. package/dist/api/audit.js +20 -0
  6. package/dist/api/audit.js.map +1 -1
  7. package/dist/api/auth.d.ts.map +1 -1
  8. package/dist/api/auth.js +3 -0
  9. package/dist/api/auth.js.map +1 -1
  10. package/dist/api/chat-context.js +1 -1
  11. package/dist/api/chat-history.d.ts +3 -0
  12. package/dist/api/chat-history.d.ts.map +1 -1
  13. package/dist/api/chat-history.js +6 -1
  14. package/dist/api/chat-history.js.map +1 -1
  15. package/dist/api/chat-jobs.d.ts +192 -0
  16. package/dist/api/chat-jobs.d.ts.map +1 -0
  17. package/dist/api/chat-jobs.js +929 -0
  18. package/dist/api/chat-jobs.js.map +1 -0
  19. package/dist/api/chat-proposals.d.ts +323 -7
  20. package/dist/api/chat-proposals.d.ts.map +1 -1
  21. package/dist/api/chat-proposals.js +1581 -40
  22. package/dist/api/chat-proposals.js.map +1 -1
  23. package/dist/api/chat-requirements.d.ts +54 -0
  24. package/dist/api/chat-requirements.d.ts.map +1 -0
  25. package/dist/api/chat-requirements.js +282 -0
  26. package/dist/api/chat-requirements.js.map +1 -0
  27. package/dist/api/chat-scope.d.ts +56 -0
  28. package/dist/api/chat-scope.d.ts.map +1 -1
  29. package/dist/api/chat-scope.js +175 -5
  30. package/dist/api/chat-scope.js.map +1 -1
  31. package/dist/api/chat-transcripts.d.ts +7 -0
  32. package/dist/api/chat-transcripts.d.ts.map +1 -1
  33. package/dist/api/chat-transcripts.js +17 -1
  34. package/dist/api/chat-transcripts.js.map +1 -1
  35. package/dist/api/delivery-assurance.d.ts.map +1 -1
  36. package/dist/api/delivery-assurance.js +5 -2
  37. package/dist/api/delivery-assurance.js.map +1 -1
  38. package/dist/api/delivery-index.d.ts +109 -5
  39. package/dist/api/delivery-index.d.ts.map +1 -1
  40. package/dist/api/delivery-index.js +199 -7
  41. package/dist/api/delivery-index.js.map +1 -1
  42. package/dist/api/mcp.d.ts +7 -2
  43. package/dist/api/mcp.d.ts.map +1 -1
  44. package/dist/api/mcp.js +1 -1
  45. package/dist/api/mcp.js.map +1 -1
  46. package/dist/api/needs.d.ts.map +1 -1
  47. package/dist/api/needs.js +19 -1
  48. package/dist/api/needs.js.map +1 -1
  49. package/dist/api/product.d.ts +87 -3
  50. package/dist/api/product.d.ts.map +1 -1
  51. package/dist/api/product.js +155 -68
  52. package/dist/api/product.js.map +1 -1
  53. package/dist/api/proposal-theme.d.ts +23 -0
  54. package/dist/api/proposal-theme.d.ts.map +1 -0
  55. package/dist/api/proposal-theme.js +30 -0
  56. package/dist/api/proposal-theme.js.map +1 -0
  57. package/dist/api/recording.d.ts +127 -10
  58. package/dist/api/recording.d.ts.map +1 -1
  59. package/dist/api/recording.js +320 -68
  60. package/dist/api/recording.js.map +1 -1
  61. package/dist/api/repo-input.d.ts +55 -0
  62. package/dist/api/repo-input.d.ts.map +1 -0
  63. package/dist/api/repo-input.js +113 -0
  64. package/dist/api/repo-input.js.map +1 -0
  65. package/dist/api/requirements.d.ts +75 -0
  66. package/dist/api/requirements.d.ts.map +1 -1
  67. package/dist/api/requirements.js +97 -9
  68. package/dist/api/requirements.js.map +1 -1
  69. package/dist/api/review-change.d.ts +64 -0
  70. package/dist/api/review-change.d.ts.map +1 -0
  71. package/dist/api/review-change.js +214 -0
  72. package/dist/api/review-change.js.map +1 -0
  73. package/dist/api/roster-standing.d.ts +4 -0
  74. package/dist/api/roster-standing.d.ts.map +1 -1
  75. package/dist/api/roster-standing.js +43 -10
  76. package/dist/api/roster-standing.js.map +1 -1
  77. package/dist/api/routes.d.ts +138 -12
  78. package/dist/api/routes.d.ts.map +1 -1
  79. package/dist/api/routes.js +1496 -301
  80. package/dist/api/routes.js.map +1 -1
  81. package/dist/api/run-documents.d.ts +97 -0
  82. package/dist/api/run-documents.d.ts.map +1 -0
  83. package/dist/api/run-documents.js +458 -0
  84. package/dist/api/run-documents.js.map +1 -0
  85. package/dist/api/run-sources.d.ts +51 -0
  86. package/dist/api/run-sources.d.ts.map +1 -0
  87. package/dist/api/run-sources.js +133 -0
  88. package/dist/api/run-sources.js.map +1 -0
  89. package/dist/api/run-timing-index.d.ts +12 -1
  90. package/dist/api/run-timing-index.d.ts.map +1 -1
  91. package/dist/api/run-timing-index.js +35 -0
  92. package/dist/api/run-timing-index.js.map +1 -1
  93. package/dist/api/runtime-state.d.ts +41 -0
  94. package/dist/api/runtime-state.d.ts.map +1 -0
  95. package/dist/api/runtime-state.js +75 -0
  96. package/dist/api/runtime-state.js.map +1 -0
  97. package/dist/api/seat-container-login.d.ts +51 -0
  98. package/dist/api/seat-container-login.d.ts.map +1 -1
  99. package/dist/api/seat-container-login.js +317 -1
  100. package/dist/api/seat-container-login.js.map +1 -1
  101. package/dist/api/seat-images.d.ts.map +1 -1
  102. package/dist/api/seat-images.js +7 -0
  103. package/dist/api/seat-images.js.map +1 -1
  104. package/dist/api/server.d.ts +7 -0
  105. package/dist/api/server.d.ts.map +1 -1
  106. package/dist/api/server.js +207 -26
  107. package/dist/api/server.js.map +1 -1
  108. package/dist/api/skills.d.ts +8 -0
  109. package/dist/api/skills.d.ts.map +1 -1
  110. package/dist/api/skills.js +21 -0
  111. package/dist/api/skills.js.map +1 -1
  112. package/dist/api/system-snapshot.d.ts +3 -2
  113. package/dist/api/system-snapshot.d.ts.map +1 -1
  114. package/dist/api/system-snapshot.js +19 -6
  115. package/dist/api/system-snapshot.js.map +1 -1
  116. package/dist/api/testing.d.ts +3 -3
  117. package/dist/api/ui-text.d.ts +45 -0
  118. package/dist/api/ui-text.d.ts.map +1 -0
  119. package/dist/api/ui-text.js +188 -0
  120. package/dist/api/ui-text.js.map +1 -0
  121. package/dist/apps/actions/card.d.ts +62 -0
  122. package/dist/apps/actions/card.d.ts.map +1 -0
  123. package/dist/apps/actions/card.js +111 -0
  124. package/dist/apps/actions/card.js.map +1 -0
  125. package/dist/apps/actions/write-path.d.ts.map +1 -1
  126. package/dist/apps/actions/write-path.js +26 -77
  127. package/dist/apps/actions/write-path.js.map +1 -1
  128. package/dist/apps/exec/sources.d.ts.map +1 -1
  129. package/dist/apps/exec/sources.js +3 -0
  130. package/dist/apps/exec/sources.js.map +1 -1
  131. package/dist/apps/exec/texts.d.ts +1 -1
  132. package/dist/apps/publish/artifacts.d.ts +18 -0
  133. package/dist/apps/publish/artifacts.d.ts.map +1 -0
  134. package/dist/apps/publish/artifacts.js +87 -0
  135. package/dist/apps/publish/artifacts.js.map +1 -0
  136. package/dist/apps/publish/check.d.ts +103 -0
  137. package/dist/apps/publish/check.d.ts.map +1 -0
  138. package/dist/apps/publish/check.js +235 -0
  139. package/dist/apps/publish/check.js.map +1 -0
  140. package/dist/apps/publish/image.d.ts +2 -0
  141. package/dist/apps/publish/image.d.ts.map +1 -1
  142. package/dist/apps/publish/image.js +2 -1
  143. package/dist/apps/publish/image.js.map +1 -1
  144. package/dist/apps/publish/render.d.ts +71 -0
  145. package/dist/apps/publish/render.d.ts.map +1 -0
  146. package/dist/apps/publish/render.js +122 -0
  147. package/dist/apps/publish/render.js.map +1 -0
  148. package/dist/apps/publish/run.d.ts +35 -0
  149. package/dist/apps/publish/run.d.ts.map +1 -0
  150. package/dist/apps/publish/run.js +127 -0
  151. package/dist/apps/publish/run.js.map +1 -0
  152. package/dist/apps/routes.d.ts +54 -2
  153. package/dist/apps/routes.d.ts.map +1 -1
  154. package/dist/apps/routes.js +124 -7
  155. package/dist/apps/routes.js.map +1 -1
  156. package/dist/apps/spec.d.ts +8 -8
  157. package/dist/apps/store.d.ts +84 -5
  158. package/dist/apps/store.d.ts.map +1 -1
  159. package/dist/apps/store.js +191 -4
  160. package/dist/apps/store.js.map +1 -1
  161. package/dist/apps/turns.d.ts +19 -1
  162. package/dist/apps/turns.d.ts.map +1 -1
  163. package/dist/apps/turns.js +60 -2
  164. package/dist/apps/turns.js.map +1 -1
  165. package/dist/apps/views.d.ts +5 -1
  166. package/dist/apps/views.d.ts.map +1 -1
  167. package/dist/apps/views.js +18 -7
  168. package/dist/apps/views.js.map +1 -1
  169. package/dist/apps-server/Dockerfile +25 -0
  170. package/dist/apps-server/runners/sqlite-runner.mjs +110 -0
  171. package/dist/apps-server/server/lib/bundle/server.mjs +92523 -0
  172. package/dist/apps-server/server/node_modules/@pgsql/types/LICENSE +22 -0
  173. package/dist/apps-server/server/node_modules/@pgsql/types/README.md +106 -0
  174. package/dist/apps-server/server/node_modules/@pgsql/types/enums.d.ts +76 -0
  175. package/dist/apps-server/server/node_modules/@pgsql/types/enums.js +2 -0
  176. package/dist/apps-server/server/node_modules/@pgsql/types/esm/enums.js +1 -0
  177. package/dist/apps-server/server/node_modules/@pgsql/types/esm/index.js +2 -0
  178. package/dist/apps-server/server/node_modules/@pgsql/types/esm/types.js +1 -0
  179. package/dist/apps-server/server/node_modules/@pgsql/types/index.d.ts +2 -0
  180. package/dist/apps-server/server/node_modules/@pgsql/types/index.js +18 -0
  181. package/dist/apps-server/server/node_modules/@pgsql/types/package.json +36 -0
  182. package/dist/apps-server/server/node_modules/@pgsql/types/types.d.ts +2488 -0
  183. package/dist/apps-server/server/node_modules/@pgsql/types/types.js +2 -0
  184. package/dist/apps-server/server/node_modules/libpg-query/LICENSE +22 -0
  185. package/dist/apps-server/server/node_modules/libpg-query/README.md +275 -0
  186. package/dist/apps-server/server/node_modules/libpg-query/package.json +58 -0
  187. package/dist/apps-server/server/node_modules/libpg-query/wasm/index.cjs +369 -0
  188. package/dist/apps-server/server/node_modules/libpg-query/wasm/index.d.ts +48 -0
  189. package/dist/apps-server/server/node_modules/libpg-query/wasm/index.js +344 -0
  190. package/dist/apps-server/server/node_modules/libpg-query/wasm/libpg-query.js +2 -0
  191. package/dist/apps-server/server/node_modules/libpg-query/wasm/libpg-query.wasm +0 -0
  192. package/dist/apps-server/server/shim/host.css +22 -0
  193. package/dist/apps-server/server/shim/host.js +1 -0
  194. package/dist/cli/apps-check.d.ts +18 -0
  195. package/dist/cli/apps-check.d.ts.map +1 -1
  196. package/dist/cli/apps-check.js +179 -5
  197. package/dist/cli/apps-check.js.map +1 -1
  198. package/dist/cli/apps-produce.d.ts +9 -0
  199. package/dist/cli/apps-produce.d.ts.map +1 -0
  200. package/dist/cli/apps-produce.js +27 -0
  201. package/dist/cli/apps-produce.js.map +1 -0
  202. package/dist/cli/index.d.ts.map +1 -1
  203. package/dist/cli/index.js +15 -3
  204. package/dist/cli/index.js.map +1 -1
  205. package/dist/cli/insights-facts.d.ts +17 -0
  206. package/dist/cli/insights-facts.d.ts.map +1 -0
  207. package/dist/cli/insights-facts.js +56 -0
  208. package/dist/cli/insights-facts.js.map +1 -0
  209. package/dist/core/adapter.d.ts +85 -16
  210. package/dist/core/adapter.d.ts.map +1 -1
  211. package/dist/core/adapter.js +274 -54
  212. package/dist/core/adapter.js.map +1 -1
  213. package/dist/core/builtin-catalog.d.ts.map +1 -1
  214. package/dist/core/builtin-catalog.js +2 -0
  215. package/dist/core/builtin-catalog.js.map +1 -1
  216. package/dist/core/deliver-text.d.ts +42 -6
  217. package/dist/core/deliver-text.d.ts.map +1 -1
  218. package/dist/core/deliver-text.js +204 -27
  219. package/dist/core/deliver-text.js.map +1 -1
  220. package/dist/core/deliver.d.ts.map +1 -1
  221. package/dist/core/deliver.js +28 -7
  222. package/dist/core/deliver.js.map +1 -1
  223. package/dist/core/engine-roster.d.ts.map +1 -1
  224. package/dist/core/engine-roster.js +1 -0
  225. package/dist/core/engine-roster.js.map +1 -1
  226. package/dist/core/estate-mcp-client.d.ts +3 -2
  227. package/dist/core/estate-mcp-client.d.ts.map +1 -1
  228. package/dist/core/estate-mcp-client.js +3 -2
  229. package/dist/core/estate-mcp-client.js.map +1 -1
  230. package/dist/core/qe-acceptance-setting.d.ts.map +1 -1
  231. package/dist/core/qe-acceptance-setting.js +6 -0
  232. package/dist/core/qe-acceptance-setting.js.map +1 -1
  233. package/dist/core/run-identity.d.ts.map +1 -1
  234. package/dist/core/run-identity.js +3 -0
  235. package/dist/core/run-identity.js.map +1 -1
  236. package/dist/core/types.d.ts +5 -0
  237. package/dist/core/types.d.ts.map +1 -1
  238. package/dist/core/types.js.map +1 -1
  239. package/dist/editors/conformance-runtime.d.ts +107 -0
  240. package/dist/editors/conformance-runtime.d.ts.map +1 -1
  241. package/dist/editors/conformance-runtime.js +268 -13
  242. package/dist/editors/conformance-runtime.js.map +1 -1
  243. package/dist/editors/csp.d.ts +2 -2
  244. package/dist/editors/csp.d.ts.map +1 -1
  245. package/dist/editors/csp.js +4 -2
  246. package/dist/editors/csp.js.map +1 -1
  247. package/dist/editors/pack-install.d.ts +28 -13
  248. package/dist/editors/pack-install.d.ts.map +1 -1
  249. package/dist/editors/pack-install.js +96 -48
  250. package/dist/editors/pack-install.js.map +1 -1
  251. package/dist/editors/registry.d.ts +111 -8
  252. package/dist/editors/registry.d.ts.map +1 -1
  253. package/dist/editors/registry.js +183 -7
  254. package/dist/editors/registry.js.map +1 -1
  255. package/dist/editors/routes.d.ts +66 -13
  256. package/dist/editors/routes.d.ts.map +1 -1
  257. package/dist/editors/routes.js +277 -44
  258. package/dist/editors/routes.js.map +1 -1
  259. package/dist/evals/replay.d.ts +6 -0
  260. package/dist/evals/replay.d.ts.map +1 -1
  261. package/dist/evals/replay.js +24 -1
  262. package/dist/evals/replay.js.map +1 -1
  263. package/dist/evals/routes.d.ts.map +1 -1
  264. package/dist/evals/routes.js +17 -2
  265. package/dist/evals/routes.js.map +1 -1
  266. package/dist/evals/runner.d.ts.map +1 -1
  267. package/dist/evals/runner.js +5 -0
  268. package/dist/evals/runner.js.map +1 -1
  269. package/dist/evals/shape-corrections.d.ts +146 -0
  270. package/dist/evals/shape-corrections.d.ts.map +1 -0
  271. package/dist/evals/shape-corrections.js +394 -0
  272. package/dist/evals/shape-corrections.js.map +1 -0
  273. package/dist/evals/shape.d.ts +145 -0
  274. package/dist/evals/shape.d.ts.map +1 -0
  275. package/dist/evals/shape.js +376 -0
  276. package/dist/evals/shape.js.map +1 -0
  277. package/dist/evals/types.d.ts +2 -2
  278. package/dist/evals/types.d.ts.map +1 -1
  279. package/dist/evals/types.js +2 -1
  280. package/dist/evals/types.js.map +1 -1
  281. package/dist/insights/analyze.d.ts +14 -1
  282. package/dist/insights/analyze.d.ts.map +1 -1
  283. package/dist/insights/analyze.js +35 -8
  284. package/dist/insights/analyze.js.map +1 -1
  285. package/dist/insights/cost.d.ts +123 -0
  286. package/dist/insights/cost.d.ts.map +1 -0
  287. package/dist/insights/cost.js +221 -0
  288. package/dist/insights/cost.js.map +1 -0
  289. package/dist/insights/review-service.d.ts +20 -1
  290. package/dist/insights/review-service.d.ts.map +1 -1
  291. package/dist/insights/review-service.js +50 -25
  292. package/dist/insights/review-service.js.map +1 -1
  293. package/dist/insights/routes.d.ts +29 -0
  294. package/dist/insights/routes.d.ts.map +1 -1
  295. package/dist/insights/routes.js +62 -0
  296. package/dist/insights/routes.js.map +1 -1
  297. package/dist/insights/run-facts.d.ts +16 -0
  298. package/dist/insights/run-facts.d.ts.map +1 -1
  299. package/dist/insights/run-facts.js +26 -3
  300. package/dist/insights/run-facts.js.map +1 -1
  301. package/dist/interactive/bridge-pool.d.ts +11 -2
  302. package/dist/interactive/bridge-pool.d.ts.map +1 -1
  303. package/dist/interactive/bridge-pool.js +10 -1
  304. package/dist/interactive/bridge-pool.js.map +1 -1
  305. package/dist/interactive/chat-events.d.ts +74 -1
  306. package/dist/interactive/chat-events.d.ts.map +1 -1
  307. package/dist/interactive/chat-events.js +338 -6
  308. package/dist/interactive/chat-events.js.map +1 -1
  309. package/dist/interactive/doc-binding.d.ts +15 -0
  310. package/dist/interactive/doc-binding.d.ts.map +1 -1
  311. package/dist/interactive/doc-binding.js +4 -0
  312. package/dist/interactive/doc-binding.js.map +1 -1
  313. package/dist/interactive/doc-checks-routes.d.ts +34 -1
  314. package/dist/interactive/doc-checks-routes.d.ts.map +1 -1
  315. package/dist/interactive/doc-checks-routes.js +84 -0
  316. package/dist/interactive/doc-checks-routes.js.map +1 -1
  317. package/dist/interactive/draft-events.d.ts +7 -0
  318. package/dist/interactive/draft-events.d.ts.map +1 -1
  319. package/dist/interactive/draft-events.js +38 -6
  320. package/dist/interactive/draft-events.js.map +1 -1
  321. package/dist/interactive/draft-skill.d.ts +76 -6
  322. package/dist/interactive/draft-skill.d.ts.map +1 -1
  323. package/dist/interactive/draft-skill.js +219 -17
  324. package/dist/interactive/draft-skill.js.map +1 -1
  325. package/dist/interactive/edit-events.d.ts.map +1 -1
  326. package/dist/interactive/edit-events.js +4 -2
  327. package/dist/interactive/edit-events.js.map +1 -1
  328. package/dist/interactive/landing-guard.d.ts +47 -0
  329. package/dist/interactive/landing-guard.d.ts.map +1 -0
  330. package/dist/interactive/landing-guard.js +43 -0
  331. package/dist/interactive/landing-guard.js.map +1 -0
  332. package/dist/interactive/landing-record.d.ts +68 -0
  333. package/dist/interactive/landing-record.d.ts.map +1 -0
  334. package/dist/interactive/landing-record.js +154 -0
  335. package/dist/interactive/landing-record.js.map +1 -0
  336. package/dist/interactive/proposal-create.d.ts +3 -1
  337. package/dist/interactive/proposal-create.d.ts.map +1 -1
  338. package/dist/interactive/proposal-create.js +14 -2
  339. package/dist/interactive/proposal-create.js.map +1 -1
  340. package/dist/interactive/proposal-refine.d.ts +48 -0
  341. package/dist/interactive/proposal-refine.d.ts.map +1 -0
  342. package/dist/interactive/proposal-refine.js +99 -0
  343. package/dist/interactive/proposal-refine.js.map +1 -0
  344. package/dist/interactive/protected-edits.d.ts +67 -0
  345. package/dist/interactive/protected-edits.d.ts.map +1 -0
  346. package/dist/interactive/protected-edits.js +160 -0
  347. package/dist/interactive/protected-edits.js.map +1 -0
  348. package/dist/interactive/proxy-routes.js +2 -2
  349. package/dist/interactive/review-events.js +1 -1
  350. package/dist/interactive/run-units.d.ts +1 -1
  351. package/dist/interactive/run-units.d.ts.map +1 -1
  352. package/dist/interactive/run-units.js +8 -2
  353. package/dist/interactive/run-units.js.map +1 -1
  354. package/dist/interactive/source-packet.d.ts +66 -1
  355. package/dist/interactive/source-packet.d.ts.map +1 -1
  356. package/dist/interactive/source-packet.js +309 -60
  357. package/dist/interactive/source-packet.js.map +1 -1
  358. package/dist/interactive/theme-events.js +1 -1
  359. package/dist/knowledge/adapters/web/egress.d.ts +99 -0
  360. package/dist/knowledge/adapters/web/egress.d.ts.map +1 -0
  361. package/dist/knowledge/adapters/web/egress.js +330 -0
  362. package/dist/knowledge/adapters/web/egress.js.map +1 -0
  363. package/dist/knowledge/adapters/web/engine.d.ts +54 -0
  364. package/dist/knowledge/adapters/web/engine.d.ts.map +1 -0
  365. package/dist/knowledge/adapters/web/engine.js +101 -0
  366. package/dist/knowledge/adapters/web/engine.js.map +1 -0
  367. package/dist/knowledge/adapters/web/fetch.d.ts +131 -0
  368. package/dist/knowledge/adapters/web/fetch.d.ts.map +1 -0
  369. package/dist/knowledge/adapters/web/fetch.js +325 -0
  370. package/dist/knowledge/adapters/web/fetch.js.map +1 -0
  371. package/dist/knowledge/adapters/web/gate-web.d.ts +182 -0
  372. package/dist/knowledge/adapters/web/gate-web.d.ts.map +1 -0
  373. package/dist/knowledge/adapters/web/gate-web.js +496 -0
  374. package/dist/knowledge/adapters/web/gate-web.js.map +1 -0
  375. package/dist/knowledge/adapters/web/routes.d.ts +36 -0
  376. package/dist/knowledge/adapters/web/routes.d.ts.map +1 -0
  377. package/dist/knowledge/adapters/web/routes.js +99 -0
  378. package/dist/knowledge/adapters/web/routes.js.map +1 -0
  379. package/dist/knowledge/adapters/web/searxng.d.ts +89 -0
  380. package/dist/knowledge/adapters/web/searxng.d.ts.map +1 -0
  381. package/dist/knowledge/adapters/web/searxng.js +274 -0
  382. package/dist/knowledge/adapters/web/searxng.js.map +1 -0
  383. package/dist/knowledge/adapters/web/source.d.ts +65 -0
  384. package/dist/knowledge/adapters/web/source.d.ts.map +1 -0
  385. package/dist/knowledge/adapters/web/source.js +192 -0
  386. package/dist/knowledge/adapters/web/source.js.map +1 -0
  387. package/dist/knowledge/gate/gate.d.ts +22 -0
  388. package/dist/knowledge/gate/gate.d.ts.map +1 -1
  389. package/dist/knowledge/gate/gate.js +62 -1
  390. package/dist/knowledge/gate/gate.js.map +1 -1
  391. package/dist/knowledge/gate/sources.d.ts +2 -0
  392. package/dist/knowledge/gate/sources.d.ts.map +1 -1
  393. package/dist/knowledge/gate/sources.js +5 -2
  394. package/dist/knowledge/gate/sources.js.map +1 -1
  395. package/dist/knowledge/package.d.ts +7 -0
  396. package/dist/knowledge/package.d.ts.map +1 -1
  397. package/dist/knowledge/package.js +15 -1
  398. package/dist/knowledge/package.js.map +1 -1
  399. package/dist/knowledge/trackers/actions.js +1 -1
  400. package/dist/knowledge/trackers/actions.js.map +1 -1
  401. package/dist/knowledge/trackers/bindings.d.ts +3 -3
  402. package/dist/knowledge/trackers/bindings.d.ts.map +1 -1
  403. package/dist/knowledge/trackers/bindings.js +36 -23
  404. package/dist/knowledge/trackers/bindings.js.map +1 -1
  405. package/dist/knowledge/trackers/routes.js +1 -1
  406. package/dist/knowledge/trackers/routes.js.map +1 -1
  407. package/dist/learnings/service.d.ts.map +1 -1
  408. package/dist/learnings/service.js +2 -0
  409. package/dist/learnings/service.js.map +1 -1
  410. package/dist/mcp/broker.d.ts +8 -0
  411. package/dist/mcp/broker.d.ts.map +1 -1
  412. package/dist/mcp/broker.js +48 -3
  413. package/dist/mcp/broker.js.map +1 -1
  414. package/dist/mcp/estate-relay.d.ts +43 -1
  415. package/dist/mcp/estate-relay.d.ts.map +1 -1
  416. package/dist/mcp/estate-relay.js +38 -2
  417. package/dist/mcp/estate-relay.js.map +1 -1
  418. package/dist/mcp/registry.d.ts +6 -0
  419. package/dist/mcp/registry.d.ts.map +1 -1
  420. package/dist/mcp/registry.js +42 -3
  421. package/dist/mcp/registry.js.map +1 -1
  422. package/dist/mcp/run-fence.d.ts +57 -0
  423. package/dist/mcp/run-fence.d.ts.map +1 -0
  424. package/dist/mcp/run-fence.js +86 -0
  425. package/dist/mcp/run-fence.js.map +1 -0
  426. package/dist/mcp/tool-list.d.ts +5 -0
  427. package/dist/mcp/tool-list.d.ts.map +1 -1
  428. package/dist/mcp/tool-list.js +7 -3
  429. package/dist/mcp/tool-list.js.map +1 -1
  430. package/dist/presets/routes.d.ts.map +1 -1
  431. package/dist/presets/routes.js +6 -0
  432. package/dist/presets/routes.js.map +1 -1
  433. package/dist/projects/routes.d.ts +1 -1
  434. package/dist/projects/state-home-preflight.d.ts.map +1 -1
  435. package/dist/projects/state-home-preflight.js +2 -0
  436. package/dist/projects/state-home-preflight.js.map +1 -1
  437. package/dist/setup/tool-path.d.ts +16 -0
  438. package/dist/setup/tool-path.d.ts.map +1 -0
  439. package/dist/setup/tool-path.js +66 -0
  440. package/dist/setup/tool-path.js.map +1 -0
  441. package/dist/skills/plugin-source.d.ts +42 -88
  442. package/dist/skills/plugin-source.d.ts.map +1 -1
  443. package/dist/skills/plugin-source.js +140 -100
  444. package/dist/skills/plugin-source.js.map +1 -1
  445. package/dist/skills/runtime.d.ts.map +1 -1
  446. package/dist/skills/runtime.js +15 -7
  447. package/dist/skills/runtime.js.map +1 -1
  448. package/dist/skills/store.d.ts.map +1 -1
  449. package/dist/skills/store.js +25 -14
  450. package/dist/skills/store.js.map +1 -1
  451. package/dist/skills/usage.d.ts +238 -0
  452. package/dist/skills/usage.d.ts.map +1 -0
  453. package/dist/skills/usage.js +789 -0
  454. package/dist/skills/usage.js.map +1 -0
  455. package/dist/skills/venv.d.ts +18 -2
  456. package/dist/skills/venv.d.ts.map +1 -1
  457. package/dist/skills/venv.js +2 -2
  458. package/dist/skills/venv.js.map +1 -1
  459. package/dist/sources/routes.d.ts +3 -1
  460. package/dist/sources/routes.d.ts.map +1 -1
  461. package/dist/sources/routes.js +11 -0
  462. package/dist/sources/routes.js.map +1 -1
  463. package/dist/standing-orders/parse.d.ts +19 -0
  464. package/dist/standing-orders/parse.d.ts.map +1 -1
  465. package/dist/standing-orders/parse.js +61 -18
  466. package/dist/standing-orders/parse.js.map +1 -1
  467. package/dist/studio/apps-standalone/fixture.html +12 -0
  468. package/dist/studio/apps-standalone/fixture.js +10 -0
  469. package/dist/studio/apps-standalone/runtime.css +139 -0
  470. package/dist/studio/apps-standalone/runtime.js +1 -0
  471. package/dist/studio/assets/{KnowledgeGraph-Cpm46tEp.js → KnowledgeGraph-AtkRlS3c.js} +1 -1
  472. package/dist/studio/assets/index-CdbCAs7s.css +32 -0
  473. package/dist/studio/assets/index-DU_8o4uq.js +1104 -0
  474. package/dist/studio/editors/wicked-apps/editor.json +1 -1
  475. package/dist/studio/editors/wicked-apps/index.html +2 -2
  476. package/dist/studio/editors/wicked-deck/editor.json +1 -1
  477. package/dist/studio/editors/wicked-deck/index.html +14 -1
  478. package/dist/studio/editors/wicked-doc/editor.json +1 -1
  479. package/dist/studio/editors/wicked-doc/index.html +1 -1
  480. package/dist/studio/editors/wicked-insights/editor.json +1 -1
  481. package/dist/studio/editors/wicked-insights/index.html +1 -1
  482. package/dist/studio/editors/wicked-page/editor.json +10 -1
  483. package/dist/studio/editors/wicked-page/index.html +2 -2
  484. package/dist/studio/editors/wicked-video/editor.json +7 -2
  485. package/dist/studio/editors/wicked-video/index.html +14 -11
  486. package/dist/studio/index.html +2 -2
  487. package/dist/studio/testid-inventory.json +2069 -242
  488. package/dist/team/routes.d.ts +11 -1
  489. package/dist/team/routes.d.ts.map +1 -1
  490. package/dist/team/routes.js +27 -0
  491. package/dist/team/routes.js.map +1 -1
  492. package/dist/workflow-catalog/build-v2.d.ts +94 -0
  493. package/dist/workflow-catalog/build-v2.d.ts.map +1 -0
  494. package/dist/workflow-catalog/build-v2.js +551 -0
  495. package/dist/workflow-catalog/build-v2.js.map +1 -0
  496. package/dist/workflow-catalog/catalog-data-v2.d.ts +12 -0
  497. package/dist/workflow-catalog/catalog-data-v2.d.ts.map +1 -0
  498. package/dist/workflow-catalog/catalog-data-v2.js +2787 -0
  499. package/dist/workflow-catalog/catalog-data-v2.js.map +1 -0
  500. package/dist/workflow-catalog/catalog-data.d.ts.map +1 -1
  501. package/dist/workflow-catalog/catalog-data.js +2 -20
  502. package/dist/workflow-catalog/catalog-data.js.map +1 -1
  503. package/dist/workflow-catalog/detect-service.d.ts +95 -0
  504. package/dist/workflow-catalog/detect-service.d.ts.map +1 -0
  505. package/dist/workflow-catalog/detect-service.js +239 -0
  506. package/dist/workflow-catalog/detect-service.js.map +1 -0
  507. package/dist/workflow-catalog/detect.d.ts +213 -0
  508. package/dist/workflow-catalog/detect.d.ts.map +1 -0
  509. package/dist/workflow-catalog/detect.js +653 -0
  510. package/dist/workflow-catalog/detect.js.map +1 -0
  511. package/dist/workflow-catalog/seeds-v2.d.ts +91 -0
  512. package/dist/workflow-catalog/seeds-v2.d.ts.map +1 -0
  513. package/dist/workflow-catalog/seeds-v2.js +2 -0
  514. package/dist/workflow-catalog/seeds-v2.js.map +1 -0
  515. package/dist/workflow-catalog/shape.d.ts +99 -0
  516. package/dist/workflow-catalog/shape.d.ts.map +1 -0
  517. package/dist/workflow-catalog/shape.js +103 -0
  518. package/dist/workflow-catalog/shape.js.map +1 -0
  519. package/dist/working-doc/bridge-backend.js +2 -2
  520. package/dist/working-doc/event-lines.d.ts +67 -2
  521. package/dist/working-doc/event-lines.d.ts.map +1 -1
  522. package/dist/working-doc/event-lines.js +155 -8
  523. package/dist/working-doc/event-lines.js.map +1 -1
  524. package/dist/working-doc/notes-index.d.ts +35 -0
  525. package/dist/working-doc/notes-index.d.ts.map +1 -0
  526. package/dist/working-doc/notes-index.js +82 -0
  527. package/dist/working-doc/notes-index.js.map +1 -0
  528. package/dist/working-doc/routes.js +4 -4
  529. package/dist/working-doc/sections.js +2 -2
  530. package/dist/working-doc/service.d.ts +260 -21
  531. package/dist/working-doc/service.d.ts.map +1 -1
  532. package/dist/working-doc/service.js +791 -90
  533. package/dist/working-doc/service.js.map +1 -1
  534. package/dist/working-doc/store.d.ts +50 -1
  535. package/dist/working-doc/store.d.ts.map +1 -1
  536. package/dist/working-doc/store.js +4 -1
  537. package/dist/working-doc/store.js.map +1 -1
  538. package/endpoint-manifest.json +219 -5
  539. package/evals/corpora/shape-corrections-v1.json +594 -0
  540. package/evals/corpora/shape-corrections-v1.seat-fixture.json +186 -0
  541. package/evals/corpora/shape-v1.json +2113 -0
  542. package/evals/corpora/shape-v1.seat-fixture.json +1800 -0
  543. package/package.json +31 -8
  544. package/scripts/apps-render.py +226 -0
  545. package/workflows/detect-shape.json +29 -0
  546. package/dist/studio/assets/index-BRBwWQMH.css +0 -32
  547. package/dist/studio/assets/index-CVrWDGRP.js +0 -1097
@@ -1,9 +1,10 @@
1
1
  import { REVIEW_WORKFLOW } from '../insights/workflow.js';
2
+ import { appsRuntimeDir, appsServerArtifact, containerEngineKnown } from '../apps/publish/artifacts.js';
2
3
  import { busSeamsOffWarning, busUnavailableWarning } from '../core/bus-notice.js';
3
4
  import { vaultBinWarning, vaultDiagnostics } from '../core/vault-bin.js';
4
5
  import { PlanSchema, toLaunchPlan } from './plan-schema.js';
5
6
  import { record, z } from '../zod.js';
6
- import { listRequirementsRead, getRequirement, patchRequirement, readRequirementsGraph, REQUIREMENTS_NOT_GENERATED, } from './requirements.js';
7
+ import { listRequirementsRead, setRepoMinimum, getRequirement, patchRequirement, readRequirementsGraph, REQUIREMENTS_NOT_GENERATED, } from './requirements.js';
7
8
  import { randomUUID } from 'node:crypto';
8
9
  import { homedir } from 'node:os';
9
10
  import { readFileSync, existsSync, mkdirSync, realpathSync } from 'node:fs';
@@ -24,15 +25,26 @@ function ensureDir(dir) {
24
25
  function turnReadRoots(scratchRoot) {
25
26
  if (!beneathSupported())
26
27
  return [];
28
+ const real = seatPathOf(scratchRoot);
29
+ const roots = [];
27
30
  try {
28
31
  ensureRealDir(contextReadRoots(scratchRoot).open);
29
32
  ensureRealDir(contextReadRoots(scratchRoot).context);
33
+ roots.push(join(real, 'open'), join(real, 'context'));
30
34
  }
31
35
  catch {
32
- return [];
36
+ // no artifact copies or run briefs this run; the requirements maps are tried on their own
33
37
  }
34
- const real = seatPathOf(scratchRoot);
35
- return [join(real, 'open'), join(real, 'context')];
38
+ // crew#1412: the requirements maps each message hands the seats (`chat-requirements.ts`). Each folder on its own
39
+ // (codex r1/r2): one that cannot be made costs only what it holds, never the other roots.
40
+ try {
41
+ ensureRealDir(join(scratchRoot, REQUIREMENTS_MAP_DIR));
42
+ roots.push(join(real, REQUIREMENTS_MAP_DIR));
43
+ }
44
+ catch {
45
+ // the maps' own publication reports it
46
+ }
47
+ return roots;
36
48
  }
37
49
  import { detectRefusal, isOpenGate, offeredChoices, replayOpenGate } from './gate-cache.js';
38
50
  import { acceptanceRequirementOf, buildAcceptanceView } from '../qe/acceptance.js';
@@ -53,9 +65,10 @@ import { chatSeatAdmission, homeless } from './seat-standing.js';
53
65
  import { seatGovernanceDiagnostics, seatGovernanceWarnings, } from './seat-governance.js';
54
66
  import { seatWorkDefaultNow } from './seat-work-default.js';
55
67
  import { ROSTER_REFRESH_WAIT_MS, rosterWithStandingFactory } from './roster-standing.js';
56
- import { SeatContainerStatus, gatewayDirOf, isContainerLoginCli, isContainerSeatFloor, isHostSeatFloor, loginDetail, runSeatLogin, seatLoginDepsFor, } from './seat-container-login.js';
68
+ import { SeatContainerStatus, gatewayDirOf, isContainerLoginCli, isContainerSeatFloor, isHostSeatFloor, loginDetail, registerSeatContainerLoginRoutes, seatLoginDepsFor, } from './seat-container-login.js';
57
69
  import { ChatTurnIndex } from './chat-turns.js';
58
- import { CHAT_ID, chatMakeDigest, ChatScopeIndex, chatScopeDeps, chatScopeStatement, prepareChatScratch, removeChatScratch, namedKindRefusal, resolveChatScope, } from './chat-scope.js';
70
+ import { CHAT_ID, chatJobTurnLines, chatMakeDigest, ChatScopeIndex, chatScopeDeps, chatScopeStatement, prepareChatScratch, removeChatScratch, namedKindRefusal, resolveChatScope, } from './chat-scope.js';
71
+ import { buildRequirementsMaps, publishRequirementsMaps, REQUIREMENTS_MAP_DIR } from './chat-requirements.js';
59
72
  import { ASK_TURN_BUDGET_SECS, AskPathIndex, isAskTurn } from './ask-paths.js';
60
73
  import { chatTurnStep, resolveChatWorkflow, servedChatWorkflows, writeCapableStep } from './chat-workflow.js';
61
74
  import { reassignRefusedSeats } from '../core/reassign-refusal.js';
@@ -68,9 +81,13 @@ import { TestSetIndex } from '../qe/test-sets.js';
68
81
  import { estateExe, parseEstateTotals, readBlastRadiusPages, resolveProjectGraphBinding } from '../projects/graph.js';
69
82
  import { registerProjectRoutes } from '../projects/routes.js';
70
83
  import { registerProjectAggregateRoutes } from './project-aggregates.js';
71
- import { registerProductRoutes } from './product.js';
84
+ import { composeLaunch, composePreflight, registerProductRoutes } from './product.js';
85
+ import { buildWorkflowCatalogV2, parseCommand, resolveOption } from '../workflow-catalog/build-v2.js';
86
+ import { DEFAULT_PROJECT_ID } from '../projects/default-project.js';
87
+ import { DETECT_MAX_CHARS, DETECT_TIMEOUT_MS, DetectService, shadowCheck } from '../workflow-catalog/detect-service.js';
88
+ import { checkLaunchShape, LaunchShapeSchema, launchShapeOf, servedFor, withBriefLines } from '../workflow-catalog/shape.js';
72
89
  import { registerPresetRoutes } from '../presets/routes.js';
73
- import { registerTeamRoutes } from '../team/routes.js';
90
+ import { busRows, openPlanGateRev, registerTeamRoutes, workPlanAccepted } from '../team/routes.js';
74
91
  import { registerCampaignRoutes } from '../campaigns/routes.js';
75
92
  import { registerGovernanceWikiRoutes } from './governance-wiki.js';
76
93
  import { DEFAULT_STEERING_TYPE, STEERING_TYPE_VALUES, STEERING_TYPES, registerGovernanceSteeringRoutes, } from './governance-steering.js';
@@ -82,7 +99,8 @@ import { registerDefaultEvalRoutes, runAndRecord } from '../evals/routes.js';
82
99
  import { prepareRunEvalsLaunch, RUN_EVALS_WORKFLOW } from '../evals/workflow.js';
83
100
  import { defaultReplaySet } from '../evals/replay.js';
84
101
  import { gardenRootFor } from '../learn/scheduler.js';
85
- import { DEMO_PRESET, demoLaunchRoots, registerDemoDocumentRoute, registerDemoRoutes, registerWalkthroughRoutes, walkthroughAcceptance } from './recording.js';
102
+ import { agentMay } from '../knowledge/gate/access.js';
103
+ import { DEMO_PRESETS, demoLaunch, demoLaunchRoots, registerDemoDocumentRoute, registerDemoRoutes, registerWalkthroughRoutes, walkthroughAcceptance } from './recording.js';
86
104
  import { projectDocsRoot } from '../interactive/project-root.js';
87
105
  import { registerSkillsRoutes } from './skills.js';
88
106
  import { registerSourceRoutes } from '../sources/routes.js';
@@ -107,13 +125,16 @@ import { isHumanOperator } from './watch-routes.js';
107
125
  import { boundOrigin, InteractiveBridgePool } from '../interactive/bridge-pool.js';
108
126
  import { defaultInteractiveRoot } from '../interactive/bridge-root.js';
109
127
  import { composeDeliverText, configuredPublicOrigin, extractFollowUps, factsFromRun, reportsFromOutputs, FOLLOW_UPS_MAX, framedDeliverText, runUrlFor, } from '../core/deliver-text.js';
110
- import { deliverIdentityFor, deliverRepoFor, deliverTargetView, isGitHubLogin, pushIdentityOf, readDeliverOriginUrl, resolvePullRequest as resolvePullRequestViaGh, unverifiedTreesFrom, } from '../core/deliver.js';
128
+ import { deliverIdentityFor, defaultGhExec, deliverRepoFor, deliverTargetView, isGitHubLogin, pushIdentityOf, readDeliverOriginUrl, resolvePullRequest as resolvePullRequestViaGh, unverifiedTreesFrom, } from '../core/deliver.js';
111
129
  import { credentialsMissingIn, deliverCredentialsProbe, missingCredentials } from '../core/deliver-credentials.js';
112
130
  import { codebaseArchiveUrl } from './codebase-archive.js';
113
131
  import { projectRepoCandidates } from '../interactive/doc-grounding.js';
114
132
  import { artifactStatus, beneathSupported, buildTurnContext, chatMount, ChatMessageContextSchema, contextReadRoots, ensureRealDir, sha256Hex, parseArtifactRef, readGroundingBeneath, seatPathOf, UNFILED_MOUNT, } from './chat-context.js';
115
133
  import { createDocInProcess, registerInteractiveProxy } from '../interactive/proxy-routes.js';
116
134
  import { CreateLauncher } from '../interactive/proposal-create.js';
135
+ import { ThemeLauncher } from './proposal-theme.js';
136
+ import { RefineLauncher } from '../interactive/proposal-refine.js';
137
+ import { lineageSteps, protectedEdits } from '../interactive/protected-edits.js';
117
138
  import { buildRunBrief } from './run-brief.js';
118
139
  import { readBeneath } from './beneath.js';
119
140
  /** A context brief copied into a document's packet, at most (the packet's per-file cap). */
@@ -121,7 +142,11 @@ const BRIEF_COPY_MAX = 512 * 1024;
121
142
  import { registerInteractiveDocDelete } from '../interactive/doc-delete-routes.js';
122
143
  import { registerInteractiveDocChecks } from '../interactive/doc-checks-routes.js';
123
144
  import { crewStateHome, stateHomeOfDb } from '../projects/state-home.js';
124
- import { ChatProposals, LaunchOnceRegistry, RecordingStubDispatcher, runCostFromEvents } from './chat-proposals.js';
145
+ import { demoShowOf, factsOf, inputLines, jobInputsOfProposal, jobLaunchCommon, personPid, requestDigest, SELF_SEATED } from './chat-jobs.js';
146
+ import { DocumentsRefused, documentsClause, RUN_DOCS_TOKENS_MAX, stagedDocumentsOf, stageRunDocuments } from './run-documents.js';
147
+ import { checkSourcePick, projectSources, RUN_SOURCES_MAX, runSourcesDeps, webScopeReason } from './run-sources.js';
148
+ import { CATALOG_V2_CARDS } from '../workflow-catalog/catalog-data-v2.js';
149
+ import { ChatProposals, LaunchOnceRegistry, proposalRunId, RecordingStubDispatcher, RevisionEditsSchema, runCostFromEvents } from './chat-proposals.js';
125
150
  import { CATALOG_SEEDS } from '../workflow-catalog/catalog-data.js';
126
151
  import { registerInteractiveDocList } from '../interactive/doc-list-routes.js';
127
152
  import { REVIEWS_DIRNAME } from '../interactive/review-ledger.js';
@@ -155,7 +180,9 @@ import { VoiceInjectInputs } from '../voice/inject-input.js';
155
180
  import { GroupIndex } from './group-index.js';
156
181
  import { RunTimingIndex, recordRunLaunched } from './run-timing-index.js';
157
182
  import { GuidanceIndex } from './guidance-index.js';
158
- import { DELIVER_REQUESTED_ACTION, DeliveryIndex, gitRunBranchIsEmpty, gitWorktreeIsClean, isDeliverConflictStranded, deliveryRecordFrom, deliverUnitOf, pushedState, canDeliverResolver, FREE_TEXT_NOTICE, freeTextOutcome, } from './delivery-index.js';
183
+ import { DELIVER_REQUESTED_ACTION, DeliveryIndex, gitRunBranchIsEmpty, gitWorktreeIsClean, isDeliverConflictStranded, deliveryRecordFrom, readDeliveredCommit, deliverUnitOf, pushedState, canDeliverResolver, FREE_TEXT_NOTICE, freeTextOutcome, } from './delivery-index.js';
184
+ import { REVIEW_CHANGE_WORKFLOW, reviewChangeExclusion } from './review-change.js';
185
+ import { rosterWithout } from '../interactive/review-events.js';
159
186
  import { DeliveryDerivationCache } from './delivery-cache.js';
160
187
  import { gitReprovisionWorktree, runDeliverScript, } from './post-hoc-deliver.js';
161
188
  import { LOCAL_ACTOR, trustAtLeast, viewOf } from './auth.js';
@@ -170,16 +197,18 @@ import { registerDecisionRoutes } from '../decisions/routes.js';
170
197
  import { ChatDecisionRecorder } from '../decisions/chat-recorder.js';
171
198
  import { ConsiderationService } from '../decisions/consider.js';
172
199
  import { gardenConformance, gardenPackCheck } from '../editors/pack-install.js';
173
- import { conformanceProvisioner, conformanceRuntimeRoot } from '../editors/conformance-runtime.js';
200
+ import { conformanceProvisioner, conformanceRuntimeReady, conformanceRuntimeRoot, conformanceVenvDir, editorPluginLaunchListener, venvPython } from '../editors/conformance-runtime.js';
174
201
  import { EditorRegistry } from '../editors/registry.js';
175
- import { registerEditorRoutes } from '../editors/routes.js';
202
+ import { registerEditorRoutes, unitTokenProbe } from '../editors/routes.js';
176
203
  import { AppWritePath } from '../apps/actions/write-path.js';
177
204
  import { AppExecutor } from '../apps/exec/executor.js';
178
205
  import { localViewerOf } from '../apps/exec/viewer.js';
179
206
  import { registerAppRoutes } from '../apps/routes.js';
180
207
  import { AppStoreError } from '../apps/store.js';
181
208
  import { registerMcpInspectRoutes } from '../mcp-inspect/routes.js';
209
+ import { daemonRunFence, fencedRunId } from '../mcp/run-fence.js';
182
210
  import { discoverLivePlugin } from '../skills/plugin-source.js';
211
+ import { onboardFailure, readRepoPath, registerFailure } from './repo-input.js';
183
212
  import { resolveDecisionsMode } from '../decisions/types.js';
184
213
  const V = API_PREFIX;
185
214
  /** How long `GET /health` waits on the engine's actor before answering `ping: "busy"` (crew#471). */
@@ -221,11 +250,6 @@ function codeGraphDbOr503(repo, reply) {
221
250
  return null;
222
251
  }
223
252
  }
224
- /**
225
- * `true` after answering **409** when the repo's registered folder is gone, BEFORE anything spawns
226
- * there: Node reports a missing spawn `cwd` as `spawn <binary> ENOENT`, which named an installed
227
- * binary as the fault (rig, tiny-math). The words are the finding's, the same everywhere.
228
- */
229
253
  function refusedMissingFolder(repo, reply) {
230
254
  const missing = repoFolderMissing(repo);
231
255
  if (missing === null)
@@ -236,6 +260,22 @@ function refusedMissingFolder(repo, reply) {
236
260
  function message(err) {
237
261
  return err instanceof Error ? err.message : String(err);
238
262
  }
263
+ /**
264
+ * What the shared launch function answers (DES-CHAT-FIRST-001 C3): the status and body `POST /runs` sends. Shaped like
265
+ * the reply the route body was written against, so the launch policy reads the same in one place for every launcher.
266
+ */
267
+ export class LaunchReply {
268
+ statusCode = 200;
269
+ payload = undefined;
270
+ code(statusCode) {
271
+ this.statusCode = statusCode;
272
+ return this;
273
+ }
274
+ send(payload) {
275
+ this.payload = payload;
276
+ return this;
277
+ }
278
+ }
239
279
  /**
240
280
  * Turns a failed parse into a 400 body, naming any field the schema does not know.
241
281
  *
@@ -368,6 +408,8 @@ const RULE_STATUSES = new Set(['active', 'retired', 'all']);
368
408
  // Repo names become directory components under ~/.wicked/repos/ — reject anything
369
409
  // that would allow path traversal (slashes, dots-only segments, control chars).
370
410
  const SAFE_REPO_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
411
+ /** `PUT /repos/:id/requirements/minimum` (api-types 0.197.0 `RequirementsMinimumBody`): `null` clears. */
412
+ export const ReqMinimumSchema = z.strictObject({ minPct: z.number().int().min(1).max(100).nullable() });
371
413
  export const RegisterRepoSchema = z.strictObject({
372
414
  name: z
373
415
  .string()
@@ -427,6 +469,17 @@ const ExcludeLinkedIssuesSchema = z
427
469
  .array(z.string().regex(/^\s*(?:\d+|(?:(?:[\w.-]+\/)?[\w.-]+)?#\d+)\s*$/, 'an issue ref: 541, #541, repo#541 or owner/repo#541'))
428
470
  .max(50)
429
471
  .optional();
472
+ /**
473
+ * F43: the seats a chat job (or a chat document's helpers) may name, and the ones its Start re-checks, in roster order:
474
+ * the seats that can work now (enabled for council, work-eligible, not signed out) under the default launch rule
475
+ * ({@link defaultLaunchRoster}: no opt-in seat unless it is the only one left). Filtered first, so a seat the predicate
476
+ * drops never hides the fallback. The standing rows carry no `optIn` (only `GET /roster` marks it, `markOptIn`), so the
477
+ * opt-in rule reads the key.
478
+ */
479
+ export function proposalRoster(standing) {
480
+ const canWork = standing.filter((s) => s.enabled_for_council && s.seat_eligible_for_work !== false && s.auth !== 'signed_out');
481
+ return defaultLaunchRoster(canWork).map((s) => ({ key: String(s.key), name: s.display_name || String(s.key) }));
482
+ }
430
483
  /**
431
484
  * The default launch roster ({@link defaultLaunchRoster}: no opt-in seats) — plus the opt-in seat a
432
485
  * launch NAMES as its lead (`primary`): naming it is the opt-in.
@@ -560,6 +613,16 @@ export const LaunchSchema = z.strictObject({
560
613
  * and the engine refuses either on a run whose workflow does not require QE acceptance. */
561
614
  skipQeAcceptance: z.strictObject({ reason: z.string().trim().min(1).max(2000) }).optional(),
562
615
  forceQeAcceptance: z.boolean().optional(),
616
+ /** (api-types 0.192.0, DES-CATALOG-002 §4.4) What this launch is the shape of; judged against the current catalog. */
617
+ shape: LaunchShapeSchema.optional(),
618
+ /** (DES-CATALOG-002 §2.d piece 2, CS4) The documents the run reads: chat source tokens, authorised again against
619
+ * `chatId` and staged read-only before the engine is called. `[]` = none (a retry inherits nothing). */
620
+ documents: z.array(z.string().trim().min(1).max(300)).max(RUN_DOCS_TOKENS_MAX).optional(),
621
+ /** (DES-CATALOG-002 §2.d piece 4, CS4) The run's source pick (registered source names); `[]` = none. */
622
+ sources: z.array(z.string().trim().min(1).max(100)).max(RUN_SOURCES_MAX).optional(),
623
+ }).refine((b) => b.documents === undefined || b.documents.length === 0 || b.chatId !== undefined, {
624
+ path: ['documents'],
625
+ error: 'documents are chat tokens: send the chatId they were named in',
563
626
  }).refine((b) => b.skipQeAcceptance === undefined || b.forceQeAcceptance !== true, {
564
627
  path: ['forceQeAcceptance'],
565
628
  error: 'skipQeAcceptance and forceQeAcceptance are mutually exclusive — skip it with a reason, or force it',
@@ -593,13 +656,23 @@ export const LaunchSchema = z.strictObject({
593
656
  * re-runs the judge of a `judge_unavailable` gate on the same work, the step's seat not run again.
594
657
  * The ENGINE refuses each at any other gate (a 409 naming the gate it answers) — and `rejudge`
595
658
  * while no judge seat is eligible ({@link GateInfo.rejudge} says beforehand). */
596
- export const ESCALATION_ACTIONS = ['extend', 'targeted', 'accept_partial', 'accept_suggestion', 'rejudge', 'retry_rules'];
597
- /** (DES-RULE-CHECK-001 S2, api-types 0.190.0) At a `rules_unchecked` gate (a steering rule no judge
598
- * ruled on): `retry_rules` (an escalation arm above) re-runs the rule check on the same work, the
599
- * step's seat not run again; `skip_rules` skips unchecked rules, each with a written reason
600
- * (`skipRules: [{id, reason}]`, required), then re-runs it. A skip is labelled on the run, the gate
601
- * and the delivery receipts. The engine refuses both at any other gate, and a skip of a rule that
602
- * is not unchecked (a broken rule denies). Skipping is the human operator's call alone. */
659
+ export const ESCALATION_ACTIONS = ['extend', 'targeted', 'accept_partial', 'accept_suggestion', 'rejudge', 'retry_rules', 'retry_qe'];
660
+ /** (e2e-1105 F23, api-types 0.195.0) `retry_qe` (an escalation arm above): REDO THE QE CHECK at the gate of the run's QE
661
+ * step whose isolated reviewer gave no verdict on the work (INCONCLUSIVE, no reviewer seat, or no bound verdict). The
662
+ * engine (wicked-core `HumanDecision::RetryQe`, core#1312) runs the QE step again from fresh evidence with a new
663
+ * isolated reviewer session, never on an author of the work outside reduced assurance; it is never a verdict (QE stays required, only that
664
+ * reviewer's PASS counts) and is capped at 2 per QE step and tree. The engine refuses it (409) at any other gate,
665
+ * at the cap, and when no reviewer seat can run now. */
666
+ /** (DES-RULE-CHECK-001 S2, api-types 0.190.0) At a gate the steering-rule check holds or denies:
667
+ * `retry_rules` (an escalation arm above) re-runs the rule check on the same work, the step's seat
668
+ * not run again; `skip_rules` skips held rules (unchecked, a waiver to confirm, or, rev 2 / api-types
669
+ * 0.193.0, disputed: no council ruling), each with a written reason (`skipRules: [{id, reason}]`,
670
+ * required), then re-runs it. A skip is labelled on the run, the gate and the delivery receipts.
671
+ * Since wicked-core-ts 0.15.30 the engine takes both wherever a rule layer is in the gated unit's
672
+ * denial record (behind a reviewer's FAIL, at `review_adjudication`), refuses them at any other
673
+ * gate, and refuses a skip of a rule that is not held (a broken rule denies, a council's broken
674
+ * ruling too): crew forwards both unfiltered, so the engine is the one check, and its refusal is
675
+ * the 409. Skipping is the human operator's call alone. */
603
676
  export const SKIP_RULES_ACTION = 'skip_rules';
604
677
  /** (core#820) A consent gate's answer token: `consent:<choice id>` approves that row of the dry-run
605
678
  * plan (the engine refuses an id its plan does not offer); `reject` stays the decline. */
@@ -657,6 +730,9 @@ export const GateSchema = z.strictObject({
657
730
  /** api-types 0.44.0 — the gate this decision answers (its unit `ord`). A mismatch with the run's
658
731
  * open gate is a 409 `gate_changed`: the decision was made on a gate that is no longer open. */
659
732
  ord: z.int().nonnegative().optional(),
733
+ /** (api-types 0.192.0, DES-CATALOG-002 §4.6) At a `plan_approval` gate: the plan revision this answer was made on.
734
+ * Passed with `ord` into the engine's own serialized decision, which refuses a stale one (`gate_changed`). */
735
+ planRev: z.int().nonnegative().optional(),
660
736
  /** (api-types 0.156.0, DES-VOICE) The person answered by voice and confirmed it on screen: recorded on the
661
737
  * `gate.decided` audit line and the decided-gate history ("by voice, confirmed"). It grants nothing. */
662
738
  input: z.literal('voice').optional(),
@@ -665,15 +741,15 @@ export const GateSchema = z.strictObject({
665
741
  * declined. Absent = every drafted rule lands, as before. 409 `no_draft` unless the run waits at its
666
742
  * steering-author propose gate with a readable draft; 400 with anything but a plain approve. */
667
743
  keepRules: z.array(z.string().min(1).max(256)).max(500).optional(),
668
- /** (DES-RULE-CHECK-001 S2, api-types 0.190.0) With `action: 'skip_rules'`: the unchecked rules to
669
- * skip, each with the person's written reason. */
744
+ /** (DES-RULE-CHECK-001 S2, api-types 0.190.0) With `action: 'skip_rules'`: the held rules to skip
745
+ * (unchecked, waived or disputed), each with the person's written reason. */
670
746
  skipRules: z
671
747
  .array(z.strictObject({ id: z.string().trim().min(1).max(256), reason: z.string().trim().min(1).max(2000) }))
672
748
  .min(1)
673
749
  .max(500)
674
750
  .optional(),
675
- }).refine((b) => (b.action === SKIP_RULES_ACTION) === (b.skipRules !== undefined), { path: ['skipRules'], error: 'skip_rules needs `skipRules`: [{id, reason}] for each unchecked rule you skip, each with your written reason; skipRules goes with skip_rules only' }).refine((b) => b.action !== SKIP_RULES_ACTION || (b.approve && b.amend === undefined && b.amendScope === undefined && b.plan === undefined), { path: ['action'], error: 'skip_rules takes approve: true and no amend, amendScope or plan — the reasons ride skipRules' }).refine((b) => b.skipRules === undefined || new Set(b.skipRules.map((r) => r.id)).size === b.skipRules.length, { path: ['skipRules'], error: 'skipRules names a rule twice' }).refine((b) => b.keepRules === undefined || (b.approve && (b.action === undefined || b.action === 'approve') && b.plan === undefined), { path: ['keepRules'], error: 'keepRules goes with a plain approve (no action other than approve, no plan) of a steering-author propose gate' }).refine((b) => b.action === undefined
676
- || (b.action === 'approve' || b.action === 'edit_plan' || b.action === 'amend_intent' || b.action === OPERATOR_JUDGMENT_ACTION || b.action === SKIP_QE_ACTION || b.action === SKIP_RULES_ACTION || isEscalationAction(b.action)) === b.approve, { path: ['action'], error: '`action` disagrees with `approve`: request_changes and reject require approve: false; approve, edit_plan, amend_intent, operator_judgment, skip_qe, skip_rules, extend, targeted, accept_partial, accept_suggestion, rejudge, retry_rules and consent:<id> require approve: true' }).refine(
751
+ }).refine((b) => (b.action === SKIP_RULES_ACTION) === (b.skipRules !== undefined), { path: ['skipRules'], error: 'skip_rules needs `skipRules`: [{id, reason}] for each rule you skip (unchecked, waived or disputed), each with your written reason; skipRules goes with skip_rules only' }).refine((b) => b.action !== SKIP_RULES_ACTION || (b.approve && b.amend === undefined && b.amendScope === undefined && b.plan === undefined), { path: ['action'], error: 'skip_rules takes approve: true and no amend, amendScope or plan — the reasons ride skipRules' }).refine((b) => b.skipRules === undefined || new Set(b.skipRules.map((r) => r.id)).size === b.skipRules.length, { path: ['skipRules'], error: 'skipRules names a rule twice' }).refine((b) => b.keepRules === undefined || (b.approve && (b.action === undefined || b.action === 'approve') && b.plan === undefined), { path: ['keepRules'], error: 'keepRules goes with a plain approve (no action other than approve, no plan) of a steering-author propose gate' }).refine((b) => b.action === undefined
752
+ || (b.action === 'approve' || b.action === 'edit_plan' || b.action === 'amend_intent' || b.action === OPERATOR_JUDGMENT_ACTION || b.action === SKIP_QE_ACTION || b.action === SKIP_RULES_ACTION || isEscalationAction(b.action)) === b.approve, { path: ['action'], error: '`action` disagrees with `approve`: request_changes and reject require approve: false; approve, edit_plan, amend_intent, operator_judgment, skip_qe, skip_rules, extend, targeted, accept_partial, accept_suggestion, rejudge, retry_rules, retry_qe and consent:<id> require approve: true' }).refine(
677
753
  // (operator ruling 2026-10-21) The override's rationale IS its record: a blank one is a 400 here,
678
754
  // before the engine is asked.
679
755
  (b) => b.action !== OPERATOR_JUDGMENT_ACTION || (b.amend !== undefined && b.amend.trim() !== ''), { path: ['amend'], error: 'operator_judgment needs `amend`: your written rationale — why the failed floor is not the work\'s (an empty one is refused)' }).refine((b) => b.action !== OPERATOR_JUDGMENT_ACTION || (b.amendScope === undefined && b.plan === undefined), { path: ['amendScope'], error: 'operator_judgment takes no amendScope or plan — it answers the failed floor of the gated unit' }).refine(
@@ -682,7 +758,7 @@ export const GateSchema = z.strictObject({
682
758
  // (wicked-core#555) An intent amendment IS its text: an empty one amends nothing, and the arm's
683
759
  // scope is every unit at or after the cursor — which is what makes it reach the evaluator — so
684
760
  // `amendScope` cannot narrow it. Both are 400s here rather than a 409 from the engine.
685
- (b) => b.action !== 'amend_intent' || (b.amend !== undefined && b.amend.trim() !== ''), { path: ['amend'], error: 'amend_intent needs `amend`: what the run\'s acceptance list now says (approve without an action to proceed unamended)' }).refine((b) => b.action !== 'amend_intent' || (b.amendScope === undefined && b.plan === undefined), { path: ['amendScope'], error: 'amend_intent takes no amendScope or plan — an intent amendment reaches every unit at or after the cursor, which is what makes it reach the evaluator' }).refine((b) => !isEscalationAction(b.action) || (b.amend === undefined && b.amendScope === undefined && b.plan === undefined), { path: ['action'], error: 'extend, targeted, accept_partial, accept_suggestion, rejudge, retry_rules and consent:<id> take no amend, amendScope or plan — the engine re-runs the floor, adopts the pinned edit, re-runs the judge or the rule check, or runs the chosen install as it stands' }).refine((b) => (b.action === 'edit_plan') === (b.plan !== undefined) || (b.action === undefined && b.plan !== undefined), { path: ['plan'], error: 'an edited plan answers a plan_approval gate: `plan` needs approve: true with `action` omitted or edit_plan, and edit_plan needs `plan`' }).refine(
761
+ (b) => b.action !== 'amend_intent' || (b.amend !== undefined && b.amend.trim() !== ''), { path: ['amend'], error: 'amend_intent needs `amend`: what the run\'s acceptance list now says (approve without an action to proceed unamended)' }).refine((b) => b.action !== 'amend_intent' || (b.amendScope === undefined && b.plan === undefined), { path: ['amendScope'], error: 'amend_intent takes no amendScope or plan — an intent amendment reaches every unit at or after the cursor, which is what makes it reach the evaluator' }).refine((b) => !isEscalationAction(b.action) || (b.amend === undefined && b.amendScope === undefined && b.plan === undefined), { path: ['action'], error: 'extend, targeted, accept_partial, accept_suggestion, rejudge, retry_rules, retry_qe and consent:<id> take no amend, amendScope or plan — the engine re-runs the floor, adopts the pinned edit, re-runs the judge, the rule check or the QE check, or runs the chosen install as it stands' }).refine((b) => (b.action === 'edit_plan') === (b.plan !== undefined) || (b.action === undefined && b.plan !== undefined), { path: ['plan'], error: 'an edited plan answers a plan_approval gate: `plan` needs approve: true with `action` omitted or edit_plan, and edit_plan needs `plan`' }).refine(
686
762
  // (crew#1139) `amend` beside a plan is the operator's note to the steps it releases (the engine lands
687
763
  // it on the plan's first creator step); a plan gate's note has no scope to choose.
688
764
  (b) => b.plan === undefined || (b.approve && b.amendScope === undefined), { path: ['plan'], error: '`plan` is an approve WITH an edited plan: approve: true, and no amendScope (a note in `amend` lands on the plan\'s first creator step)' }).refine((b) => b.amendScope === undefined || b.approve, { path: ['amendScope'], error: '`amendScope` applies to an approve only (approve: true)' });
@@ -839,6 +915,21 @@ export const ChatOpenSchema = z.strictObject({
839
915
  /** (api-types 0.169.0, DES-CHAT-ARTIFACTS-001 §6.3) "Ask about this" on a document no open chat holds: seed the
840
916
  * chat's repositories from the document's recorded binding, after an access check. */
841
917
  seedFromArtifact: z.string().max(200).optional(),
918
+ /** (api-types 0.192.0, DES-CATALOG-002 §4.6) A `/` pick or a command with no chat open: the chat opens with this
919
+ * person-made proposal in it; its id and the proposal's derive from (the person, `requestId`). */
920
+ seed: z.strictObject({
921
+ card: z.string().trim().min(1).max(120),
922
+ option: z.string().trim().min(1).max(80).nullable().optional(),
923
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
924
+ words: z.string().max(8000).optional(),
925
+ source: z.enum(['pick', 'command']),
926
+ }).optional(),
927
+ requestId: z.string().trim().min(1).max(128).optional(),
928
+ /** (api-types 0.192.0) What the client renders (`['job']`). */
929
+ accepts: z.array(z.literal('job')).max(4).optional(),
930
+ }).refine((b) => b.seed === undefined || (b.requestId !== undefined && b.chatId === undefined), {
931
+ path: ['seed'],
932
+ error: 'seed needs requestId and no chatId: the chat id derives from you and the request',
842
933
  });
843
934
  /**
844
935
  * The `singleSeat` disclosure (crew#641, hole closed in crew#650) — built in ONE place so the 201
@@ -932,6 +1023,52 @@ security = { audit: AuditLog.noop(), authMode: 'off' },
932
1023
  // Defaulted likewise: a directly-driven route set gets a fresh (all-active) health map and the
933
1024
  // real OS opener — tests inject both through this seam.
934
1025
  runtime = {}) {
1026
+ // (DES-DEMO-RECORD-001 §3.7) The seams a demo launch reads to decide what the app may show a model, and whether
1027
+ // the engine records demos on the host at all. One object for the route and a chat's Demo video job.
1028
+ const demoDeps = {
1029
+ engineRecordsDemos: async () => (typeof adapter.catalog === 'function' ? (await adapter.catalog()).some((e) => e.id === 'demo_record') : true),
1030
+ // (DES-DEMO-RECORD-001 §3.7) The sources a crew app reads, and whether agents may query each: a demo of an app
1031
+ // whose rows may not reach a model records with no model review.
1032
+ ...(runtime.apps !== undefined
1033
+ ? {
1034
+ // Every source any version of the app reads (the head, and every accepted version the page may serve):
1035
+ // the person's page picks its version, so the decision covers them all. `null` when the head spec
1036
+ // cannot be read (the decision then keeps the rows private).
1037
+ appSources: async (slug) => {
1038
+ const store = runtime.apps;
1039
+ const detail = await store.detail(slug);
1040
+ if (detail.spec === null || detail.spec === undefined)
1041
+ return null;
1042
+ const sourcesOf = (spec) => (spec?.queries ?? [])
1043
+ .map((q) => q.source)
1044
+ .filter((x) => typeof x === 'string');
1045
+ const all = new Set(sourcesOf(detail.spec));
1046
+ for (const v of detail.versions) {
1047
+ try {
1048
+ for (const s of sourcesOf((await store.acceptedSpec(slug, v.version)).spec))
1049
+ all.add(s);
1050
+ }
1051
+ catch (err) {
1052
+ // A version that was never accepted never runs against a source; anything else is unreadable.
1053
+ if (err.code !== 'not_accepted')
1054
+ return null;
1055
+ }
1056
+ }
1057
+ return [...all];
1058
+ },
1059
+ }
1060
+ : {}),
1061
+ ...(runtime.dataGate !== undefined
1062
+ ? {
1063
+ // The data gate's own predicate (DES-APPS-001 S5): the source on, query on, and the run's project in its
1064
+ // scope. A source the gate does not know keeps the rows private.
1065
+ agentQueryAllowed: async (source, projectId) => {
1066
+ const s = (await runtime.dataGate.sources()).find((x) => x.name === source);
1067
+ return s !== undefined && agentMay(s.access, s, projectId, 'query');
1068
+ },
1069
+ }
1070
+ : {}),
1071
+ };
935
1072
  const { audit } = security;
936
1073
  const seatHealth = runtime.seatHealth ?? new SeatHealthTracker();
937
1074
  const deliveryFreeze = runtime.deliveryFreeze ?? new DeliveryFreeze();
@@ -964,19 +1101,30 @@ runtime = {}) {
964
1101
  const chatTranscripts = runtime.chatTranscripts;
965
1102
  const chatAttachments = runtime.chatAttachments ?? new ChatAttachmentStore();
966
1103
  const chatHistory = runtime.chatHistory ?? (chatTranscripts !== undefined ? new ChatHistoryStore(chatTranscripts, chatAttachments) : null);
967
- // DES-CHAT-ARTIFACTS-001 §14 (A2): what a chat can do with artifacts. Production: `proposals` on and every operation
968
- // off — each later slice turns its own on and registers its launcher. The TEST configuration (§13 A2) turns every
1104
+ // DES-CHAT-ARTIFACTS-001 §14 (A2): what a chat can do with artifacts. Production: `proposals` on, and each operation
1105
+ // on once its slice registers its launcher (A3 create, A7 theme). The TEST configuration (§13 A2) turns every
969
1106
  // operation's resolution on and registers a recording stub that starts nothing.
970
1107
  const chatArtifactsStub = runtime.chatArtifactsStub === true;
971
1108
  // A3: a real `create` exists whenever the draft seam can launch a proposal-bound draft (the launcher is registered
972
1109
  // below, once the bridge pool exists). Production advertises it; the test configuration keeps the recording stub only
973
1110
  // for the operations whose slices have not landed.
974
1111
  const realCreate = runtime.docBindings !== undefined && runtime.launchBoundDraft !== undefined;
975
- const stubOps = realCreate ? ['refine', 'theme', 'demo'] : ['create', 'refine', 'theme', 'demo'];
1112
+ // A7: a theme starts no run (§15.2), so its launcher is always real: studio applies the patch, Go records it.
1113
+ // A5: a real `refine` exists whenever the chat seam can launch a proposal-bound refine (its launcher is registered
1114
+ // below, beside `create`).
1115
+ const realRefine = runtime.docBindings !== undefined && runtime.launchBoundRefine !== undefined;
1116
+ const stubOps = [
1117
+ ...(realCreate ? [] : ['create']),
1118
+ ...(realRefine ? [] : ['refine']),
1119
+ 'demo',
1120
+ ];
976
1121
  const chatArtifactFlags = chatArtifactsStub
977
1122
  ? { context: true, proposals: true, create: true, refine: true, theme: true, demo: true, stub: true, stubOps }
978
- : { context: true, proposals: true, create: realCreate, refine: false, theme: false, demo: false };
1123
+ : { context: true, proposals: true, create: realCreate, refine: realRefine, theme: true, demo: false };
979
1124
  const proposalLaunchers = new LaunchOnceRegistry();
1125
+ proposalLaunchers.register('theme', new ThemeLauncher());
1126
+ /** (DES-CATALOG-002 §4.6) Job proposals in a chat: on wherever chat proposals are. */
1127
+ const chatJobProposalsOn = chatArtifactFlags.proposals;
980
1128
  if (chatArtifactsStub) {
981
1129
  // Under the registered `chats` entry (a new top-level state-home entry would make core refuse every launch), and
982
1130
  // not a `.jsonl` there (the boot sweep clears orphaned transcripts by that suffix).
@@ -1084,11 +1232,35 @@ runtime = {}) {
1084
1232
  ...(runtime.studioRoot !== undefined ? { studioRoot: runtime.studioRoot } : {}),
1085
1233
  log: (m) => app.log.warn(m),
1086
1234
  });
1235
+ // (DES-EDITOR-CONFORMANCE-HOST) An editor-plugin run's conformance step runs on this host under crew's runtime:
1236
+ // start making it when such a run starts, so it is ready when the build is done.
1237
+ if (runtime.editorConformance === undefined && typeof adapter.onLaunch === 'function') {
1238
+ const root = conformanceRuntimeRoot();
1239
+ const off = adapter.onLaunch(editorPluginLaunchListener({
1240
+ provision: editorConformanceRuntime,
1241
+ log: (m) => app.log.warn(m),
1242
+ managed: venvPython(conformanceVenvDir(root)),
1243
+ ready: () => conformanceRuntimeReady(root),
1244
+ workflowOf: async (runId) => {
1245
+ const events = await adapter.runEvents(runId);
1246
+ const started = events?.find((e) => e.type === 'sessionStarted');
1247
+ return typeof started?.workflowId === 'string' ? started.workflowId : undefined;
1248
+ },
1249
+ }));
1250
+ app.addHook('onClose', async () => {
1251
+ off();
1252
+ });
1253
+ }
1087
1254
  registerEditorRoutes(app, {
1088
1255
  registry: editorRegistry,
1089
1256
  adapter,
1090
1257
  packCheck: runtime.packCheck ?? gardenPackCheck(discoverLivePlugin()?.path ?? null),
1091
1258
  conformance: runtime.editorConformance ?? gardenConformance(discoverLivePlugin()?.path ?? null, () => process.env['WICKED_CREW_URL'] ?? null, { provision: editorConformanceRuntime }),
1259
+ // F37: the grant write's §6.4 tripwire asks the engine whether a bearer is a governed unit's token.
1260
+ ...(() => {
1261
+ const probe = runtime.editorUnitTokenProbe !== undefined ? runtime.editorUnitTokenProbe : unitTokenProbe(CoreAdapter.estateScopeResolver());
1262
+ return probe !== undefined ? { isUnitToken: probe } : {};
1263
+ })(),
1092
1264
  log: (m) => app.log.warn(m),
1093
1265
  });
1094
1266
  // DES-APPS-001 §7.6 (K2a): the app store's routes, when this daemon has a store.
@@ -1132,6 +1304,15 @@ runtime = {}) {
1132
1304
  registerAppRoutes(app, {
1133
1305
  store: runtime.apps,
1134
1306
  audit,
1307
+ publish: {
1308
+ engine: adapter,
1309
+ roster: async () => {
1310
+ await rosterWithStanding.ready?.();
1311
+ return JSON.stringify(launchRosterNaming(rosterWithStanding(), undefined));
1312
+ },
1313
+ registry: runtime.mcp ?? null,
1314
+ grantOf: (slug, action) => appsWritePath?.getGrant(slug, action) ?? null,
1315
+ },
1135
1316
  ...(appsExecutor !== undefined ? { executor: appsExecutor } : {}),
1136
1317
  ...(appsWritePath !== undefined ? { writePath: appsWritePath } : {}),
1137
1318
  ...(runtime.appsVerifyUnitToken !== undefined ? { verifyUnitToken: runtime.appsVerifyUnitToken } : {}),
@@ -1152,6 +1333,27 @@ runtime = {}) {
1152
1333
  : null;
1153
1334
  /** Repo root for a repo ref, from the registry — shared by the reprovision path below. */
1154
1335
  const repoRootOf = async (repoRef) => (await adapter.listRepos()).find((r) => r.id === repoRef)?.root_path;
1336
+ /** The lookups a review-change exclusion reads (the launch and the job proposal read the same ones, CJ13). */
1337
+ const reviewChangeDeps = (repoRef, repoRoot) => ({
1338
+ repoRef,
1339
+ repoRoot,
1340
+ views: () => adapter.sessionsDetail(),
1341
+ deliveredUrl: (id) => deliveryIndex.urlFor(id),
1342
+ pushed: (id) => deliveryIndex.pushedFor(id),
1343
+ deliveredCommit: (id) => deliveryIndex.commitFor(id),
1344
+ revisesPr: (id) => retryIndex.revisesPrFor(id),
1345
+ gh: runtime.reviewChange?.gh ?? defaultGhExec,
1346
+ git: runtime.reviewChange?.git ?? (async (args, cwd) => {
1347
+ try {
1348
+ return { ...(await execCapped('git', args, { cwd, timeout: 5_000 })), code: 0 };
1349
+ }
1350
+ catch (err) {
1351
+ // Only exit 1 proves non-membership; preserve it separately from lookup failures.
1352
+ const code = err.code;
1353
+ return { code: typeof code === 'number' ? code : null, stdout: '', stderr: message(err) };
1354
+ }
1355
+ }),
1356
+ });
1155
1357
  /** DES-L9: PR number → head branch, through `gh pr view` unless the runtime injected an answerer. */
1156
1358
  const resolvePullRequest = runtime.resolvePullRequest ?? resolvePullRequestViaGh;
1157
1359
  /** crew#627: the intent's linked issues, read under the daemon's identity at launch. */
@@ -1363,6 +1565,13 @@ runtime = {}) {
1363
1565
  const landingFailed = runTimingIndex.landingFailedOf(view.session.id);
1364
1566
  if (landingFailed !== undefined)
1365
1567
  view.session.landing_failed = landingFailed;
1568
+ // DES-CATALOG-002 §4.4: the shape it was launched as and the chat proposal whose Go launched it — ABSENT otherwise.
1569
+ const launchedShape = runTimingIndex.shapeOf(view.session.id);
1570
+ if (launchedShape !== undefined)
1571
+ view.session.shape = launchedShape;
1572
+ const fromProposal = runTimingIndex.fromProposalOf(view.session.id);
1573
+ if (fromProposal !== undefined)
1574
+ view.session.from_proposal = fromProposal;
1366
1575
  // crew#552: the onboarding run a chained capture was launched from — ABSENT otherwise.
1367
1576
  const chainedFrom = runTimingIndex.chainedFromOf(view.session.id);
1368
1577
  if (chainedFrom !== undefined)
@@ -1541,6 +1750,15 @@ runtime = {}) {
1541
1750
  voice: app.hasRoute({ method: 'POST', url: `${V}/voice/transcribe` }),
1542
1751
  // (api-types 0.168.0, wf-catalog) The categorised workflow catalog with the operator's usage.
1543
1752
  workflowCatalog: app.hasRoute({ method: 'GET', url: `${V}/workflows/catalog` }),
1753
+ // DES-CATALOG-002 §4.1: `?v=2` on the same route, and `shape` on every launch route.
1754
+ workflowCatalogV2: app.hasRoute({ method: 'GET', url: `${V}/workflows/catalog` }),
1755
+ launchShape: true,
1756
+ // DES-CATALOG-002 §2.3: `POST /workflows/catalog/detect` (the words layer, then the hidden detect-shape turn).
1757
+ detectShape: app.hasRoute({ method: 'POST', url: `${V}/workflows/catalog/detect` }),
1758
+ // DES-CATALOG-002 §4.6: person-made and revised job proposals, the revising hold, plan answers bound to planRev.
1759
+ chatJobProposals: chatJobProposalsOn,
1760
+ chatJobPower: chatJobProposalsOn,
1761
+ reshapeRun: chatJobProposalsOn,
1544
1762
  // (api-types 0.169.0, DES-CHAT-ARTIFACTS-001 §14) Per operation: A1 serves `context` (the chat sees the open
1545
1763
  // artifact and the runs the person names; `seedFromArtifact`); A2 (0.170.0) `proposals`. The operations are later
1546
1764
  // slices (all on, with `stub`, in the test configuration).
@@ -1553,7 +1771,7 @@ runtime = {}) {
1553
1771
  query: appsExecutor !== undefined,
1554
1772
  actions: appsWritePath !== undefined,
1555
1773
  turns: runtime.apps.turns !== null,
1556
- publish: false,
1774
+ publish: appsServerArtifact() !== null && appsRuntimeDir() !== null && containerEngineKnown(),
1557
1775
  uploads: app.hasRoute({ method: 'POST', url: `${V}/apps/uploads` }),
1558
1776
  sourceCheck: runtime.apps.sourceStage !== null,
1559
1777
  },
@@ -1755,6 +1973,43 @@ runtime = {}) {
1755
1973
  return { diagnostics: [], workEligible: new Set() };
1756
1974
  }
1757
1975
  };
1976
+ /**
1977
+ * The seat record per query (`<days> <project>`), F35: one read at a time per query, which every
1978
+ * caller asking meanwhile shares, kept while the views snapshot it was read from is current (held
1979
+ * weakly: a kept answer never keeps an old snapshot alive). At most {@link SEAT_RECORDS_KEPT}
1980
+ * answered queries are kept (trimmed as each read settles); a read in flight is never dropped, so it
1981
+ * stays shared.
1982
+ */
1983
+ const seatRecords = new Map();
1984
+ const SEAT_RECORDS_KEPT = 16;
1985
+ /** Drop the oldest answered queries past {@link SEAT_RECORDS_KEPT}; a read in flight is never dropped. */
1986
+ const trimSeatRecords = () => {
1987
+ let answered = 0;
1988
+ for (const kept of seatRecords.values())
1989
+ if (kept.settled)
1990
+ answered++;
1991
+ for (const [k, kept] of seatRecords) {
1992
+ if (answered <= SEAT_RECORDS_KEPT)
1993
+ break;
1994
+ if (kept.settled) {
1995
+ seatRecords.delete(k);
1996
+ answered--;
1997
+ }
1998
+ }
1999
+ };
2000
+ const readSeatRecord = async (snapshot, days, project) => {
2001
+ const detail = structuredClone(snapshot.views);
2002
+ await backfillEndedAt(detail);
2003
+ const all = detail.map(decorateRun);
2004
+ const views = project === undefined ? all : all.filter((v) => v.session.project_id === project);
2005
+ return seatRecord(views, async (id) => {
2006
+ const engine = await adapter.runEvents(id);
2007
+ if (engine === null)
2008
+ return null;
2009
+ const daemon = runtime.stallFrames?.(id) ?? [];
2010
+ return daemon.length === 0 ? engine : [...engine, ...daemon];
2011
+ }, { days, now: Date.now() });
2012
+ };
1758
2013
  // Each seat's week (studio's weekly 1:1 per agent; api-types 0.52.0): units, first pass, rework,
1759
2014
  // stalls, bench and cost, folded from the runs' durable event logs by `seatRecord` — nothing new
1760
2015
  // is stored. The daemon's remembered stall frames join the engine's, as on `/runs/:id/events`.
@@ -1776,17 +2031,25 @@ runtime = {}) {
1776
2031
  return reply.code(400).send({ error: 'Invalid ?project — expected one project id' });
1777
2032
  }
1778
2033
  const project = rawProject?.trim();
1779
- const detail = await adapter.sessionsDetail();
1780
- await backfillEndedAt(detail);
1781
- const all = detail.map(decorateRun);
1782
- const views = project === undefined ? all : all.filter((v) => v.session.project_id === project);
1783
- const out = await seatRecord(views, async (id) => {
1784
- const engine = await adapter.runEvents(id);
1785
- if (engine === null)
1786
- return null;
1787
- const daemon = runtime.stallFrames?.(id) ?? [];
1788
- return daemon.length === 0 ? engine : [...engine, ...daemon];
1789
- }, { days, now: Date.now() });
2034
+ // F35: it reads up to SEAT_RECORD_RUN_CAP run logs and studio asks from every tab, so one read
2035
+ // per query runs at a time, shared, and is kept while its views snapshot is current.
2036
+ const snapshot = await adapter.runViewsSnapshot();
2037
+ const key = `${days} ${project ?? ''}`;
2038
+ let entry = seatRecords.get(key);
2039
+ if (entry === undefined || (entry.settled && entry.of.deref() !== snapshot)) {
2040
+ const started = { of: new WeakRef(snapshot), read: readSeatRecord(snapshot, days, project), settled: false };
2041
+ seatRecords.delete(key);
2042
+ seatRecords.set(key, started);
2043
+ started.read.then(() => {
2044
+ started.settled = true;
2045
+ trimSeatRecords();
2046
+ }, () => {
2047
+ if (seatRecords.get(key) === started)
2048
+ seatRecords.delete(key);
2049
+ });
2050
+ entry = started;
2051
+ }
2052
+ const out = await entry.read;
1790
2053
  if (out === null) {
1791
2054
  return reply.code(503).send({ error: 'Seat records are unavailable: this wicked-core build has no event-log read binding' });
1792
2055
  }
@@ -1812,8 +2075,7 @@ runtime = {}) {
1812
2075
  try {
1813
2076
  let session;
1814
2077
  if (runId !== undefined) {
1815
- const views = await adapter.sessionsDetail();
1816
- const view = views.find((v) => v.session.id === runId);
2078
+ const view = await adapter.runView(runId);
1817
2079
  if (view === undefined) {
1818
2080
  return reply.code(404).send({ error: `unknown run: ${runId}` });
1819
2081
  }
@@ -1850,8 +2112,7 @@ runtime = {}) {
1850
2112
  let session;
1851
2113
  let roots;
1852
2114
  try {
1853
- const views = await adapter.sessionsDetail();
1854
- const view = views.find((v) => v.session.id === id);
2115
+ const view = await adapter.runView(id);
1855
2116
  if (view === undefined) {
1856
2117
  await reply.code(404).send({ error: `unknown run: ${id}` });
1857
2118
  return null;
@@ -2200,7 +2461,15 @@ runtime = {}) {
2200
2461
  const refused = await onboardRefusal();
2201
2462
  if (refused !== null)
2202
2463
  return reply.code(refused.status).send(refused.body);
2203
- const { name, rootPath, gitUrl, projectId, channel, actor, autoCapture } = parsed.data;
2464
+ const { name, gitUrl, projectId, channel, actor, autoCapture } = parsed.data;
2465
+ // First-run C1: `~/code/my-app` (the field's own example) is expanded; a relative or missing folder is refused in plain words.
2466
+ let rootPath = parsed.data.rootPath;
2467
+ if (rootPath !== undefined && rootPath !== '') {
2468
+ const read = readRepoPath(rootPath);
2469
+ if (!read.ok)
2470
+ return reply.code(400).send({ code: read.code, error: read.error });
2471
+ rootPath = read.path;
2472
+ }
2204
2473
  // (DES-PM-001 Q-PM2) Re-pointing an existing repo id at another checkout keeps its projects and tracker links.
2205
2474
  const repointed = await reRegisterRefusal(actorOf(req), name, rootPath, Boolean(gitUrl), () => adapter.listRepos());
2206
2475
  if (repointed !== null)
@@ -2222,10 +2491,11 @@ runtime = {}) {
2222
2491
  }
2223
2492
  catch (err) {
2224
2493
  if (repo === undefined)
2225
- return reply.code(400).send({ error: message(err) });
2494
+ return reply.code(400).send(registerFailure(message(err), gitUrl ? undefined : rootPath));
2226
2495
  req.log.warn({ repoId: repo.id }, `repo registered but onboarding launch failed: ${message(err)}`);
2227
2496
  // No run exists to record or file, even when projectId was supplied (crew#1019).
2228
- return reply.code(201).send({ repo, onboardRunId: null, onboardError: message(err) });
2497
+ const failure = onboardFailure(message(err));
2498
+ return reply.code(201).send({ repo, onboardRunId: null, onboardError: failure.error, ...(failure.code !== undefined ? { onboardErrorCode: failure.code, missingTool: failure.tool } : {}) });
2229
2499
  }
2230
2500
  const projectAttachError = await recordOnboardingLaunch(req, runId, repo.id, { projectId, channel, actor, autoCapture });
2231
2501
  return reply.code(201).send({ repo, onboardRunId: runId, ...(projectAttachError !== undefined ? { projectAttachError } : {}) });
@@ -2256,7 +2526,8 @@ runtime = {}) {
2256
2526
  runId = await adapter.launchOnboardingRun(repo.id, repo.name);
2257
2527
  }
2258
2528
  catch (err) {
2259
- return reply.code(400).send({ error: message(err) });
2529
+ const failure = onboardFailure(message(err));
2530
+ return reply.code(400).send({ error: failure.error, ...(failure.code !== undefined ? { code: failure.code, missingTool: failure.tool } : {}) });
2260
2531
  }
2261
2532
  const projectAttachError = await recordOnboardingLaunch(req, runId, repo.id, body.data);
2262
2533
  return reply.code(201).send({ runId, ...(projectAttachError !== undefined ? { projectAttachError } : {}) });
@@ -2288,32 +2559,87 @@ runtime = {}) {
2288
2559
  return { issues: [], appendedChars: 0, error: `linked issues could not be read: ${message(err)} — a launch now runs on the intent alone` };
2289
2560
  }
2290
2561
  });
2291
- // Launch a run (replaces POST /sessions). `clisJson` defaults to the roster;
2292
- // `sessionId` is minted if the client omits it.
2293
- app.post(`${V}/runs`, {
2294
- config: {
2295
- manifest: {
2296
- requestType: 'LaunchRunBody',
2297
- responseType: 'LaunchRunResponse',
2298
- // 404/409: unknown project / unknown campaignId (wicked-studio#27) /
2299
- // archived-or-synthesized project + busy engine + the state-home blocker
2300
- // (`state_home_unregistered`) + a roster with no eligible seat (`no_eligible_seat`,
2301
- // wicked-core#461 — see the catch below); 400: zod reject or a retryOf naming no
2302
- // existing run; 422: the base-skill intake refusal (`base_skill_refused`, crew#554);
2303
- // 501: campaignId attach on an engine addon without the campaign bindings ("upgrade
2304
- // the engine").
2305
- statusCodes: [201, 400, 404, 409, 422, 501],
2306
- },
2307
- },
2308
- }, async (req, reply) => {
2562
+ /**
2563
+ * (DES-CHAT-FIRST-001 C3, DES-CATALOG-002 §4.6) THE launch: the whole launch policy and provenance path of
2564
+ * `POST /runs`, shared by that route and every other launcher of a run (a chat job proposal's Go, a reshape). The
2565
+ * route parses nothing itself: the body is checked here, by the same schema, so no launcher has a side path.
2566
+ * `internal` carries what only crew may set (never a client field): the proposal a run was launched from.
2567
+ */
2568
+ /** What a shape is judged against: the engine's served defs, presets and phase catalog (DES-CATALOG-002 §4.4). */
2569
+ const shapeReads = {
2570
+ defs: () => adapter.listWorkflows(),
2571
+ presets: (projectId) => adapter.listPresets(projectId),
2572
+ entries: () => adapter.catalog(),
2573
+ };
2574
+ /** (CS4) A chat's project, as its proposals read it (`null`: Unfiled, or the chat is unknown). */
2575
+ const chatProposalsProjectOf = (chatId) => {
2576
+ const p = chatScopes.get(chatId)?.projectId ?? chatHistory?.stateOf(chatId)?.projectId ?? null;
2577
+ return p === null || p === DEFAULT_PROJECT_ID ? null : p;
2578
+ };
2579
+ /**
2580
+ * (CS4) The documents an earlier run was given, to be authorised and staged again for its retry: its tokens and chat
2581
+ * from its staged manifest, hash-checked. `null` = it had none; `'unreadable'` = it had some that can't be read back.
2582
+ */
2583
+ const stagedTokensOf = (runId, root) => {
2584
+ const staged = stagedDocumentsOf(runId, root);
2585
+ if (staged === null) {
2586
+ try {
2587
+ readFileSync(join(root, runId, 'records', 'MANIFEST.json'));
2588
+ }
2589
+ catch {
2590
+ return null;
2591
+ }
2592
+ return 'unreadable';
2593
+ }
2594
+ try {
2595
+ const m = JSON.parse(readFileSync(join(staged.records, 'MANIFEST.json'), 'utf8'));
2596
+ const tokens = [...new Set(staged.files.filter((f) => f.derived === undefined).map((f) => f.token))];
2597
+ return typeof m.chat === 'string' && tokens.length > 0 ? { chatId: m.chat, tokens } : 'unreadable';
2598
+ }
2599
+ catch {
2600
+ return 'unreadable';
2601
+ }
2602
+ };
2603
+ const launchRun = async (raw, ctx) => {
2604
+ const reply = new LaunchReply();
2605
+ const req = { body: raw, log: ctx.log, actor: ctx.actor };
2309
2606
  const parsed = LaunchSchema.safeParse(req.body);
2310
2607
  if (!parsed.success) {
2311
2608
  return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
2312
2609
  }
2313
- const b = parsed.data;
2610
+ const b = { ...parsed.data };
2611
+ // DES-CATALOG-002 §4.4: the words as the person gave them, before crew's framing line (the envelope's `words`, which
2612
+ // a reshape relaunches from), with any block an earlier launch appended taken out.
2613
+ const envelopeWords = stripLinkedIssues(stripRulesBrief(b.problem));
2614
+ // The shape as judged, re-judged just before the engine is called (the awaits between can see a preset saved).
2615
+ let shapeChecked = null;
2616
+ // DES-CATALOG-002 §4.4: a shape is judged against the CURRENT catalog and this launch's own target before anything is
2617
+ // read or committed; its framing line (and depth) goes first in the brief, crew's, never the client's.
2618
+ if (b.shape !== undefined) {
2619
+ const target = ctx.target === 'compose'
2620
+ ? { kind: 'compose' }
2621
+ : b.workflow !== undefined && DEMO_PRESETS.includes(b.workflow)
2622
+ ? { kind: 'demo' }
2623
+ : { kind: 'run', workflow: b.workflow };
2624
+ if (ctx.target !== 'compose' && b.plan !== undefined) {
2625
+ return reply.code(400).send({ code: 'shape_mismatch', error: 'a shape names a card, and a launch with its own plan runs no card' });
2626
+ }
2627
+ let served;
2628
+ try {
2629
+ served = await servedFor(shapeReads, b.projectId);
2630
+ }
2631
+ catch (err) {
2632
+ return reply.code(409).send({ code: 'catalog_unavailable', error: message(err) });
2633
+ }
2634
+ const verdict = checkLaunchShape(launchShapeOf(b.shape), target, served);
2635
+ if (!verdict.ok)
2636
+ return reply.code(verdict.code).send(verdict.body);
2637
+ shapeChecked = { shape: launchShapeOf(b.shape), target, resolution: verdict.resolved.resolved.resolution };
2638
+ b.problem = withBriefLines(b.problem, verdict.lines);
2639
+ }
2314
2640
  // The demo preset launches only from POST /projects/:id/demo (api/recording.ts), which mints the run's
2315
2641
  // demo root and brief first: launched here directly it would have neither.
2316
- if (b.workflow === DEMO_PRESET && (b.sessionId === undefined || !demoLaunchRoots.has(b.sessionId))) {
2642
+ if (b.workflow !== undefined && DEMO_PRESETS.includes(b.workflow) && (b.sessionId === undefined || !demoLaunchRoots.has(b.sessionId))) {
2317
2643
  return reply.code(400).send({
2318
2644
  error: 'the demo preset launches from POST /projects/:id/demo, which makes its demo root and brief; POST /runs does not take it directly',
2319
2645
  });
@@ -2380,10 +2706,15 @@ runtime = {}) {
2380
2706
  const captureRoot = captureLaunchRoots.get(input.sessionId);
2381
2707
  if (captureRoot !== undefined)
2382
2708
  input.extraWriteRoots = [captureRoot];
2383
- // A demo launch (api/recording.ts) writes every file into the demo root the demo route minted for it.
2384
- const demoRoot = demoLaunchRoots.get(input.sessionId);
2385
- if (demoRoot !== undefined)
2386
- input.extraWriteRoots = [demoRoot];
2709
+ // A demo launch (api/recording.ts, DES-DEMO-RECORD-001 §3.2): the demo root is the run's evidence root (the
2710
+ // engine's Tools record under it); the plan directory is its ONLY write root; the probe (and the review
2711
+ // sheets, when the rows may reach a model) are read-only mounts.
2712
+ const demo = demoLaunchRoots.get(input.sessionId);
2713
+ if (demo !== undefined) {
2714
+ input.extraWriteRoots = [demo.write];
2715
+ input.extraReadRoots = demo.read;
2716
+ input.demoRoot = demo.root;
2717
+ }
2387
2718
  if (b.entityMode !== undefined)
2388
2719
  input.entityMode = b.entityMode;
2389
2720
  if (b.humanConfirm !== undefined)
@@ -2508,7 +2839,15 @@ runtime = {}) {
2508
2839
  else if (!powerSupported()) {
2509
2840
  powerNotice = 'this engine has no power mode; the launch runs phased';
2510
2841
  }
2511
- else {
2842
+ else if (ctx.powerRequired === true && ((await adapter.getSettings()).powerModeDefault ?? true) === false) {
2843
+ // A chat job's power Start follows the setting up to the engine call (it may have been turned off meanwhile).
2844
+ powerNotice = 'Power mode for new jobs is off on this daemon; the launch runs phased';
2845
+ }
2846
+ // A chat job's power Start is never run phased in its place (the person chose no plan review for a power run).
2847
+ if (powerNotice !== null && ctx.powerRequired === true) {
2848
+ return reply.code(409).send({ code: 'power_unavailable', error: `${powerNotice.replace(/; this launch runs phased|; the launch runs phased/u, '')}; press Start with Review plan on` });
2849
+ }
2850
+ if (powerNotice === null) {
2512
2851
  input.power = true;
2513
2852
  input.humanConfirm = 'none';
2514
2853
  // DES-LEARN §3.3 / wicked-core#1216: the orchestrator talks to the person in their personality
@@ -2527,6 +2866,66 @@ runtime = {}) {
2527
2866
  input.skipQeAcceptanceReason = settingSkip;
2528
2867
  if (b.forceQeAcceptance === true)
2529
2868
  input.forceQeAcceptance = true;
2869
+ let reviewChange;
2870
+ if (b.workflow === REVIEW_CHANGE_WORKFLOW) {
2871
+ if (b.deliver === 'pr' || b.revisesPr !== undefined) {
2872
+ return reply.code(400).send({ error: 'a review posts nothing and never delivers' });
2873
+ }
2874
+ if (b.repoRef === undefined)
2875
+ return reply.code(400).send({ error: 'review-change needs repoRef' });
2876
+ deliver = 'none';
2877
+ delete input.deliver;
2878
+ const root = await repoRootOf(b.repoRef);
2879
+ if (root === undefined)
2880
+ return reply.code(404).send({ error: `repoRef names an unknown repo: ${b.repoRef}` });
2881
+ const ex = await reviewChangeExclusion(envelopeWords, reviewChangeDeps(b.repoRef, root));
2882
+ if (!ex.ok)
2883
+ return reply.code(409).send({ code: ex.code, error: ex.error });
2884
+ const excluded = b.reducedAssurance === true ? [] : ex.excludeSeats;
2885
+ if (b.reducedAssurance !== true) {
2886
+ let parsed;
2887
+ try {
2888
+ parsed = JSON.parse(input.clisJson);
2889
+ }
2890
+ catch {
2891
+ parsed = null;
2892
+ }
2893
+ if (!Array.isArray(parsed))
2894
+ return reply.code(400).send({ error: 'review-change needs clisJson to be a roster array' });
2895
+ const roster = rosterWithout(parsed, excluded);
2896
+ const canWork = roster.some((seat) => {
2897
+ if (typeof seat !== 'object' || seat === null)
2898
+ return false;
2899
+ const s = seat;
2900
+ const health = toEngineSeat(s).health;
2901
+ return typeof s['key'] === 'string' && s['key'].trim() !== '' && s['work_eligible'] !== false &&
2902
+ s['seat_eligible_for_work'] !== false && s['signed_in'] !== false && s['auth'] !== 'signed_out' && health?.usable !== false;
2903
+ });
2904
+ if (!canWork) {
2905
+ return reply.code(409).send({
2906
+ code: 'no_independent_reviewer',
2907
+ error: `Every available seat (${ex.excludeSeats.join(', ')}) wrote part of this change, so none can review it independently. Sign in another seat, or start it again in reduced assurance (the authors review their own change, labelled on the run and every gate).`,
2908
+ excluded: ex.excludeSeats,
2909
+ retryWith: { reducedAssurance: true },
2910
+ });
2911
+ }
2912
+ input.clisJson = JSON.stringify(roster);
2913
+ input.excludeSeats = [...new Set([...(input.excludeSeats ?? []), ...excluded])];
2914
+ if (input.primary !== undefined) {
2915
+ const refusal = primaryRefusal(input.primary, input.clisJson);
2916
+ if (refusal !== null)
2917
+ return reply.code(400).send({ error: refusal });
2918
+ }
2919
+ }
2920
+ const lines = ex.briefLines.map((line) => b.reducedAssurance === true && line === ex.label
2921
+ ? "reduced assurance: the change's authors may review it" : line);
2922
+ // The workflow decoration below rebuilds input.problem from b.problem: retain these lines in both.
2923
+ b.problem = withBriefLines(stripLinkedIssues(b.problem), lines);
2924
+ input.problem = withBriefLines(input.problem, lines);
2925
+ if (ex.baseRef !== undefined)
2926
+ input.baseRef = ex.baseRef;
2927
+ reviewChange = { target: ex.target, provenance: ex.provenance, runs: ex.runs, excluded, headSha: ex.headSha };
2928
+ }
2530
2929
  // DES-L9 / crew#550 — REVISION: `revisesPr` names an OPEN same-repository pull request whose
2531
2930
  // head branch becomes the run's base (`baseRef`, crew-internal → the engine's
2532
2931
  // `LaunchSpec.base_ref`) and the push target of the composed deliver phase — the PR gains
@@ -2568,6 +2967,30 @@ runtime = {}) {
2568
2967
  });
2569
2968
  }
2570
2969
  }
2970
+ // (DES-CATALOG-002 §2.d piece 4, CS4) The source pick, checked at launch against the project's sources and their
2971
+ // "Agents can query" switches (the pick narrows the switches, never widens them), before anything is committed. A
2972
+ // retry or reshape that sends none keeps the earlier run's pick; a run without a pick reads what the switches allow.
2973
+ let sourcePick = null;
2974
+ // An inherited pick is checked like a sent one (the switches may have changed since the earlier run).
2975
+ const wantedPick = b.sources ?? (b.retryOf !== undefined ? (runtime.runSourcePicks?.get(b.retryOf) ?? undefined) : undefined);
2976
+ if (wantedPick !== undefined) {
2977
+ if (runtime.runSourcePicks === undefined || runtime.dataGate === undefined) {
2978
+ return reply.code(400).send({ code: 'sources_refused', error: 'this daemon cannot limit a run to picked sources' });
2979
+ }
2980
+ const checked = await checkSourcePick(b.projectId ?? null, wantedPick, runSourcesDeps(runtime.dataGate));
2981
+ if (!checked.ok) {
2982
+ return reply.code(400).send({
2983
+ code: 'sources_refused',
2984
+ error: `can't read ${checked.refused.map((r) => `${r.id} (${r.reason})`).join(', ')}`,
2985
+ refused: checked.refused,
2986
+ });
2987
+ }
2988
+ sourcePick = checked.ids;
2989
+ }
2990
+ // (DES-CATALOG-002 §2.d piece 2, CS4) The documents can be staged only where this daemon keeps them.
2991
+ if (b.documents !== undefined && b.documents.length > 0 && runtime.runDocumentsRoot === undefined) {
2992
+ return reply.code(400).send({ code: 'documents_refused', error: 'this daemon cannot stage documents for a run' });
2993
+ }
2571
2994
  // Ad-hoc campaign attach (wicked-studio#27): `campaignId` must name an EXISTING campaign,
2572
2995
  // checked BEFORE anything launches — an unknown id is a 404 with nothing committed, never a
2573
2996
  // run silently filed onto a surface that does not exist. An engine addon without the
@@ -2695,6 +3118,95 @@ runtime = {}) {
2695
3118
  if (live !== null)
2696
3119
  return reply.code(409).send({ code: 'chat_busy', error: `This chat already has a job running (${live}). Wait, or stop that run.` });
2697
3120
  }
3121
+ // DES-CATALOG-002 §4.4 (codex r1): the effective resolution a shape was judged by is read again right before the
3122
+ // engine resolves the preset, so a preset saved during this launch's awaits refuses it rather than running a shape
3123
+ // the person did not see. (The engine has no snapshot binding; every chat-launched job is also held at its plan.)
3124
+ if (shapeChecked !== null) {
3125
+ try {
3126
+ const again = checkLaunchShape(shapeChecked.shape, shapeChecked.target, await servedFor(shapeReads, b.projectId));
3127
+ if (!again.ok || again.resolved.resolved.resolution !== shapeChecked.resolution) {
3128
+ return reply.code(409).send({ code: 'catalog_changed', error: 'the catalog changed while this was starting; check the job again' });
3129
+ }
3130
+ }
3131
+ catch (err) {
3132
+ return reply.code(409).send({ code: 'catalog_unavailable', error: message(err) });
3133
+ }
3134
+ }
3135
+ // (CS4) The pick is recorded before anything is staged and before the engine is called, so no unit of the run ever
3136
+ // runs without it (CS10's fence reads it) and a failed record leaves nothing behind. Fail closed: nothing launches.
3137
+ if (sourcePick !== null) {
3138
+ try {
3139
+ runtime.runSourcePicks.set(input.sessionId, sourcePick);
3140
+ }
3141
+ catch (err) {
3142
+ return reply.code(409).send({ code: 'sources_unavailable', error: `the source pick could not be recorded: ${message(err)}` });
3143
+ }
3144
+ }
3145
+ // (DES-CATALOG-002 §2.d piece 2, CS4) The documents: every token authorised again with the chat's own rules (this
3146
+ // chat, its project, the document's version now) and staged whole, read-only, in the run's own folder outside the
3147
+ // state home; a retry or reshape that sends none reuses the earlier run's staged folder (hash-checked). The folder
3148
+ // is a READ root only: the run can read its documents and never write there. The brief says where they are.
3149
+ let staged = null;
3150
+ // What to stage: the documents sent, or (a retry that sends none) the earlier run's tokens under the earlier run's
3151
+ // chat, authorised again now; never the earlier folder mounted as it is. `[]` = none, inherit nothing.
3152
+ let docTokens = null;
3153
+ if (b.documents !== undefined) {
3154
+ if (b.documents.length > 0 && b.chatId !== undefined)
3155
+ docTokens = { chatId: b.chatId, tokens: b.documents };
3156
+ }
3157
+ else if (b.retryOf !== undefined && runtime.runDocumentsRoot !== undefined) {
3158
+ const earlier = stagedTokensOf(b.retryOf, runtime.runDocumentsRoot);
3159
+ if (earlier === 'unreadable') {
3160
+ return reply.code(409).send({ code: 'documents_unavailable', error: `the documents of run ${b.retryOf} can't be read again; start the job again from its chat` });
3161
+ }
3162
+ if (earlier !== null)
3163
+ docTokens = earlier;
3164
+ }
3165
+ if (docTokens !== null && runtime.runDocumentsRoot !== undefined) {
3166
+ // The documents are the chat's: a run filed in another project never reads them.
3167
+ const chatProject = chatProposalsProjectOf(docTokens.chatId);
3168
+ const runProject = b.projectId !== undefined && b.projectId !== DEFAULT_PROJECT_ID ? b.projectId : null;
3169
+ if ((chatProject ?? null) !== runProject) {
3170
+ // A bare retry sends no projectId: it is filed Unfiled, so it is told where its documents belong (fail closed).
3171
+ return reply.code(400).send({
3172
+ code: 'documents_refused',
3173
+ error: chatProject !== null && runProject === null
3174
+ ? `the documents belong to project ${chatProject}: file this run there (send projectId)`
3175
+ : "the documents belong to the chat's project, and this run is filed in another",
3176
+ });
3177
+ }
3178
+ try {
3179
+ staged = await stageRunDocuments(input.sessionId, docTokens.chatId, docTokens.tokens, {
3180
+ authorize: (chatId, tokens) => chatProposals.authorizeDocuments(chatId, tokens),
3181
+ attachment: (chatId, id) => {
3182
+ // An attachment the store no longer has is "no longer attached", not a 500 (resolve throws for an unknown id).
3183
+ try {
3184
+ const hit = chatAttachments.resolve(chatId, [id])[0];
3185
+ return hit === undefined ? null : { name: hit.name, path: hit.path };
3186
+ }
3187
+ catch {
3188
+ return null;
3189
+ }
3190
+ },
3191
+ docsRoot: (projectId) => projectDocsRoot(adapter, projectSettings, projectId),
3192
+ stateRoot: runtime.runDocumentsRoot,
3193
+ });
3194
+ }
3195
+ catch (err) {
3196
+ if (err instanceof DocumentsRefused) {
3197
+ return reply.code(400).send({
3198
+ code: 'documents_refused',
3199
+ error: `can't read ${err.refused.map((r) => `${r.token} (${r.reason})`).join(', ')}`,
3200
+ refused: err.refused,
3201
+ });
3202
+ }
3203
+ return reply.code(409).send({ code: 'documents_unavailable', error: `the documents could not be staged: ${message(err)}` });
3204
+ }
3205
+ }
3206
+ if (staged !== null) {
3207
+ input.extraReadRoots = [...(input.extraReadRoots ?? []), staged.root];
3208
+ input.problem = `${input.problem.trimEnd()}\n\n${documentsClause(staged)}`;
3209
+ }
2698
3210
  try {
2699
3211
  const runId = await adapter.launchRun(input);
2700
3212
  // crew#641/#642 (item 5): when a run is promoted from a chat, record how many seats
@@ -2748,6 +3260,7 @@ runtime = {}) {
2748
3260
  // DES-L9: the revised PR (number, head branch, URL) — the retry index (and a restarted
2749
3261
  // daemon's hydrate) reads it back from here so a stranded revision re-pushes to THAT PR.
2750
3262
  ...(revisesPr !== undefined ? { revisesPr, baseRef: revisesPr.headRef } : {}),
3263
+ ...(reviewChange !== undefined ? { reviewChange } : {}),
2751
3264
  // wicked-studio#27: the trail is likewise the durable record of the group attach —
2752
3265
  // the group index (and a restarted daemon's hydrate) reads it back from here.
2753
3266
  ...(b.campaignId !== undefined ? { campaignId: b.campaignId } : {}),
@@ -2763,6 +3276,30 @@ runtime = {}) {
2763
3276
  ...(b.actor !== undefined ? { actor: b.actor } : {}),
2764
3277
  // crew#627: which linked issues the daemon read into the problem, and which it could not.
2765
3278
  ...(linkedIssues !== undefined ? { linkedIssues } : {}),
3279
+ // DES-CATALOG-002 §4.4: the shape it was launched as, what it was launched with, and the proposal behind it.
3280
+ ...(b.shape !== undefined ? { shape: launchShapeOf(b.shape) } : {}),
3281
+ ...(ctx.fromProposal !== undefined ? { fromProposal: ctx.fromProposal } : {}),
3282
+ envelope: {
3283
+ words: envelopeWords,
3284
+ ...(b.repoRef !== undefined ? { repoRef: b.repoRef } : {}),
3285
+ ...(b.projectId !== undefined ? { projectId: b.projectId } : {}),
3286
+ ...(b.clisJson !== undefined ? { clisJson: b.clisJson } : {}),
3287
+ ...(b.primary !== undefined ? { primary: b.primary } : {}),
3288
+ ...(input.humanConfirm !== undefined ? { humanConfirm: input.humanConfirm } : {}),
3289
+ deliver,
3290
+ ...(b.deliverGate !== undefined ? { deliverGate: b.deliverGate } : {}),
3291
+ ...(b.chatId !== undefined ? { chatId: b.chatId } : {}),
3292
+ ...(b.skipQeAcceptance !== undefined ? { skipQeAcceptance: b.skipQeAcceptance } : {}),
3293
+ ...(b.forceQeAcceptance === true ? { forceQeAcceptance: true } : {}),
3294
+ ...(b.reducedAssurance === true ? { reducedAssurance: true } : {}),
3295
+ ...(b.power !== undefined ? { power: b.power } : {}),
3296
+ ...(b.revisesPr !== undefined ? { revisesPr: b.revisesPr } : {}),
3297
+ ...(b.campaignId !== undefined ? { campaignId: b.campaignId } : {}),
3298
+ ...(b.groupLabel !== undefined ? { groupLabel: b.groupLabel } : {}),
3299
+ ...(revisesPr !== undefined ? { baseRef: revisesPr.headRef } : {}),
3300
+ ...(b.shape !== undefined ? { shape: launchShapeOf(b.shape) } : {}),
3301
+ ...(ctx.fromProposal !== undefined ? { fromProposal: ctx.fromProposal } : {}),
3302
+ },
2766
3303
  });
2767
3304
  // Stamp the index live so the field is served without waiting for a daemon restart.
2768
3305
  if (chatSeatCount !== undefined && chatGrounded !== undefined) {
@@ -2883,6 +3420,186 @@ runtime = {}) {
2883
3420
  const busy = /busy|in flight|already/i.test(msg);
2884
3421
  return reply.code(busy ? 409 : 400).send({ error: msg });
2885
3422
  }
3423
+ };
3424
+ // Launch a run (replaces POST /sessions). `clisJson` defaults to the roster;
3425
+ // `sessionId` is minted if the client omits it.
3426
+ app.post(`${V}/runs`, {
3427
+ config: {
3428
+ manifest: {
3429
+ requestType: 'LaunchRunBody',
3430
+ responseType: 'LaunchRunResponse',
3431
+ // 404/409: unknown project / unknown campaignId (wicked-studio#27) /
3432
+ // archived-or-synthesized project + busy engine + the state-home blocker
3433
+ // (`state_home_unregistered`) + a roster with no eligible seat (`no_eligible_seat`,
3434
+ // wicked-core#461 — see the catch below); 400: zod reject or a retryOf naming no
3435
+ // existing run; 422: the base-skill intake refusal (`base_skill_refused`, crew#554);
3436
+ // 501: campaignId attach on an engine addon without the campaign bindings ("upgrade
3437
+ // the engine").
3438
+ statusCodes: [201, 400, 404, 409, 422, 501],
3439
+ },
3440
+ },
3441
+ }, async (req, reply) => {
3442
+ const out = await launchRun(req.body, { actor: actorOf(req), log: req.log });
3443
+ return reply.code(out.statusCode).send(out.payload);
3444
+ });
3445
+ /**
3446
+ * (DES-CATALOG-002 §4.6) The `job` launcher: a chat job proposal's Go, one launcher per launch kind, each with the
3447
+ * identity derived from the proposal (`sessionId` = its run id, so a retry finds and adopts it), the chat filing, the
3448
+ * shape, and the plan held: a job launched from a chat stops at its first plan unless the person's Start chose a
3449
+ * power run (`power: true`, api-types 0.196.0), which is refused unless this daemon can run that job as one.
3450
+ */
3451
+ const jobRefusalText = (payload) => {
3452
+ const b = payload;
3453
+ return `${typeof b?.error === 'string' ? b.error : 'the launch was refused'}${typeof b?.code === 'string' ? ` (${b.code})` : ''}`;
3454
+ };
3455
+ /**
3456
+ * (operator ruling 2026-11-06) Why a chat job can't run as a power run on this daemon now, else `null`: only a
3457
+ * workflow run on a repository whose workflow is a preset, on an engine with power mode (launchRun's own rule, which
3458
+ * would otherwise run it phased and only say so), with Power mode for new jobs on (chat starts follow the setting).
3459
+ */
3460
+ const chatJobPowerRefusal = async (p) => {
3461
+ const askPlan = 'press Start with Review plan on';
3462
+ if (p.launch !== 'run' && p.launch !== undefined)
3463
+ return `${p.what.label} can't run as a power run; ${askPlan}`;
3464
+ if (p.repoRefs?.[0] === undefined)
3465
+ return `a power run works on a repository, and this job names none; ${askPlan}`;
3466
+ if (!powerSupported())
3467
+ return `this daemon's engine has no power mode; ${askPlan}`;
3468
+ // The operator ruling: chat starts follow the Power-mode default; with it off, a chat job reviews its plan.
3469
+ try {
3470
+ if (((await adapter.getSettings()).powerModeDefault ?? true) === false)
3471
+ return `Power mode for new jobs is off on this daemon; ${askPlan}`;
3472
+ }
3473
+ catch (err) {
3474
+ return `the Power-mode setting could not be read (${err instanceof Error ? err.message : String(err)}); press Start again`;
3475
+ }
3476
+ if (p.shape === undefined)
3477
+ return `this proposal has no shape to launch; ${askPlan}`;
3478
+ const projectId = p.filedIn.projectId;
3479
+ let served;
3480
+ try {
3481
+ served = await servedFor(shapeReads, projectId ?? undefined);
3482
+ }
3483
+ catch (err) {
3484
+ return `${err instanceof Error ? err.message : String(err)}; press Start again`;
3485
+ }
3486
+ const resolved = resolveOption(p.shape.card, p.shape.option, served);
3487
+ if (resolved === null || resolved.workflow === null)
3488
+ return `${p.what.label} has no workflow to run; ${askPlan}`;
3489
+ const scoped = projectId !== null && projectId !== DEFAULT_PROJECT_ID ? projectId : undefined;
3490
+ if (!(await namesPreset(resolved.workflow, scoped)))
3491
+ return `${p.what.label} can't run as a power run (its workflow is not a preset); ${askPlan}`;
3492
+ return null;
3493
+ };
3494
+ proposalLaunchers.register('job', {
3495
+ find: async (identity) => (await adapter.sessions()).includes(identity.runId),
3496
+ live: async (runId) => {
3497
+ const v = await adapter.runView(runId);
3498
+ return v !== undefined && !['completed', 'cancelled', 'failed'].includes(String(v.session.status));
3499
+ },
3500
+ launch: async (d) => {
3501
+ const p = d.resolution;
3502
+ if (p.shape === undefined || p.catalogRev === undefined)
3503
+ throw new Error('this proposal has no shape to launch');
3504
+ const ctx = { actor: d.actor, log: app.log };
3505
+ const projectId = p.filedIn.projectId;
3506
+ const words = (p.brief ?? p.words ?? '').trim();
3507
+ const served = await servedFor(shapeReads, projectId ?? undefined);
3508
+ const resolved = resolveOption(p.shape.card, p.shape.option, served);
3509
+ if (resolved === null)
3510
+ throw new Error(`${p.what.label} is no longer in the catalog`);
3511
+ const selfSeated = resolved.workflow !== null && SELF_SEATED.has(resolved.workflow);
3512
+ // The seats the person saw: the lead, and the roster narrowed to the proposal's keys.
3513
+ const lead = p.seats?.lead ?? undefined;
3514
+ const keys = p.seats?.keys ?? [];
3515
+ // A reshape inherits the held run's roster configuration; its membership is still the proposal's seats (codex r2).
3516
+ let inherited = null;
3517
+ if (p.relaunch?.clisJson !== undefined) {
3518
+ try {
3519
+ const parsedRoster = JSON.parse(p.relaunch.clisJson);
3520
+ if (Array.isArray(parsedRoster))
3521
+ inherited = parsedRoster;
3522
+ }
3523
+ catch {
3524
+ inherited = null;
3525
+ }
3526
+ }
3527
+ const current = launchRosterNaming(rosterWithStanding(), lead);
3528
+ // Inherited configuration for the seats it names; the current roster's entry for a seat added since (codex r3).
3529
+ const roster = inherited === null ? current : [...inherited, ...current.filter((s) => !inherited.some((i) => i.key === s.key))];
3530
+ const narrowed = keys.length > 0 ? roster.filter((s) => keys.includes(String(s.key))) : roster;
3531
+ const missingSeat = keys.find((k) => !roster.some((s) => String(s.key) === k));
3532
+ if (missingSeat !== undefined)
3533
+ throw new Error(`${missingSeat} is not on this daemon's roster; change who works on it`);
3534
+ const common = jobLaunchCommon(p, { runId: d.identity.runId, chatId: d.chatId }, {
3535
+ ...((inherited !== null || narrowed.length !== roster.length) && narrowed.length > 0 ? { clisJson: JSON.stringify(narrowed) } : {}),
3536
+ selfSeated,
3537
+ });
3538
+ // A power Start was checked before accepting; checked again here, so it never runs phased behind the person's back.
3539
+ if (d.power === true) {
3540
+ const why = await chatJobPowerRefusal(p);
3541
+ if (why !== null)
3542
+ throw new Error(why);
3543
+ }
3544
+ if (p.launch === 'run' || p.launch === undefined) {
3545
+ if (resolved.workflow === null)
3546
+ throw new Error(`${p.what.label} has no workflow to run`);
3547
+ const lines = inputLines(p);
3548
+ const out = await launchRun({
3549
+ problem: [words === '' ? p.what.label : words, ...(lines.length > 0 ? [`Inputs:\n${lines.map((l) => `- ${l}`).join('\n')}`] : [])].join('\n\n'),
3550
+ workflow: resolved.workflow,
3551
+ ...(p.repoRefs?.[0] !== undefined ? { repoRef: p.repoRefs[0] } : {}),
3552
+ ...(projectId !== null && projectId !== DEFAULT_PROJECT_ID ? { projectId } : {}),
3553
+ ...common,
3554
+ // (CS4) The documents and the source pick, as tokens and names (never flattened into the brief's prose).
3555
+ ...jobInputsOfProposal(p, runtime.runSourcePicks !== undefined ? (runId) => runtime.runSourcePicks.get(runId) : undefined),
3556
+ // A power run when the person's Start chose one (checked against this daemon just now); otherwise it
3557
+ // stops at its first plan, as every chat job did before (operator ruling 2026-11-06).
3558
+ // (A power launch overrides the plan hold; launchRun refuses rather than run it phased, `powerRequired`.)
3559
+ humanConfirm: 'before:1',
3560
+ power: d.power === true,
3561
+ channel: 'studio',
3562
+ // §2.5: a reshape's replacement keeps the held run's delivery and grouping.
3563
+ ...(p.relaunch?.deliver !== undefined ? { deliver: p.relaunch.deliver } : {}),
3564
+ ...(p.relaunch?.deliverGate !== undefined && p.relaunch.deliver !== 'none' ? { deliverGate: p.relaunch.deliverGate } : {}),
3565
+ ...(p.relaunch?.revisesPr !== undefined && p.relaunch.deliver === 'pr' && p.repoRefs?.[0] !== undefined ? { revisesPr: p.relaunch.revisesPr } : {}),
3566
+ }, { ...ctx, fromProposal: d.pid, ...(d.power === true ? { powerRequired: true } : {}) });
3567
+ if (out.statusCode !== 201)
3568
+ throw new Error(jobRefusalText(out.payload));
3569
+ return;
3570
+ }
3571
+ if (p.launch === 'compose') {
3572
+ const req = p.inputs?.['requirements'];
3573
+ if (projectId === null || req === undefined || req.kind !== 'requirements')
3574
+ throw new Error('Backlog needs a project and the requirements you pick');
3575
+ const out = await composeLaunch(adapter, launchRun, projectId, { requirements: req.refs, ...(words !== '' ? { instructions: words } : {}), shape: common['shape'] }, ctx, {
3576
+ fromProposal: d.pid,
3577
+ humanConfirm: 'before:1',
3578
+ common,
3579
+ });
3580
+ if (out.code !== 202)
3581
+ throw new Error(jobRefusalText(out.body));
3582
+ return;
3583
+ }
3584
+ if (p.launch === 'demo') {
3585
+ const v = (id) => {
3586
+ const x = p.inputs?.[id];
3587
+ return x !== undefined && (x.kind === 'text' || x.kind === 'url') ? x.value : undefined;
3588
+ };
3589
+ // What to show is the person's own field, with the corrections carried (§4.6 rule 6).
3590
+ // What to show: the person's first words, their show field and the corrections, together (codex r3); its length
3591
+ // was checked before Start was offered (codex r4), never clipped here.
3592
+ const show = demoShowOf(p);
3593
+ const out = await demoLaunch(launchRun, projectId ?? DEFAULT_PROJECT_ID, { url: v('url') ?? '', audience: v('audience') ?? '', show, shape: common['shape'] }, ctx, {
3594
+ fromProposal: d.pid,
3595
+ common,
3596
+ }, demoDeps);
3597
+ if (out.code !== 201)
3598
+ throw new Error(jobRefusalText(out.body));
3599
+ return;
3600
+ }
3601
+ throw new Error(`a ${p.launch} job does not start from a chat`);
3602
+ },
2886
3603
  });
2887
3604
  // Run list (replaces GET /sessions). Actionable-first; reconciles the gate and elicitation caches
2888
3605
  // so that terminal-run entries are pruned even when their terminal CoreEvent was missed.
@@ -2986,14 +3703,15 @@ runtime = {}) {
2986
3703
  // are one step, so a gate answered at the same moment can never be stopped by a resolve. The
2987
3704
  // status is read again inside the lock, right before the stop.
2988
3705
  const outcome = await decideExclusively(id, async () => {
2989
- const views = await adapter.sessionsDetail();
2990
- const run = views.find((v) => v.session.id === id);
3706
+ // The replacement is looked up first, so the run's own status is the last read before the stop.
3707
+ const byKnown = b.action === 'superseded' && b.by !== id ? (await adapter.runView(b.by)) !== undefined : true;
3708
+ const run = await adapter.runView(id);
2991
3709
  if (run === undefined)
2992
3710
  return { code: 404, body: { error: 'Run not found' } };
2993
3711
  if (b.action === 'superseded') {
2994
3712
  if (b.by === id)
2995
3713
  return { code: 400, body: { error: '`by` must name another run' } };
2996
- if (!views.some((v) => v.session.id === b.by))
3714
+ if (!byKnown)
2997
3715
  return { code: 400, body: { error: `\`by\` names an unknown run: ${b.by}` } };
2998
3716
  }
2999
3717
  const status = run.session.status;
@@ -3047,8 +3765,7 @@ runtime = {}) {
3047
3765
  // One run's detail.
3048
3766
  app.get(`${V}/runs/:id`, { config: { manifest: { responseType: '{ run: SessionView }', statusCodes: [200, 404] } } }, async (req, reply) => {
3049
3767
  const { id } = req.params;
3050
- const views = await adapter.sessionsDetail();
3051
- const run = views.find((v) => v.session.id === id);
3768
+ const run = await adapter.runView(id);
3052
3769
  if (!run)
3053
3770
  return reply.code(404).send({ error: 'Run not found' });
3054
3771
  await settleDeliveries([run]);
@@ -3077,8 +3794,7 @@ runtime = {}) {
3077
3794
  // is the run's open gate. Read-only.
3078
3795
  app.get(`${V}/governance/steering/author/:runId/draft`, { config: { manifest: { responseType: 'SteeringDraftResponse', statusCodes: [200, 404, 500] } } }, async (req, reply) => {
3079
3796
  const { runId } = req.params;
3080
- const views = await adapter.sessionsDetail();
3081
- const run = views.find((v) => v.session.id === runId);
3797
+ const run = await adapter.runView(runId);
3082
3798
  if (!run)
3083
3799
  return reply.code(404).send({ error: 'Run not found' });
3084
3800
  if (!isSteeringAuthorRun(run))
@@ -3111,8 +3827,7 @@ runtime = {}) {
3111
3827
  },
3112
3828
  }, async (req, reply) => {
3113
3829
  const { id } = req.params;
3114
- const views = await adapter.sessionsDetail();
3115
- const run = views.find((v) => v.session.id === id);
3830
+ const run = await adapter.runView(id);
3116
3831
  if (!run)
3117
3832
  return reply.code(404).send({ error: 'Run not found' });
3118
3833
  if (typeof adapter.workOutput !== 'function') {
@@ -3161,8 +3876,7 @@ runtime = {}) {
3161
3876
  // asks, and is listed as `this PR`.
3162
3877
  app.get(`${V}/runs/:id/deliver-text`, { config: { manifest: { statusCodes: [200, 404] } } }, async (req, reply) => {
3163
3878
  const { id } = req.params;
3164
- const views = await adapter.sessionsDetail();
3165
- const run = views.find((v) => v.session.id === id);
3879
+ const run = await adapter.runView(id);
3166
3880
  if (!run)
3167
3881
  return reply.code(404).send({ error: 'Run not found' });
3168
3882
  const followUps = await evaluatorFollowUps(run);
@@ -3249,8 +3963,7 @@ runtime = {}) {
3249
3963
  if (pushedAlready !== undefined) {
3250
3964
  return reply.code(409).send({ error: pushedOnlyRefusal(id, pushedAlready) });
3251
3965
  }
3252
- const views = await adapter.sessionsDetail();
3253
- const run = views.find((v) => v.session.id === id);
3966
+ const run = await adapter.runView(id);
3254
3967
  if (!run)
3255
3968
  return reply.code(404).send({ error: 'Run not found' });
3256
3969
  // Freeze deliveries (idea 15): nothing pushes while the switch is on.
@@ -3304,6 +4017,11 @@ runtime = {}) {
3304
4017
  let result;
3305
4018
  let codebase;
3306
4019
  let worktreeGone = false;
4020
+ // CS11 (cs11-b review P1): the delivered HEAD of the run branch, captured INSIDE the per-repo
4021
+ // deliver lock below — before the lock is released and `deliverInFlight` cleared — so no
4022
+ // concurrent delivery can move `wicked/<id>` between the push and the read. `undefined` records
4023
+ // the delivery without a commit (the review-change join then keeps the run, fail-closed).
4024
+ let deliveredCommit;
3307
4025
  // DES-L9: a stranded REVISION re-pushes onto its PR's branch (re-checked OPEN via the same
3308
4026
  // resolver), never a new PR; a PR that closed meanwhile is a named 409.
3309
4027
  let revisionRefused;
@@ -3376,6 +4094,17 @@ runtime = {}) {
3376
4094
  // Best-effort: the archive store logs its own failures; a lookup that threw leaves none.
3377
4095
  }
3378
4096
  }
4097
+ // CS11 (cs11-b review P1): read the delivered HEAD of the run branch HERE — still under the
4098
+ // per-repo deliver lock, right after the script's verdict, before the lock releases and
4099
+ // `deliverInFlight` is cleared. The branch lives in the repo root (not this possibly-
4100
+ // throwaway worktree), so a `repoRootOf` read is correct even after `cw` is torn down; the
4101
+ // point is the LOCK, which keeps `wicked/<id>` from moving between the push and this read.
4102
+ if (result !== undefined && result.status === 0) {
4103
+ const deliveredRoot = await repoRootOf(repoRef).catch(() => undefined);
4104
+ if (deliveredRoot !== undefined) {
4105
+ deliveredCommit = (await readDeliveredCommit(deliveredRoot, s.run_branch ?? `wicked/${id}`)) ?? undefined;
4106
+ }
4107
+ }
3379
4108
  }
3380
4109
  finally {
3381
4110
  if (cw !== null)
@@ -3423,6 +4152,11 @@ runtime = {}) {
3423
4152
  const record = deliveryRecordFrom(result.output);
3424
4153
  const url = record !== null && 'url' in record ? record.url : null;
3425
4154
  const pushedOnly = record !== null && 'pushed' in record ? record.pushed : null;
4155
+ // A post-hoc push also needs its delivered head for later reviews' ancestry checks. CS11
4156
+ // (cs11-b review P1): use the SHA captured inside the delivery lock above — not a fresh read
4157
+ // here, after the lock released and `deliverInFlight` was cleared, where a concurrent delivery
4158
+ // could have moved the branch. No delivery to record (`record === null`) attaches no commit.
4159
+ const commit = record === null ? undefined : deliveredCommit;
3426
4160
  // wicked-core#850 EX-04: no engine lift re-verified what this pushed — the run record says so,
3427
4161
  // with the trees the script named (the PR body carries the same label). Built before the
3428
4162
  // outcome branches, so a push-only delivery records it too (codex r1).
@@ -3431,8 +4165,8 @@ runtime = {}) {
3431
4165
  // N1: the script pushed the branch and gh could resolve no GitHub repository for the
3432
4166
  // origin. That IS a delivery — record it, so the run reads `delivery: 'pushed'` — but there
3433
4167
  // is no PR URL to answer with, so the reply says what happened instead of a 200 `prUrl`.
3434
- audit.record('run.delivered', actorOf(req), { runId: id, detail: { pushed: pushedOnly, via: 'post-hoc', assurance } });
3435
- deliveryIndex.setPushed(id, pushedOnly, assurance);
4168
+ audit.record('run.delivered', actorOf(req), { runId: id, detail: { pushed: pushedOnly, via: 'post-hoc', assurance, ...(commit !== undefined ? { commit } : {}) } });
4169
+ deliveryIndex.setPushed(id, pushedOnly, assurance, commit);
3436
4170
  return reply.code(409).send({ error: pushedOnlyRefusal(id, pushedOnly) });
3437
4171
  }
3438
4172
  if (url === null) {
@@ -3444,8 +4178,8 @@ runtime = {}) {
3444
4178
  }
3445
4179
  // The durable record first, then the read-side index — the same write order as the
3446
4180
  // deliver-phase resolution in server.ts, so the index can only LAG a crash, never lead it.
3447
- audit.record('run.delivered', actorOf(req), { runId: id, detail: { url, via: 'post-hoc', assurance, ...(codebase !== undefined ? { codebase } : {}) } });
3448
- deliveryIndex.set(id, url, assurance);
4181
+ audit.record('run.delivered', actorOf(req), { runId: id, detail: { url, via: 'post-hoc', assurance, ...(commit !== undefined ? { commit } : {}), ...(codebase !== undefined ? { codebase } : {}) } });
4182
+ deliveryIndex.set(id, url, assurance, commit);
3449
4183
  return { prUrl: url, assurance, ...(codebase !== undefined ? { codebase } : {}) };
3450
4184
  });
3451
4185
  // Durable pre-gate guidance (DES-UX-002 §7.2 — spec'd there as CREW-UX-4, implemented as
@@ -3505,12 +4239,46 @@ runtime = {}) {
3505
4239
  ...(runtime.entityCount !== undefined ? { entityCount: runtime.entityCount } : {}),
3506
4240
  ...(runtime.freshenCheckout !== undefined ? { freshen: runtime.freshenCheckout } : {}),
3507
4241
  });
4242
+ /** (DES-CATALOG-002 §4.6) Chats whose client renders job proposals (`accepts: ['job']`), by its newest declaration. */
4243
+ const chatAccepts = new Map();
4244
+ /** A seed as the person route's body (one spelling, so its request digest is the same on every retry). */
4245
+ const seedBody = (seed, requestId) => ({
4246
+ card: seed.card,
4247
+ ...(seed.option !== undefined ? { option: seed.option } : {}),
4248
+ ...(seed.depth !== undefined ? { depth: seed.depth } : {}),
4249
+ ...(seed.words !== undefined ? { words: seed.words } : {}),
4250
+ source: seed.source,
4251
+ requestId,
4252
+ });
4253
+ /** The seeded chat's person-made proposal (`POST /chats {seed}`), made or found by its request id. */
4254
+ const seedProposal = async (chatId, seed, requestId, actor) => {
4255
+ const instance = chatHistory?.stateOf(chatId)?.instance ?? null;
4256
+ // The chat is live and may have no turn yet (a new chat's seed always has none): its proposal starts the transcript.
4257
+ chatTranscripts?.start(chatId);
4258
+ const out = await chatProposals.propose(chatId, seedBody(seed, requestId), actor, instance);
4259
+ if (out.code >= 300) {
4260
+ const b = out.body;
4261
+ app.log.warn(`[proposals] chat ${chatId}: its seed proposal was refused (${String(b.code ?? out.code)})`);
4262
+ return { refused: { code: typeof b.code === 'string' ? b.code : 'seed_refused', error: typeof b.error === 'string' ? b.error : 'the seed proposal was refused' } };
4263
+ }
4264
+ return { view: out.body.view };
4265
+ };
4266
+ /** A seed's card, checked before a chat is opened for it (a hidden card only by its alias). `null` = it resolves. */
4267
+ const seedCardRefusal = (card) => {
4268
+ if (card.startsWith('/'))
4269
+ return parseCommand(card) === null ? `no job has the command ${card.slice(0, 80)}` : null;
4270
+ const c = CATALOG_V2_CARDS.find((x) => x.id === card);
4271
+ if (c === undefined)
4272
+ return `there is no job called “${card.slice(0, 80)}”`;
4273
+ return c.hidden === true ? `${c.title} is reached only by its own command` : null;
4274
+ };
3508
4275
  app.post(`${V}/chats`, {
3509
4276
  config: {
3510
4277
  manifest: {
3511
4278
  requestType: 'ChatOpenBody',
3512
4279
  responseType: 'ChatOpenResponse',
3513
- statusCodes: [201, 400, 403, 404, 409, 500, 501],
4280
+ // 200: a seeded retry answers the chat its request already opened (api-types 0.192.0).
4281
+ statusCodes: [200, 201, 400, 403, 404, 409, 500, 501],
3514
4282
  },
3515
4283
  },
3516
4284
  }, async (req, reply) => {
@@ -3519,7 +4287,44 @@ runtime = {}) {
3519
4287
  return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
3520
4288
  }
3521
4289
  const b = parsed.data;
3522
- const chatId = b.chatId ?? randomUUID();
4290
+ // DES-CATALOG-002 §4.6: a seeded open is a person's, refused before a chat exists or a seat warms; its chat id
4291
+ // derives from (the person, the request), so a retry after a lost response lands on the same chat and proposal.
4292
+ let seedActor = null;
4293
+ let seedChatId;
4294
+ if (b.seed !== undefined) {
4295
+ if (!chatJobProposalsOn)
4296
+ return reply.code(400).send({ error: 'this daemon does not take job proposals from a chat' });
4297
+ seedActor = actorOf(req);
4298
+ if (!isHumanOperator(seedActor)) {
4299
+ audit.record('chat.proposal.refused', seedActor, { detail: { reason: 'not_a_person', what: 'seed' } });
4300
+ return reply.code(403).send({ code: 'proposal_refused', error: `only a person starts a chat with a job (you are ${seedActor.kind}/${seedActor.trust}). Nothing was opened.` });
4301
+ }
4302
+ const bad = seedCardRefusal(b.seed.card);
4303
+ if (bad !== null)
4304
+ return reply.code(400).send({ code: 'card_unknown', error: bad });
4305
+ seedChatId = proposalRunId(`seed\u0000${seedActor.id}\u0000${b.requestId}`);
4306
+ // A retry: this request's chat exists (open, or kept in history after a close or a restart). Answer it and its
4307
+ // proposal, completing the proposal while the chat is open; never open the id again (codex r1).
4308
+ const open = askPaths.get(seedChatId) !== undefined || chatScopes.get(seedChatId) !== undefined;
4309
+ if (open || chatHistory?.has(seedChatId) === true) {
4310
+ let view = chatProposals.viewOfPid(seedChatId, personPid(seedChatId, seedActor.id, b.requestId));
4311
+ // The same request id with another seed is not a retry (codex r2).
4312
+ if (view !== null && view.proposal.request?.digest !== requestDigest(seedBody(b.seed, b.requestId))) {
4313
+ return reply.code(409).send({ code: 'request_reused', error: 'this requestId already started a chat with another job', chatId: seedChatId });
4314
+ }
4315
+ if (view === null && open) {
4316
+ const seeded = await seedProposal(seedChatId, b.seed, b.requestId, seedActor);
4317
+ if ('refused' in seeded)
4318
+ return reply.code(409).send({ ...seeded.refused, chatId: seedChatId });
4319
+ view = seeded.view;
4320
+ }
4321
+ return reply.code(200).send({ chatId: seedChatId, seats: [], scope: chatScopes.get(seedChatId) ?? null, refused: [], ...(view !== null ? { proposal: view } : {}), adopted: true });
4322
+ }
4323
+ }
4324
+ const chatId = seedChatId ?? b.chatId ?? randomUUID();
4325
+ // A new chat's declaration is its own (an omitted one is "no job cards"): an id reused after a close never inherits
4326
+ // the previous chat's (codex r2 on Lane D).
4327
+ const openAccepts = b.accepts?.includes('job') === true;
3523
4328
  const requestedRefs = [...(b.repoRef !== undefined ? [b.repoRef] : []), ...(b.repoRefs ?? [])];
3524
4329
  // The scope kind as the open resolves it: the request's, unless an Ask-about-this seed names the repositories.
3525
4330
  let scopeKind = b.scopeKind;
@@ -3638,7 +4443,7 @@ runtime = {}) {
3638
4443
  return reply.code(resolved.status).send({ error: resolved.error });
3639
4444
  workflow = resolved.workflow;
3640
4445
  }
3641
- const statementOpts = { analysis: workflow !== undefined, make: chatProposals.digest() };
4446
+ const statementOpts = { analysis: workflow !== undefined, make: chatProposals.digest(chatId, openAccepts, { appearance: false }) };
3642
4447
  // A chat id this daemon already holds a scope for is LIVE: re-preparing its scratch root and
3643
4448
  // re-opening it would overwrite the statement its seats are reading and (on a changed scope)
3644
4449
  // evict them mid-conversation (Copilot, #518). Close it first, or let the daemon mint the id.
@@ -3653,6 +4458,9 @@ runtime = {}) {
3653
4458
  : `chat ${chatId} is already open on this daemon; DELETE /chats/${chatId} first, or omit chatId to mint a fresh one`,
3654
4459
  });
3655
4460
  }
4461
+ // DES-CATALOG-002 §4.6: this open owns the id now: its declaration is the chat's (an omitted one is "no job cards").
4462
+ // A refused open (409 above) never touched the live chat's (codex r3).
4463
+ chatAccepts.set(chatId, openAccepts);
3656
4464
  // DC-S7: the in-force rules the statement lists; recorded as "told" only once the open succeeds.
3657
4465
  let inForceAtOpen = [];
3658
4466
  // Everything below either ends in `chatScopes.set(chatId, …, token)` or releases the reservation.
@@ -3871,11 +4679,15 @@ runtime = {}) {
3871
4679
  // prominently so the caller does not have to reason about the refused[] array.
3872
4680
  const warm = seats.filter((s) => s.ok);
3873
4681
  const singleSeat = warm.length === 1 ? singleSeatDisclosure(warm[0].cliKey, refused, 'open') : undefined;
4682
+ // DES-CATALOG-002 §4.6: the seeded chat's proposal, made once the chat exists (idempotent by its request id).
4683
+ const seeded = b.seed !== undefined && seedActor !== null ? await seedProposal(chatId, b.seed, b.requestId, seedActor) : null;
4684
+ const seedOut = seeded === null ? {} : 'view' in seeded ? { proposal: seeded.view } : { seedRefused: seeded.refused };
3874
4685
  return reply.code(201).send({
3875
4686
  chatId,
3876
4687
  seats,
3877
4688
  scope,
3878
4689
  refused,
4690
+ ...seedOut,
3879
4691
  ...(workflow !== undefined ? { workflow: workflow.name } : {}),
3880
4692
  ...(projectAttachError !== undefined ? { projectAttachError } : {}),
3881
4693
  ...(singleSeat !== undefined ? { singleSeat } : {}),
@@ -3916,6 +4728,8 @@ runtime = {}) {
3916
4728
  attachments: z.array(z.string().min(1).max(64)).optional(),
3917
4729
  /** (api-types 0.169.0, DES-CHAT-ARTIFACTS-001 §5.1) What studio shows beside the message. */
3918
4730
  context: ChatMessageContextSchema.optional(),
4731
+ /** (api-types 0.192.0, DES-CATALOG-002 §4.6) What the client renders (`['job']`): the newest declaration wins. */
4732
+ accepts: z.array(z.literal('job')).max(4).optional(),
3919
4733
  });
3920
4734
  // DES-CHAT-ARTIFACTS-001 §5.1 (A1): what a turn's block reads — the docs roots, the decorated runs (project,
3921
4735
  // document and chat ids), unit outputs and the acceptance line. One set of deps, so the block and the run pages
@@ -3934,8 +4748,66 @@ runtime = {}) {
3934
4748
  // records go to the live transcript, or the kept history copy once the chat has ended.
3935
4749
  // A dollar figure only from a run whose EVERY dispatched attempt of every agent step reported a price (DES §4.2).
3936
4750
  const proposalCosts = async (view) => runCostFromEvents(view, (await adapter.runEvents(view.session.id)));
4751
+ /**
4752
+ * (DES-CATALOG-002 §2.5) A run is reshapeable only while it waits at its first WORK-plan approval (a PA's scope-only
4753
+ * rev 1 may be accepted): the gate's ord and plan revision as read, which the Reject is then bound to.
4754
+ */
4755
+ const reshapeEligibility = async (runId) => {
4756
+ const after = (why) => ({ refusal: { code: 409, body: { code: 'reshape_after_work', error: `run ${runId} ${why}: change it with the plan's own edit, or start a new job` } } });
4757
+ const run = await adapter.runView(runId);
4758
+ if (run === undefined)
4759
+ return { refusal: { code: 404, body: { error: 'Run not found' } } };
4760
+ if (run.session.status !== 'awaiting_human')
4761
+ return after('is not waiting at its plan');
4762
+ const held = await gateOfRecord(run, undefined);
4763
+ if ('refusal' in held || held.gateKind !== 'plan_approval' || held.gated === undefined)
4764
+ return after('is not waiting at its plan');
4765
+ const rows = await busRows(adapter.busDbPath, runId);
4766
+ if (workPlanAccepted(rows))
4767
+ return after('is past its first plan approval');
4768
+ const planRev = openPlanGateRev(rows);
4769
+ if (planRev === undefined)
4770
+ return after('holds a plan whose version could not be read');
4771
+ return { ord: held.gated.ord, planRev };
4772
+ };
4773
+ /** The held plan answered Reject (`reshaped`) for a reshape, bound to the ord and revision just read. */
4774
+ const reshapeReject = async (runId, actor, pid, expect) => {
4775
+ const elig = await reshapeEligibility(runId);
4776
+ if ('refusal' in elig)
4777
+ return elig.refusal;
4778
+ // A reshape offered on one plan version answers only that version (Lane D, codex r1): a plan revised since is
4779
+ // gate_changed, and the engine checks the same expectation inside its decision.
4780
+ if (expect !== undefined && (expect.ord !== elig.ord || expect.planRev !== elig.planRev)) {
4781
+ return { code: 409, body: { code: 'gate_changed', error: `run ${runId}'s plan changed since this was offered (now version ${elig.planRev}); look at it again`, openOrd: elig.ord, planRev: elig.planRev } };
4782
+ }
4783
+ const out = await decideGate(runId, { approve: false, action: 'reject', amend: 'reshaped', ord: elig.ord, planRev: elig.planRev }, actor, { reshape: pid });
4784
+ return out.code === 200 ? null : { code: out.code, body: (out.body ?? {}) };
4785
+ };
3937
4786
  const chatProposals = new ChatProposals({
3938
4787
  flags: () => chatArtifactFlags,
4788
+ // (DES-CATALOG-002 §2.d piece 4, CS4) The sources a job's pick lists: the project's sources with their switches.
4789
+ ...(runtime.dataGate !== undefined && runtime.runSourcePicks !== undefined
4790
+ ? {
4791
+ jobSources: (projectId) => projectSources(projectId, runSourcesDeps(runtime.dataGate)),
4792
+ webReason: (projectId) => webScopeReason(projectId, {
4793
+ scopedElsewhere: (p) => runtime.dataGate.webScopedElsewhere(p),
4794
+ projectName: async (id) => (await adapter.projectGet(id).catch(() => null))?.name ?? null,
4795
+ }),
4796
+ }
4797
+ : {}),
4798
+ // A5 (DES §6.1-6.2): the person's own edits a refine keeps, from the document's lineage (fail closed: an error
4799
+ // blocks the card, since the landing guard could never pass). Only where a real refine can run.
4800
+ ...(runtime.docBindings !== undefined && runtime.launchBoundRefine !== undefined ? { protectedEdits: async (artifactRef, version, touch) => {
4801
+ const ref = parseArtifactRef(artifactRef);
4802
+ const root = ref === null ? null : await projectDocsRoot(adapter, projectSettings, ref.projectId);
4803
+ if (ref === null || root === null)
4804
+ return { ok: false, error: 'the document is not on this daemon' };
4805
+ const steps = lineageSteps(root, ref.doc, version, (runId) => runtime.docBindings?.allowOf(runId) ?? []);
4806
+ if (steps === null)
4807
+ return { ok: false, error: `its versions up to v${version} could not be read` };
4808
+ const mapped = await protectedEdits(steps, touch);
4809
+ return mapped.ok ? { ok: true, entries: mapped.entries } : mapped;
4810
+ } } : {}),
3939
4811
  catalog: CATALOG_SEEDS,
3940
4812
  records: (chatId) => chatHistory?.messages(chatId) ?? chatTranscripts?.read(chatId) ?? [],
3941
4813
  append: (chatId, record) => {
@@ -3958,9 +4830,7 @@ runtime = {}) {
3958
4830
  analysis: path?.workflow !== undefined,
3959
4831
  };
3960
4832
  },
3961
- rosterEligible: () => rosterWithStanding()
3962
- .filter((s) => s.enabled_for_council && s.seat_eligible_for_work !== false && s.auth !== 'signed_out' && s.optIn !== true)
3963
- .map((s) => ({ key: String(s.key), name: s.display_name || String(s.key) })),
4833
+ rosterEligible: () => proposalRoster(rosterWithStanding()),
3964
4834
  runs: async () => (await adapter.sessionsDetail()).map((v) => decorateRun(v)),
3965
4835
  chatOfRun: (runId) => runTimingIndex.chatIdFor(runId),
3966
4836
  isAskPath: (runId) => runTimingIndex.isAskPath(runId),
@@ -3980,6 +4850,79 @@ runtime = {}) {
3980
4850
  },
3981
4851
  runCostUsd: proposalCosts,
3982
4852
  registry: proposalLaunchers,
4853
+ // DES-CATALOG-002 §4.6: job proposals, resolved against the catalog a launch in the chat's project reads.
4854
+ jobs: () => chatJobProposalsOn,
4855
+ reshapeReject,
4856
+ // DES-CATALOG-002 §2.4: a chat job's run as typed plan edits read it (held at a plan gate, its ord and revision).
4857
+ heldPlan: async (runId) => {
4858
+ const run = await adapter.runView(runId);
4859
+ if (run === undefined)
4860
+ return null;
4861
+ if (['completed', 'failed', 'cancelled'].includes(String(run.session.status)))
4862
+ return { state: 'ended' };
4863
+ if (run.session.status !== 'awaiting_human')
4864
+ return { state: 'running' };
4865
+ const held = await gateOfRecord(run, undefined);
4866
+ if ('refusal' in held || held.gateKind !== 'plan_approval' || held.gated === undefined)
4867
+ return { state: 'running' };
4868
+ const rows = await busRows(adapter.busDbPath, runId);
4869
+ const planRev = openPlanGateRev(rows);
4870
+ if (planRev === undefined)
4871
+ return { state: 'running' };
4872
+ const lead = run.session.primary;
4873
+ return { state: 'held', ord: held.gated.ord, planRev, reshapeable: !workPlanAccepted(rows), lead: typeof lead === 'string' ? lead : null };
4874
+ },
4875
+ preflight: async (p) => {
4876
+ // The project it files into still takes runs: an archived one refuses every new attachment (codex r6).
4877
+ if (p.filedIn.projectId !== null && p.filedIn.projectId !== DEFAULT_PROJECT_ID) {
4878
+ const project = await adapter.projectGet(p.filedIn.projectId).catch(() => null);
4879
+ if (project === null)
4880
+ return `the project ${p.filedIn.label} is no longer on this daemon`;
4881
+ if (project.status === 'archived')
4882
+ return `the project ${p.filedIn.label} is archived; restore it first`;
4883
+ }
4884
+ // A repository job's repository is still registered and its folder is still there (the launch's own refusal,
4885
+ // checked before a reshape answers its held plan; codex r5).
4886
+ const repoRef = p.repoRefs?.[0];
4887
+ // A compose reads its requirements' own repositories (checked below), not the chat's (pi r6).
4888
+ if (repoRef !== undefined && p.launch !== 'compose') {
4889
+ const entry = (await adapter.listRepos().catch(() => [])).find((r) => r.id === repoRef);
4890
+ if (entry === undefined)
4891
+ return `${p.repos[0] ?? repoRef} is no longer registered on this daemon`;
4892
+ const missing = repoFolderMissing(entry);
4893
+ if (missing !== null)
4894
+ return String(repoFolderMissingBody(missing).error ?? `${entry.name}'s folder is missing`);
4895
+ }
4896
+ if (p.launch !== 'compose')
4897
+ return null;
4898
+ const req = p.inputs?.['requirements'];
4899
+ if (p.filedIn.projectId === null)
4900
+ return 'a backlog needs a project';
4901
+ if (req === undefined || req.kind !== 'requirements')
4902
+ return 'pick the requirements first';
4903
+ const steer = (p.brief ?? p.words ?? '').trim();
4904
+ if (steer.length > 500)
4905
+ return 'A backlog takes a steer of at most 500 characters: say it shorter';
4906
+ return composePreflight(adapter, p.filedIn.projectId, req.refs, steer === '' ? undefined : steer);
4907
+ },
4908
+ qeOff: async () => addonSupportsQeOverride() && (await qeAcceptanceNow()) === 'off',
4909
+ powerRefusal: chatJobPowerRefusal,
4910
+ reviewAuthors: async (repoRef, words) => {
4911
+ const root = await repoRootOf(repoRef);
4912
+ if (root === undefined)
4913
+ return null;
4914
+ const ex = await reviewChangeExclusion(words, reviewChangeDeps(repoRef, root));
4915
+ return ex.ok ? ex.excludeSeats : null;
4916
+ },
4917
+ powerPresets: async (projectId) => {
4918
+ if (!powerSupported() || ((await adapter.getSettings()).powerModeDefault ?? true) === false || typeof adapter.listPresets !== 'function')
4919
+ return null;
4920
+ // The launch's own source (namesPreset): this project's presets, else the global ones.
4921
+ return new Set((await adapter.listPresets(projectId !== null && projectId !== DEFAULT_PROJECT_ID ? projectId : undefined)).map((p) => p.name));
4922
+ },
4923
+ acceptsJobs: (chatId) => chatAccepts.get(chatId) === true,
4924
+ served: (projectId) => servedFor(shapeReads, projectId ?? undefined),
4925
+ turnLive: (chatId, turnId) => chatTurns.turnsOf(chatId).some((t) => t.turnId === turnId),
3983
4926
  broadcast: (frame) => runtime.broadcast?.(frame),
3984
4927
  audit: (event, actor, detail) => {
3985
4928
  audit.record(event, actor, { detail });
@@ -4083,12 +5026,20 @@ runtime = {}) {
4083
5026
  // logged, never a retraction of a turn that is already being answered (codex on #808 r2, 9).
4084
5027
  const persistAccepted = (preface, after) => {
4085
5028
  try {
5029
+ // DES-CATALOG-002 §4.6: the client's declaration takes effect with an ACCEPTED message only (a refused one, a
5030
+ // second tab's 409, never changes how a turn in flight is read; codex r2 on Lane D).
5031
+ if (parsed.data.accepts !== undefined)
5032
+ chatAccepts.set(id, parsed.data.accepts.includes('job'));
4086
5033
  after();
4087
5034
  if (preface !== null)
4088
5035
  chatTranscripts?.appendSystem(id, turnId, preface);
4089
5036
  chatTranscripts?.appendUser(id, turnId, text, voice, attached.map(attachmentWire), contextAllowed);
4090
5037
  if (turnBinding !== null)
4091
5038
  chatTranscripts?.appendContext(id, turnId, turnBinding);
5039
+ // DES-CATALOG-002 §4.6: the person's message holds the chat's open job proposal while its seat turn may revise
5040
+ // it (Go waits: 409 `proposal_revising`), written under the lock Go takes.
5041
+ if (contextAllowed)
5042
+ void chatProposals.holdForMessage(id, turnId).catch((err) => req.log.warn(`[proposals] chat ${id}: the hold for turn ${turnId} could not be written: ${message(err)}`));
4092
5043
  // The recorder's audience is the turn's AS THE TURN INDEX HOLDS IT NOW: the eligible roster
4093
5044
  // for a random pick, or the PA the relay narrowed it to during the engine awaits above
4094
5045
  // (`path.started` / `path.repicked` may land before this record exists — ASK-C2, codex on
@@ -4144,7 +5095,7 @@ runtime = {}) {
4144
5095
  return reply.code(409).send({ error: `chat '${id}' was closed while the message was in flight; nothing was sent` });
4145
5096
  }
4146
5097
  if (path.runId !== undefined) {
4147
- const view = (await adapter.sessionsDetail()).find((v) => v.session.id === path.runId);
5098
+ const view = await adapter.runView(path.runId);
4148
5099
  if (view === undefined) {
4149
5100
  askPaths.release(id, lease);
4150
5101
  return reply.code(409).send({ error: `chat '${id}': its path ${path.runId} is gone — open a new chat` });
@@ -4188,6 +5139,15 @@ runtime = {}) {
4188
5139
  });
4189
5140
  }
4190
5141
  const pending = await considerations.pendingPreface(id, { inForce: rules });
5142
+ // A7: a seat is told it can propose a studio theme only when this message carried the tab's appearance (a client
5143
+ // that can preview and apply one sends it).
5144
+ const themeClient = { appearance: msgContext?.appearance !== undefined };
5145
+ // DES-CATALOG-002 §2.3, §4.6: the per-message job lines (the chat catalog digest, the open proposal, the held plan),
5146
+ // read here, before the last check (no await after it). Never in an analysis.
5147
+ // The declaration this message's instructions are written for: its own, else the chat's (applied to the chat only
5148
+ // once the message is accepted; the reply to this turn is read the same way, codex r3).
5149
+ const turnAccepts = parsed.data.accepts !== undefined ? parsed.data.accepts.includes('job') : chatAccepts.get(id) === true;
5150
+ const jobTurn = path.workflow === undefined ? await chatProposals.jobTurn(id, turnAccepts).catch(() => null) : null;
4191
5151
  // DES-CHAT-ARTIFACTS-001 §5.1 (A1): the turn's block — scope checked before anything is read or copied; the
4192
5152
  // copies and briefs land in the scratch root's `open/` and `context/`, read roots of the chat's run.
4193
5153
  // Built in memory here (it awaits); its files are written only after the last check below, with no await between.
@@ -4213,6 +5173,10 @@ runtime = {}) {
4213
5173
  return reply.code(500).send({ error: `could not prepare what this message is about: ${message(err)}. Nothing was sent.` });
4214
5174
  }
4215
5175
  }
5176
+ // crew#1412: each repository's requirements map, read for this message (never fails the turn; published below).
5177
+ const requirementsBuilt = scope !== undefined
5178
+ ? await buildRequirementsMaps(scope, { listRepos: () => adapter.listRepos(), reader: adapter }).catch(() => [])
5179
+ : [];
4216
5180
  // The last await before delivery may also have closed/reopened the chat. From this check
4217
5181
  // through publication and the send there is no await, so no executing turn's files change.
4218
5182
  if (askPaths.get(id)?.generation !== lease || chatScopes.get(id) !== storedScope) {
@@ -4220,7 +5184,7 @@ runtime = {}) {
4220
5184
  }
4221
5185
  if (storedScope !== undefined && scope !== undefined && engine !== undefined &&
4222
5186
  (JSON.stringify(scope) !== JSON.stringify(storedScope) || JSON.stringify(engine) !== JSON.stringify(chatScopes.engineOf(id)))) {
4223
- prepareChatScratch(id, scope, rules, { analysis: path.workflow !== undefined, make: chatProposals.digest(), ...voiceFor(scope.projectId) });
5187
+ prepareChatScratch(id, scope, rules, { analysis: path.workflow !== undefined, make: chatProposals.digest(id, turnAccepts, themeClient), ...voiceFor(scope.projectId) });
4224
5188
  if (chatScopes.refresh(id, storedScope, scope, engine)) {
4225
5189
  chatTranscripts?.registerRoots(id, scope.repos.map((r) => ({ absRoot: resolve(r.rootPath), name: r.name })));
4226
5190
  }
@@ -4254,20 +5218,29 @@ runtime = {}) {
4254
5218
  seatText = `${seatText}\n\n${contextBlock}`;
4255
5219
  }
4256
5220
  // A2: the per-message digest of what the chat can make now (advertised operations only; never in an analysis).
4257
- const makeDigest = path.workflow === undefined ? chatMakeDigest(chatProposals.digest()) : '';
4258
- if (makeDigest !== '')
5221
+ const makeDigest = path.workflow === undefined ? chatMakeDigest(chatProposals.digest(id, turnAccepts, themeClient)) : '';
5222
+ // DES-CATALOG-002 §2.3: with job cards, the make digest rides INSIDE the job block, under its one 2 KB budget.
5223
+ if (jobTurn !== null && jobTurn.mode === 'cards') {
5224
+ seatText = `${seatText}\n\n${chatJobTurnLines(jobTurn.mode, { ...jobTurn.context, preface: makeDigest })}`;
5225
+ }
5226
+ else if (makeDigest !== '') {
5227
+ // An older client's message is today's (its statement lists the job commands).
4259
5228
  seatText = `${seatText}\n\n${makeDigest}`;
5229
+ }
4260
5230
  voice = path.pa !== null ? [path.pa] : [];
4261
5231
  // A random pick reserves every eligible seat until the relay names the PA.
4262
5232
  audience = voice.length > 0 ? voice : path.eligible;
4263
5233
  turn = chatTurns.begin(id, audience, text, ASK_TURN_BUDGET_SECS);
4264
5234
  turnId = turn?.turnId ?? turnId;
5235
+ chatProposals.noteTurnAccepts(id, turnId, turnAccepts);
4265
5236
  // A repo-bound path can deliver; project and multi-repo scopes remain read-only asks. A workflow
4266
5237
  // chat (crew#1157) never delivers: it is bound to its repository read-only, with no deliver.
4267
5238
  const repoRef = scope?.kind === 'repos' && scope.repos.length === 1 ? scope.repos[0].id : undefined;
4268
5239
  const delivers = repoRef !== undefined && path.workflow === undefined;
4269
5240
  // A2: the per-message digest of what the chat can make now (advertised operations only).
4270
- const statementOpts = { analysis: path.workflow !== undefined, make: chatProposals.digest(), ...voiceFor(scope?.projectId) };
5241
+ // crew#1412: written after the last await and the generation check; a map that cannot be written says so.
5242
+ const requirementsMaps = scope !== undefined ? publishRequirementsMaps(scope.cwd, requirementsBuilt) : [];
5243
+ const statementOpts = { analysis: path.workflow !== undefined, make: chatProposals.digest(id, turnAccepts, themeClient), requirementsMaps, ...voiceFor(scope?.projectId) };
4271
5244
  const projectId = scope?.projectId;
4272
5245
  if (path.runId === undefined) {
4273
5246
  const stepId = 'answer-1';
@@ -4352,7 +5325,7 @@ runtime = {}) {
4352
5325
  // The status read above is a pre-check that changes nothing; this read is the one that counts.
4353
5326
  const pathRunId = path.runId;
4354
5327
  const refused = await decideExclusively(pathRunId, async () => {
4355
- const view = (await adapter.sessionsDetail()).find((v) => v.session.id === pathRunId);
5328
+ const view = await adapter.runView(pathRunId);
4356
5329
  if (view === undefined || view.session.status !== 'awaiting_human') {
4357
5330
  return { code: 409, body: {
4358
5331
  code: 'turn_in_flight',
@@ -4410,7 +5383,64 @@ runtime = {}) {
4410
5383
  audience: z.string().max(800).optional(),
4411
5384
  show: z.string().max(4000).optional(),
4412
5385
  helpers: z.array(z.string().min(1).max(64)).max(8).optional(),
5386
+ // (api-types 0.192.0, DES-CATALOG-002 §4.6) a job's edits, merged by the revision rules before Go.
5387
+ option: z.string().trim().min(1).max(80).nullable().optional(),
5388
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
5389
+ repoRef: z.string().trim().min(1).max(200).optional(),
5390
+ seats: z.array(z.string().min(1).max(64)).min(1).max(8).optional(),
5391
+ inputs: RevisionEditsSchema.shape.inputs,
4413
5392
  }).optional(),
5393
+ // (api-types 0.196.0, operator ruling 2026-11-06) a job's Start chooses how it runs: `true` = a power run (no plan
5394
+ // gate), `false` = it stops at its plan. Absent = it stops at its plan, as before.
5395
+ power: z.boolean().optional(),
5396
+ });
5397
+ /** (api-types 0.192.0) `POST /chats/:id/proposals`: a person-made proposal, or a revision of the open one. */
5398
+ const PersonProposalSchema = z.union([
5399
+ z.strictObject({
5400
+ card: z.string().trim().min(1).max(120),
5401
+ option: z.string().trim().min(1).max(80).nullable().optional(),
5402
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
5403
+ words: z.string().max(8000).optional(),
5404
+ source: z.enum(['pick', 'command', 'question', 'suggestion', 'swap']),
5405
+ requestId: z.string().trim().min(1).max(128),
5406
+ }),
5407
+ z.strictObject({
5408
+ revises: z.string().trim().min(1).max(400),
5409
+ edits: RevisionEditsSchema,
5410
+ source: z.enum(['swap', 'suggestion', 'question']),
5411
+ requestId: z.string().trim().min(1).max(128),
5412
+ words: z.string().max(2000).optional(),
5413
+ }),
5414
+ ]);
5415
+ /** The checks every person route makes before a proposal is read: the capability, a person, the chat is theirs. */
5416
+ const personChatGate = (req, id, what) => {
5417
+ const actor = actorOf(req);
5418
+ if (!isHumanOperator(actor)) {
5419
+ audit.record('chat.proposal.refused', actor, { detail: { chatId: id, reason: 'not_a_person', what } });
5420
+ return { refusal: { code: 403, body: { code: 'proposal_refused', error: `only a person ${what} (you are ${actor.kind}/${actor.trust}). Nothing was started.` } } };
5421
+ }
5422
+ const viewer = security.authMode === 'required' ? actor.id : null;
5423
+ if (!CHAT_ID.test(id) || chatHistory === null || !chatHistory.visibleTo(id, viewer)) {
5424
+ return { refusal: { code: 404, body: { error: `no chat ${id} on this daemon` } } };
5425
+ }
5426
+ return { actor, instance: chatHistory.stateOf(id)?.instance ?? null };
5427
+ };
5428
+ app.post(`${V}/chats/:id/proposals`, { config: { manifest: { requestType: 'PersonProposalBody | PersonRevisionBody', responseType: 'PersonProposalResponse', statusCodes: [200, 201, 400, 403, 404, 409] } } }, async (req, reply) => {
5429
+ const { id } = req.params;
5430
+ if (!chatArtifactFlags.proposals || !chatJobProposalsOn)
5431
+ return reply.code(404).send({ error: 'this daemon does not take job proposals from a chat' });
5432
+ const gate = personChatGate(req, id, 'proposes a job');
5433
+ if ('refusal' in gate)
5434
+ return reply.code(gate.refusal.code).send(gate.refusal.body);
5435
+ const parsed = PersonProposalSchema.safeParse(req.body);
5436
+ if (!parsed.success)
5437
+ return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
5438
+ const clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
5439
+ const body = 'revises' in parsed.data
5440
+ ? clean({ ...parsed.data, edits: clean(parsed.data.edits) })
5441
+ : clean(parsed.data);
5442
+ const out = await chatProposals.propose(id, body, gate.actor, gate.instance);
5443
+ return reply.code(out.code).send(out.body);
4414
5444
  });
4415
5445
  app.post(`${V}/chats/:id/proposals/:pid`, { config: { manifest: { requestType: 'ChatProposalDecisionBody', responseType: 'ChatProposalDecisionResponse', statusCodes: [200, 400, 403, 404, 409, 502] } } }, async (req, reply) => {
4416
5446
  const { id, pid } = req.params;
@@ -4437,7 +5467,11 @@ runtime = {}) {
4437
5467
  const edits = parsed.data.edits === undefined
4438
5468
  ? undefined
4439
5469
  : Object.fromEntries(Object.entries(parsed.data.edits).filter(([, v]) => v !== undefined));
4440
- const out = await chatProposals.decide(id, pid, { decision: parsed.data.decision, ...(edits !== undefined ? { edits } : {}) }, actor, instance);
5470
+ const out = await chatProposals.decide(id, pid, {
5471
+ decision: parsed.data.decision,
5472
+ ...(edits !== undefined ? { edits } : {}),
5473
+ ...(parsed.data.power !== undefined ? { power: parsed.data.power } : {}),
5474
+ }, actor, instance);
4441
5475
  return reply.code(out.code).send(out.body);
4442
5476
  });
4443
5477
  const ChatSeatsSchema = z.strictObject({
@@ -4752,6 +5786,10 @@ runtime = {}) {
4752
5786
  const chat = chatHistory.visibleTo(id, viewer)
4753
5787
  ? chatHistory.entry(id, askPaths.get(id)?.pa ?? null, (cid) => askPaths.get(cid) !== undefined || chatScopes.get(cid) !== undefined)
4754
5788
  : null;
5789
+ // DES-CATALOG-002 §4.6: a read that finds a job proposal held by a turn that is gone (failed, expired, or forgotten
5790
+ // by a restart) releases it with its note first, so the proposal reads startable again.
5791
+ if (chat !== null)
5792
+ await chatProposals.reopenStale(id).catch(() => false);
4755
5793
  const messages = chat === null ? null : chatHistory.messages(id);
4756
5794
  if (chat === null || messages === null)
4757
5795
  return reply.code(404).send({ error: `no chat ${id} in this daemon's history` });
@@ -4824,8 +5862,7 @@ runtime = {}) {
4824
5862
  });
4825
5863
  app.get(`${V}/runs/:id/units/:unitKey/output`, async (req, reply) => {
4826
5864
  const { id, unitKey } = req.params;
4827
- const views = await adapter.sessionsDetail();
4828
- const run = views.find((v) => v.session.id === id);
5865
+ const run = await adapter.runView(id);
4829
5866
  if (!run)
4830
5867
  return reply.code(404).send({ error: 'Run not found' });
4831
5868
  const unit = resolveUnit(run, unitKey);
@@ -4917,8 +5954,7 @@ runtime = {}) {
4917
5954
  // per-run event log — what actually happened, not a re-derivation of it.
4918
5955
  app.get(`${V}/runs/:id/evidence`, async (req, reply) => {
4919
5956
  const { id } = req.params;
4920
- const views = await adapter.sessionsDetail();
4921
- const run = views.find((v) => v.session.id === id);
5957
+ const run = await adapter.runView(id);
4922
5958
  if (!run)
4923
5959
  return reply.code(404).send({ error: 'Run not found' });
4924
5960
  const bundle = await buildEvidenceBundle(run, (unitId) => adapter.workOutput(unitId), (runId) => adapter.runEvents(runId));
@@ -4942,8 +5978,7 @@ runtime = {}) {
4942
5978
  const q = req.query;
4943
5979
  const qeRunRaw = Array.isArray(q.qeRun) ? q.qeRun[0] : q.qeRun;
4944
5980
  const qeRunId = qeRunRaw?.trim();
4945
- const views = await adapter.sessionsDetail();
4946
- const run = views.find((v) => v.session.id === id);
5981
+ const run = await adapter.runView(id);
4947
5982
  if (!run)
4948
5983
  return reply.code(404).send({ error: 'Run not found' });
4949
5984
  return acceptanceViewOf(run, { ...(qeRunId !== undefined && qeRunId !== '' ? { qeRunId } : {}) });
@@ -5159,6 +6194,17 @@ runtime = {}) {
5159
6194
  */
5160
6195
  async function gateForDecision(run, namedOrd, opts = {}) {
5161
6196
  const decided = await gateOfRecord(run, namedOrd);
6197
+ // DES-CATALOG-002 §4.6 (codex r1): a plan held for a run launched from a chat proposal is approved only by an
6198
+ // answer bound to its version (`POST /runs/:id/gate` with `planRev`); every other approving path (a gated resume or
6199
+ // reassign, a plan edit at the gate, a standing order) is refused there. Declining stays open.
6200
+ if (!('refusal' in decided) && opts.declining !== true && opts.versioned !== true && decided.gateKind === 'plan_approval'
6201
+ && runTimingIndex.fromProposalOf(run.session.id) !== undefined) {
6202
+ return { refusal: { code: 409, body: {
6203
+ code: 'gate_changed',
6204
+ error: 'This plan was started from a chat proposal: approve it through its gate with the plan version you read (planRev).',
6205
+ ...(await currentPlanOf(run.session.id, false)),
6206
+ } } };
6207
+ }
5162
6208
  // crew#1157: every APPROVING path (the gate route, standing orders, a gated resume or reassign, a
5163
6209
  // plan edit at the gate, the next message of a chat) is judged here, so no path approves a held
5164
6210
  // plan change on an analysis run. Declining stays open.
@@ -5320,8 +6366,7 @@ runtime = {}) {
5320
6366
  };
5321
6367
  }
5322
6368
  return decideExclusively(id, async () => {
5323
- const views = await adapter.sessionsDetail();
5324
- const run = views.find((v) => v.session.id === id);
6369
+ const run = await adapter.runView(id);
5325
6370
  if (!run)
5326
6371
  return { code: 404, body: { error: 'Run not found' } };
5327
6372
  if (run.session.status !== 'awaiting_human') {
@@ -5330,9 +6375,32 @@ runtime = {}) {
5330
6375
  // Decision integrity (api-types 0.44.0; crew#1083 rounds 3–5): the gate this decision answers
5331
6376
  // is the RECORD's — read first thing inside the lock, so the gated unit and its delivery
5332
6377
  // checks below are the ones the record confirms ({@link gateForDecision}).
5333
- const decided = await gateForDecision(run, parsed.data.ord, { declining: !parsed.data.approve });
5334
- if ('refusal' in decided)
5335
- return decided.refusal;
6378
+ const decided = await gateForDecision(run, parsed.data.ord, { declining: !parsed.data.approve, versioned: true });
6379
+ if ('refusal' in decided) {
6380
+ const r = decided.refusal.body;
6381
+ return r?.code === 'gate_changed' ? { code: decided.refusal.code, body: { ...(await currentPlanOf(id, false)), ...r } } : decided.refusal;
6382
+ }
6383
+ // DES-CATALOG-002 §4.6: a plan-gate answer is bound to the plan on screen. A run launched from a chat proposal
6384
+ // REQUIRES `planRev` there, whichever client answers; a send-back needs it on any run. The engine compares it
6385
+ // (and `ord`) inside its own serialized decision, so a re-plan landing after this read still loses.
6386
+ if (decided.gateKind === 'plan_approval') {
6387
+ const fromProposal = runTimingIndex.fromProposalOf(id);
6388
+ // A Reject cancels the run whatever revision it holds, so only an approving answer or a send-back needs it.
6389
+ const bindsPlan = parsed.data.approve || parsed.data.action === 'request_changes';
6390
+ if (parsed.data.planRev === undefined && fromProposal !== undefined && bindsPlan) {
6391
+ return { code: 409, body: {
6392
+ code: 'gate_changed',
6393
+ error: 'Gate changed: this run was started from a chat proposal, so a plan answer must name the plan version it was made on (planRev). Read the plan again and answer it.',
6394
+ ...(await currentPlanOf(id)),
6395
+ } };
6396
+ }
6397
+ if (parsed.data.planRev !== undefined && !adapterSupportsPlanSendBack()) {
6398
+ return { code: 501, body: { error: 'Answering a plan by its version needs a wicked-core-ts that checks it (Core.supportsPlanSendBack); upgrade the engine' } };
6399
+ }
6400
+ }
6401
+ else if (parsed.data.planRev !== undefined) {
6402
+ return { code: 409, body: { code: 'gate_changed', error: 'Gate changed: this answer names a plan version, but the open gate is not a plan approval. Read the gate again.', ...(await currentPlanOf(id)) } };
6403
+ }
5336
6404
  // (crew#1139) A note on a plan approval needs an engine that lands it. An older one refuses it with
5337
6405
  // words that predate notes ("send the edited steps"), so the daemon says what to do instead.
5338
6406
  if (parsed.data.approve && decided.gateKind === 'plan_approval' && (parsed.data.amend ?? '').trim() !== ''
@@ -5385,9 +6453,21 @@ runtime = {}) {
5385
6453
  // confirm, which records it as the judge when this approve answers a `judge_unavailable`
5386
6454
  // gate ("judged by operator").
5387
6455
  adapter.recordGateActor?.(id, `${actor.id} (${actor.kind})`);
5388
- const status = await adapter.confirmGate(id, parsed.data.approve,
5389
- // (DES-RULE-CHECK-001 S2) The engine takes a rule skip's reasons in `amend` as JSON.
5390
- parsed.data.action === SKIP_RULES_ACTION ? skipRulesAmend(parsed.data.skipRules ?? []) : parsed.data.amend, parsed.data.action, parsed.data.amendScope, parsed.data.plan !== undefined ? toLaunchPlan(parsed.data.plan) : undefined);
6456
+ // The expected ord and plan revision ride as the trailing argument only when sent (an answer without them keeps
6457
+ // the confirm's existing arity; DES-CATALOG-002 §4.6).
6458
+ const expect = parsed.data.planRev !== undefined ? { ...(gated !== undefined ? { ord: gated.ord } : parsed.data.ord !== undefined ? { ord: parsed.data.ord } : {}), planRev: parsed.data.planRev } : undefined;
6459
+ const confirmArgs = [
6460
+ id,
6461
+ parsed.data.approve,
6462
+ // (DES-RULE-CHECK-001 S2) The engine takes a rule skip's reasons in `amend` as JSON.
6463
+ parsed.data.action === SKIP_RULES_ACTION ? skipRulesAmend(parsed.data.skipRules ?? []) : parsed.data.amend,
6464
+ parsed.data.action,
6465
+ parsed.data.amendScope,
6466
+ parsed.data.plan !== undefined ? toLaunchPlan(parsed.data.plan) : undefined,
6467
+ ];
6468
+ if (expect !== undefined)
6469
+ confirmArgs.push(expect);
6470
+ const status = await adapter.confirmGate(...confirmArgs);
5391
6471
  // WHO approved/rejected — the gate-decision audit (task #88). The engine
5392
6472
  // records THAT the gate resolved (interaction_requests / gateDecided);
5393
6473
  // only this HTTP layer knows the authenticated principal behind it.
@@ -5415,6 +6495,7 @@ runtime = {}) {
5415
6495
  ...(parsed.data.amendScope !== undefined ? { amendScope: parsed.data.amendScope } : {}),
5416
6496
  ...(parsed.data.plan !== undefined ? { planSteps: parsed.data.plan.steps.length } : {}),
5417
6497
  ...(parsed.data.ord !== undefined ? { ord: parsed.data.ord } : {}),
6498
+ ...(parsed.data.planRev !== undefined ? { planRev: parsed.data.planRev } : {}),
5418
6499
  ...(parsed.data.input !== undefined ? { input: parsed.data.input } : {}),
5419
6500
  ...extraDetail,
5420
6501
  status,
@@ -5461,10 +6542,31 @@ runtime = {}) {
5461
6542
  if (err instanceof PlanLaunchUnsupportedError || err instanceof PlanGateNoteUnsupportedError) {
5462
6543
  return { code: 501, body: { error: message(err) } };
5463
6544
  }
6545
+ // DES-CATALOG-002 §4.6: the engine's own stale-answer refusal (`gate_changed: …`) is the typed 409, with the
6546
+ // plan the gate holds now, so the person reads it again.
6547
+ if (/^gate_changed\b/u.test(message(err))) {
6548
+ return { code: 409, body: { code: 'gate_changed', error: `Gate changed: ${message(err).replace(/^gate_changed:?\s*/u, '')} — read the plan again and answer it.`, ...(await currentPlanOf(id)) } };
6549
+ }
5464
6550
  return { code: 409, body: { error: message(err) } };
5465
6551
  }
5466
6552
  });
5467
6553
  }
6554
+ /** (DES-CATALOG-002 §4.6) The plan a gate holds now, for a `gate_changed` answer: its ord and revision, best-effort. */
6555
+ async function currentPlanOf(runId, readGate = true) {
6556
+ try {
6557
+ // The caller that already read the open gate (and names its ord) asks for the plan revision only.
6558
+ const recorded = readGate ? await recordedOpenGate(runId) : null;
6559
+ const rev = openPlanGateRev(await busRows(adapter.busDbPath, runId));
6560
+ return { ...(recorded?.state === 'open' ? { openOrd: recorded.ord } : {}), ...(rev !== undefined ? { planRev: rev } : {}) };
6561
+ }
6562
+ catch {
6563
+ return {};
6564
+ }
6565
+ }
6566
+ /** Whether the linked engine checks `expectOrd` / `expectPlanRev` (`Core.supportsPlanSendBack`). */
6567
+ function adapterSupportsPlanSendBack() {
6568
+ return typeof adapter.supportsPlanSendBack === 'function' && adapter.supportsPlanSendBack();
6569
+ }
5468
6570
  // The steering gate (§11.1). approve+amend = approve-with-steer; approve:false = reject (cancels).
5469
6571
  app.post(`${V}/runs/:id/gate`, {
5470
6572
  config: {
@@ -5481,6 +6583,98 @@ runtime = {}) {
5481
6583
  const out = await decideGate(id, req.body, actorOf(req));
5482
6584
  return reply.code(out.code).send(out.body);
5483
6585
  });
6586
+ /**
6587
+ * (DES-CATALOG-002 §2.5, api-types 0.192.0) Start a run held at its FIRST work-plan approval again as another card or
6588
+ * option: the crew-made reshape proposal, validated, the held gate answered Reject (`reshaped`) and the replacement
6589
+ * launched from the held run's envelope, all under the chat's lock (`ChatProposals.reshape`).
6590
+ */
6591
+ const ReshapeSchema = z.strictObject({
6592
+ card: z.string().trim().min(1).max(120),
6593
+ option: z.string().trim().min(1).max(80).nullable().optional(),
6594
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
6595
+ inputs: RevisionEditsSchema.shape.inputs,
6596
+ requestId: z.string().trim().min(1).max(128).regex(/^[A-Za-z0-9._-]+$/),
6597
+ /** The person's press on the reshape question: the loss ids it was shown. */
6598
+ confirmLoss: z.array(z.string().min(1).max(40)).min(1).max(12).optional(),
6599
+ /** (api-types 0.194.0) The plan version a `plan_offer` was made on: both or neither. */
6600
+ ord: z.number().int().min(0).optional(),
6601
+ planRev: z.number().int().min(0).optional(),
6602
+ }).refine((b) => (b.ord === undefined) === (b.planRev === undefined), { message: 'send `ord` and `planRev` together (the plan version the offer was made on)' });
6603
+ app.post(`${V}/runs/:id/reshape`, { config: { manifest: { requestType: 'ReshapeRunBody', responseType: 'ReshapeRunResponse', statusCodes: [200, 400, 403, 404, 409, 502] } } }, async (req, reply) => {
6604
+ const { id } = req.params;
6605
+ if (!chatJobProposalsOn)
6606
+ return reply.code(404).send({ error: 'this daemon does not start runs again from a chat' });
6607
+ const parsed = ReshapeSchema.safeParse(req.body);
6608
+ if (!parsed.success)
6609
+ return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
6610
+ const envelope = runTimingIndex.envelopeOf(id);
6611
+ const fromProposal = runTimingIndex.fromProposalOf(id);
6612
+ const chatId = envelope?.chatId ?? runTimingIndex.chatIdFor(id);
6613
+ if (envelope === undefined || fromProposal === undefined || chatId === undefined) {
6614
+ return reply.code(409).send({ code: 'reshape_not_chat', error: `run ${id} was not started from a chat proposal: start the other job in a chat instead` });
6615
+ }
6616
+ const gate = personChatGate(req, chatId, 'starts a run again');
6617
+ if ('refusal' in gate)
6618
+ return reply.code(gate.refusal.code).send(gate.refusal.body);
6619
+ const run = await adapter.runView(id);
6620
+ if (run === undefined)
6621
+ return reply.code(404).send({ error: 'Run not found' });
6622
+ const pid = `${chatId}:reshape:${id}:${parsed.data.requestId}`;
6623
+ // Eligible only while the run waits at its first WORK-plan approval (a PA's scope-only rev 1 may be accepted); a
6624
+ // retry after THIS reshape's own Reject (recorded on its proposal) goes on to its launch (codex r2).
6625
+ if (chatProposals.proposalOfPid(chatId, pid)?.heldRejected !== true) {
6626
+ const elig = await reshapeEligibility(id);
6627
+ if ('refusal' in elig)
6628
+ return reply.code(elig.refusal.code).send(elig.refusal.body);
6629
+ if (parsed.data.planRev !== undefined && (parsed.data.planRev !== elig.planRev || parsed.data.ord !== elig.ord)) {
6630
+ return reply.code(409).send({ code: 'gate_changed', error: `run ${id}'s plan changed since this was offered (now version ${elig.planRev}); look at it again`, openOrd: elig.ord, planRev: elig.planRev });
6631
+ }
6632
+ }
6633
+ const old = chatProposals.proposalOfPid(chatId, fromProposal);
6634
+ const base = old !== null && old.shape !== undefined ? factsOf(old) : null;
6635
+ const facts = {
6636
+ card: parsed.data.card,
6637
+ option: parsed.data.option ?? undefined,
6638
+ depth: parsed.data.depth ?? null,
6639
+ words: base?.words ?? envelope.words,
6640
+ details: base?.details ?? [],
6641
+ repoRef: base?.repoRef ?? envelope.repoRef ?? null,
6642
+ projectId: base?.projectId ?? envelope.projectId ?? null,
6643
+ lead: base?.lead ?? envelope.primary ?? null,
6644
+ seats: base?.seats ?? null,
6645
+ inputs: { ...(base?.inputs ?? {}), ...(parsed.data.inputs ?? {}) },
6646
+ // A QE skip given for the held run is not carried: the new shape's checks are its own.
6647
+ skipQe: null,
6648
+ by: 'person',
6649
+ source: 'reshape',
6650
+ };
6651
+ const out = await chatProposals.reshape(chatId, {
6652
+ pid,
6653
+ oldRunId: id,
6654
+ parentPid: fromProposal,
6655
+ facts,
6656
+ edits: {
6657
+ card: parsed.data.card,
6658
+ ...(parsed.data.option !== undefined ? { option: parsed.data.option } : {}),
6659
+ ...(parsed.data.depth !== undefined ? { depth: parsed.data.depth } : {}),
6660
+ ...(parsed.data.inputs !== undefined ? { inputs: parsed.data.inputs } : {}),
6661
+ },
6662
+ reducedAssurance: envelope.reducedAssurance === true,
6663
+ relaunch: {
6664
+ deliver: envelope.deliver,
6665
+ ...(envelope.deliverGate !== undefined ? { deliverGate: envelope.deliverGate } : {}),
6666
+ ...(envelope.campaignId !== undefined ? { campaignId: envelope.campaignId } : {}),
6667
+ ...(envelope.groupLabel !== undefined ? { groupLabel: envelope.groupLabel } : {}),
6668
+ ...(envelope.revisesPr !== undefined ? { revisesPr: envelope.revisesPr } : {}),
6669
+ ...(envelope.forceQeAcceptance === true ? { forceQeAcceptance: true } : {}),
6670
+ ...(envelope.clisJson !== undefined ? { clisJson: envelope.clisJson } : {}),
6671
+ },
6672
+ request: { id: parsed.data.requestId, digest: requestDigest({ card: parsed.data.card, option: parsed.data.option ?? null, depth: parsed.data.depth ?? null, inputs: parsed.data.inputs ?? null }) },
6673
+ confirmLoss: parsed.data.confirmLoss ?? [],
6674
+ ...(parsed.data.ord !== undefined && parsed.data.planRev !== undefined ? { heldPlan: { ord: parsed.data.ord, planRev: parsed.data.planRev } } : {}),
6675
+ }, gate.actor, gate.instance);
6676
+ return reply.code(out.code).send(out.body);
6677
+ });
5484
6678
  // Cancel a running or paused run (distinct third action, §11.1).
5485
6679
  // (api-types 0.161.0, DES-VOICE) An optional body: the person's `reason` (said or typed) and `input: "voice"`, both
5486
6680
  // kept on the `run.cancelled` audit line. A bodiless cancel is unchanged; voice is a person's only (403).
@@ -5494,8 +6688,7 @@ runtime = {}) {
5494
6688
  const spoken = parsed.data.input === 'voice';
5495
6689
  if (spoken && !isHumanOperator(actorOf(req)))
5496
6690
  return reply.code(403).send({ error: 'Only a person speaks: input "voice" is a person\'s stop' });
5497
- const views = await adapter.sessionsDetail();
5498
- const run = views.find((v) => v.session.id === id);
6691
+ const run = await adapter.runView(id);
5499
6692
  if (!run)
5500
6693
  return reply.code(404).send({ error: 'Run not found' });
5501
6694
  try {
@@ -5513,8 +6706,7 @@ runtime = {}) {
5513
6706
  const { id } = req.params;
5514
6707
  // A gated resume confirms the gate: one decision at a time per run (crew#1083 round 5).
5515
6708
  return decideExclusively(id, async () => {
5516
- const views = await adapter.sessionsDetail();
5517
- const run = views.find((v) => v.session.id === id);
6709
+ const run = await adapter.runView(id);
5518
6710
  if (!run)
5519
6711
  return reply.code(404).send({ error: 'Run not found' });
5520
6712
  // crew#418 A: a run stranded by a deliver-phase lift collision reads `failed` from the engine
@@ -5683,7 +6875,7 @@ runtime = {}) {
5683
6875
  return reply.code(409).send({ error: 'Refused', reason });
5684
6876
  };
5685
6877
  const powerView = async (id) => {
5686
- const view = (await adapter.sessionsDetail()).find((v) => v.session.id === id);
6878
+ const view = await adapter.runView(id);
5687
6879
  if (view === undefined)
5688
6880
  return null;
5689
6881
  const power = view.session.power ?? null;
@@ -5867,8 +7059,7 @@ runtime = {}) {
5867
7059
  reassignsInFlight.add(id);
5868
7060
  try {
5869
7061
  return await decideExclusively(id, async () => {
5870
- const views = await adapter.sessionsDetail();
5871
- const run = views.find((v) => v.session.id === id);
7062
+ const run = await adapter.runView(id);
5872
7063
  if (!run)
5873
7064
  return reply.code(404).send({ error: 'Run not found' });
5874
7065
  // Wave 6 (F-7R2-007 root fix): a run PARKED at a gate on a dead seat — the stall watchdog's
@@ -6013,8 +7204,13 @@ runtime = {}) {
6013
7204
  // read it. A restart is routine: deploy, crash, laptop sleep.
6014
7205
  app.get(`${V}/runs/:id/gate`, async (req, reply) => {
6015
7206
  const { id } = req.params;
7207
+ // F35: this run's view only, never every run's (studio polls this route for every parked run, from
7208
+ // every open tab). Each read is a copy of one run from the shared snapshot, so a read after an
7209
+ // await sees a change the adapter learned of during it (a frame, or a write it made); any other
7210
+ // change is at most the snapshot's age bound old.
7211
+ const runOf = () => adapter.runView(id);
6016
7212
  // wicked-core#850: the gate answer carries the gated unit's receipt — what assured the work it asks about.
6017
- const unitAt = async (ord) => (await adapter.sessionsDetail()).find((v) => v.session.id === id)?.units?.find((u) => u.ord === ord);
7213
+ const unitAt = async (ord) => (await runOf())?.units?.find((u) => u.ord === ord);
6018
7214
  // (rejudge, api-types 0.134.0) A gate whose unit no judge could rule on says whether its judge
6019
7215
  // can be re-run now, and from which seats — the engine's own selection, read each time (a seat
6020
7216
  // signed in since the pause counts). Absent on every other gate and on an addon without the read.
@@ -6042,7 +7238,7 @@ runtime = {}) {
6042
7238
  const skipQeAt = async (gated) => {
6043
7239
  if (gated === undefined || !isDeliverUnit(gated))
6044
7240
  return {};
6045
- const run = (await adapter.sessionsDetail()).find((v) => v.session.id === id);
7241
+ const run = await runOf();
6046
7242
  if (run === undefined)
6047
7243
  return {};
6048
7244
  const decision = qeDecisionOf(run);
@@ -6080,8 +7276,7 @@ runtime = {}) {
6080
7276
  if (cached) {
6081
7277
  const servable = recorded === null
6082
7278
  || (recorded.state === 'open' && cached.ord === recorded.ord)
6083
- || (recorded.state === 'none'
6084
- && (await adapter.sessionsDetail()).find((v) => v.session.id === id)?.session.status === 'awaiting_human');
7279
+ || (recorded.state === 'none' && (await runOf())?.session.status === 'awaiting_human');
6085
7280
  if (servable) {
6086
7281
  // One read of the gated unit serves both its receipt and its re-judge offer.
6087
7282
  const gated = await unitAt(cached.ord);
@@ -6095,11 +7290,16 @@ runtime = {}) {
6095
7290
  // common case here, since studio polls this route for runs that are merely finished.
6096
7291
  //
6097
7292
  // Reading status first is therefore CHEAPER than not reading it, the opposite of what the first
6098
- // cut of this assumed: it trades one `sessionsDetail()` for replaying an entire event history,
7293
+ // cut of this assumed: it trades one read of the run's view for replaying an entire event history,
6099
7294
  // and it was that skipped check which made a completed run answer 503 on any build without the
6100
7295
  // binding (CI caught it) — an error where the honest, knowable answer was "no gate".
6101
- const views = await adapter.sessionsDetail();
6102
- const run = views.find((v) => v.session.id === id);
7296
+ let run = await runOf();
7297
+ // F35: the engine's gate record was read before the view and outranks it. A record showing a gate
7298
+ // open beside no view of the run, or a view of it still moving, means the shared snapshot predates
7299
+ // the pause (its frame has not landed yet): read the run from a fold that starts now.
7300
+ if (recorded?.state === 'open' && run?.session.status !== 'awaiting_human') {
7301
+ run = await adapter.runView(id, { fresh: true });
7302
+ }
6103
7303
  if (!run)
6104
7304
  return reply.code(404).send({ error: 'Run not found' });
6105
7305
  if (run.session.status !== 'awaiting_human') {
@@ -6784,23 +7984,39 @@ runtime = {}) {
6784
7984
  // wf-catalog (api-types 0.168.0): the workflows as a categorised catalog with the requesting
6785
7985
  // operator's usage. Metadata is the ONE data module (`workflow-catalog/catalog-data.ts`); what a
6786
7986
  // workflow is and does stays on its def; usage is derived from the runs and the launch trail.
6787
- app.get(`${V}/workflows/catalog`, { config: { manifest: { responseType: 'WorkflowCatalogResponse', statusCodes: [200, 400] } } }, async (req, reply) => {
7987
+ app.get(`${V}/workflows/catalog`, { config: { manifest: { responseType: 'WorkflowCatalogResponse | WorkflowCatalogV2Response', statusCodes: [200, 400, 503] } } }, async (req, reply) => {
6788
7988
  const raw = req.query?.projectId;
6789
7989
  if (raw !== undefined && (typeof raw !== 'string' || raw.length > 200)) {
6790
7990
  return reply.code(400).send({ error: '`projectId` must be a string' });
6791
7991
  }
7992
+ // DES-CATALOG-002 §4.1: `v=2` answers the catalog by verb; anything else but an absent `v` is a 400, so v1 stays
7993
+ // exactly as it was for every caller that sends none.
7994
+ const version = req.query?.v;
7995
+ if (version !== undefined && version !== '1' && version !== '2') {
7996
+ return reply.code(400).send({ error: '`v` must be 1 or 2' });
7997
+ }
6792
7998
  const projectId = typeof raw === 'string' && raw !== '' ? raw : null;
6793
7999
  const { workflows } = await adapter.workflowCatalog();
6794
8000
  let presets = [];
8001
+ // v2 serves only presets it actually read (an unknown project's global ones included); no read at all is a 503.
8002
+ let presetsRead = true;
6795
8003
  try {
6796
8004
  presets = await adapter.listPresets(projectId ?? undefined);
6797
8005
  }
6798
8006
  catch (err) {
6799
8007
  // An unknown project: the global presets (built-in attribution and saved ones still hold, agy r1).
6800
8008
  // An engine without presets lists the served defs only. Either way, said once in the log.
6801
- app.log.warn(`workflows/catalog: the presets could not be read${projectId !== null ? ` for project ${projectId}` : ''} (${message(err)}); listing ${projectId !== null ? 'the global ones' : 'the served workflows only'}`);
6802
- if (projectId !== null)
6803
- presets = await adapter.listPresets().catch(() => []);
8009
+ app.log.warn(`workflows/catalog: the presets could not be read${projectId !== null ? ` for project ${projectId}` : ''} (${message(err)}); v1 lists ${projectId !== null ? 'the global ones' : 'the served workflows only'}, v2 answers 503 if no presets read succeeds`);
8010
+ presetsRead = false;
8011
+ if (projectId !== null) {
8012
+ try {
8013
+ presets = await adapter.listPresets();
8014
+ presetsRead = true;
8015
+ }
8016
+ catch {
8017
+ presets = [];
8018
+ }
8019
+ }
6804
8020
  }
6805
8021
  const views = await adapter.sessionsDetail();
6806
8022
  // codex r1: date terminal runs that have no `run.ended` entry from their event log, as GET /runs
@@ -6818,6 +8034,26 @@ runtime = {}) {
6818
8034
  retryOf: retryIndex.retryOfFor(view.session.id),
6819
8035
  principal: runTimingIndex.principalFor(view.session.id),
6820
8036
  }));
8037
+ if (version === '2') {
8038
+ // v2 fails closed (codex r2): a catalog read without the project's presets or the phase catalog would show checks
8039
+ // and a revision a launch could not honour. v1 keeps its fallback below.
8040
+ let entries;
8041
+ try {
8042
+ entries = await adapter.catalog();
8043
+ }
8044
+ catch (err) {
8045
+ return reply.code(503).send({ code: 'catalog_unavailable', error: `the catalog could not be read: ${message(err)}` });
8046
+ }
8047
+ if (!presetsRead)
8048
+ return reply.code(503).send({ code: 'catalog_unavailable', error: 'the presets could not be read' });
8049
+ return buildWorkflowCatalogV2({
8050
+ defs: workflows, presets, entries, actorId: me, projectId,
8051
+ runs: runs.map((r) => {
8052
+ const shape = runTimingIndex.shapeOf(r.id);
8053
+ return shape === undefined ? r : { ...r, shape: { card: shape.card, option: shape.option } };
8054
+ }),
8055
+ });
8056
+ }
6821
8057
  const body = buildWorkflowCatalog({
6822
8058
  defs: workflows, presets, runs, actorId: me, projectId,
6823
8059
  // The same rule as `GET /health.capabilities.apps.turns`.
@@ -6825,6 +8061,58 @@ runtime = {}) {
6825
8061
  });
6826
8062
  return body;
6827
8063
  });
8064
+ /**
8065
+ * (DES-CATALOG-002 §2.3, api-types 0.192.0 `DetectShapeRequest` → `ShapeGuess`) Free words typed into the `/` list
8066
+ * that match no command: the words layer, then (unless `seat: false`) the hidden `detect-shape` turn on one seat,
8067
+ * validated, cross-checked and banded. A person's route: it spends a seat's turn, and it proposes and starts nothing.
8068
+ */
8069
+ const detectService = new DetectService({
8070
+ turn: seatTurn({
8071
+ adapter,
8072
+ roster: rosterWithStanding,
8073
+ timeoutMs: DETECT_TIMEOUT_MS,
8074
+ outputOf: async (runId) => {
8075
+ const view = await adapter.runView(runId);
8076
+ const unit = view?.units.find((u) => u.ord === 1) ?? view?.units[0];
8077
+ return view !== undefined && unit !== undefined ? adapter.workOutput(coreUnitId(runId, unit)) : null;
8078
+ },
8079
+ }),
8080
+ cancelRun: async (runId) => {
8081
+ await adapter.cancelRun(runId);
8082
+ },
8083
+ catalog: async (projectId) => {
8084
+ const served = await servedFor(shapeReads, projectId ?? undefined);
8085
+ const status = (card, option) => resolveOption(card, option, served)?.resolved.status ?? 'unavailable';
8086
+ // The detect turn launches repo-less and project-less: the global rows (and the project's) are what could shadow it.
8087
+ // A read that fails is a shadow: the seat is not asked (codex r7).
8088
+ const detectShadowed = await shadowCheck(async () => [...(await adapter.listPresets()), ...(projectId !== null ? await adapter.listPresets(projectId) : [])]);
8089
+ return { rev: served.rev, status, available: (card, option) => status(card, option) === 'available', detectShadowed };
8090
+ },
8091
+ costOf: async (runId) => {
8092
+ const view = await adapter.runView(runId);
8093
+ return view === undefined ? null : runCostFromEvents(view, (await adapter.runEvents(runId)));
8094
+ },
8095
+ audit: (row) => audit.record('workflow.detect', { id: row.actor, kind: 'human', trust: 'operator' }, { ...(row.runId !== null ? { runId: row.runId } : {}), detail: { ...row } }),
8096
+ // A detect-shape run's id carries its fence (mcp/run-fence.ts), across a restart.
8097
+ newId: () => fencedRunId(),
8098
+ log: (m) => app.log.warn(m),
8099
+ });
8100
+ const DetectSchema = z.strictObject({
8101
+ text: z.string().max(DETECT_MAX_CHARS),
8102
+ seat: z.boolean().optional(),
8103
+ projectId: z.string().trim().min(1).max(200).optional(),
8104
+ });
8105
+ app.post(`${V}/workflows/catalog/detect`, { config: { manifest: { requestType: 'DetectShapeRequest', responseType: 'ShapeGuess', statusCodes: [200, 400, 403, 409, 503] } } }, async (req, reply) => {
8106
+ const actor = actorOf(req);
8107
+ if (!isHumanOperator(actor)) {
8108
+ return reply.code(403).send({ code: 'detect_refused', error: `only a person asks what job their words are (you are ${actor.kind}/${actor.trust})` });
8109
+ }
8110
+ const parsed = DetectSchema.safeParse(req.body);
8111
+ if (!parsed.success)
8112
+ return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
8113
+ const out = await detectService.detect({ text: parsed.data.text, ...(parsed.data.seat !== undefined ? { seat: parsed.data.seat } : {}), projectId: parsed.data.projectId ?? null }, actor);
8114
+ return reply.code(out.code).send(out.body);
8115
+ });
6828
8116
  app.get(`${V}/workflows/:id`, async (req, reply) => {
6829
8117
  const { id } = req.params;
6830
8118
  const workflow = adapter.getWorkflow(id);
@@ -6932,6 +8220,7 @@ runtime = {}) {
6932
8220
  q: z.string().optional(),
6933
8221
  risk: z.enum(['risk', 'no-risk']).optional(),
6934
8222
  category: z.enum(['functional', 'config-data']).optional(),
8223
+ mismatch: z.enum(['yes', 'no']).optional(),
6935
8224
  domain: z.string().optional(),
6936
8225
  offset: z.coerce.number().int().min(0).prefault(0),
6937
8226
  limit: z.coerce.number().int().min(1).max(200).prefault(50),
@@ -6948,8 +8237,9 @@ runtime = {}) {
6948
8237
  }
6949
8238
  let page;
6950
8239
  let coverage = null;
8240
+ let minimum = null;
6951
8241
  try {
6952
- ({ page, coverage } = await listRequirementsRead(repo, parsed.data, adapter));
8242
+ ({ page, coverage, minimum } = await listRequirementsRead(repo, parsed.data, adapter));
6953
8243
  }
6954
8244
  catch (err) {
6955
8245
  // wicked-core#406: a CURRENT engine with no repo-graph root is a 503, not a 500.
@@ -6962,9 +8252,11 @@ runtime = {}) {
6962
8252
  // Not generated yet is a state, typed by `code`, not a refusal (lane repo-page). It says how
6963
8253
  // far the repository is ("23% real requirements · 4397 placeholders · target 80%";
6964
8254
  // wicked-core#1233), from the very engine read the page used, when it has a store to count.
6965
- return reply
6966
- .code(404)
6967
- .send(coverage === null ? REQUIREMENTS_NOT_GENERATED : { ...REQUIREMENTS_NOT_GENERATED, coverage });
8255
+ return reply.code(404).send({
8256
+ ...REQUIREMENTS_NOT_GENERATED,
8257
+ ...(coverage === null ? {} : { coverage }),
8258
+ ...(minimum === null ? {} : { minimum }),
8259
+ });
6968
8260
  }
6969
8261
  // Overrides keyed by ids the corpus no longer mints (an estate id-scheme migration re-keys
6970
8262
  // method/field SymbolIds) would otherwise vanish without a trace — the count is on the page
@@ -6974,6 +8266,33 @@ runtime = {}) {
6974
8266
  }
6975
8267
  return page;
6976
8268
  });
8269
+ // P3 (operator ruling 2026-11-06): raise, lower or clear a repository's OWN minimum from the requirements page.
8270
+ // `minPct: null` clears it (the Settings minimum applies again).
8271
+ app.put(`${V}/repos/:id/requirements/minimum`, { config: { manifest: { requestType: 'RequirementsMinimumBody', responseType: 'RequirementsMinimumResponse', statusCodes: [200, 400, 404, 409, 500, 503] } } }, async (req, reply) => {
8272
+ const { id } = req.params;
8273
+ const repos = await adapter.listRepos();
8274
+ const repo = repos.find((r) => r.id === id);
8275
+ if (!repo)
8276
+ return reply.code(404).send({ error: `Repo ${id} not found` });
8277
+ const parsed = ReqMinimumSchema.safeParse(req.body);
8278
+ if (!parsed.success)
8279
+ return reply.code(400).send(invalidBody(parsed.error, 'Invalid minimum'));
8280
+ let set;
8281
+ try {
8282
+ set = await setRepoMinimum(repo, parsed.data.minPct);
8283
+ }
8284
+ catch (err) {
8285
+ const status = codeGraphErrorStatus(err);
8286
+ if (status !== null)
8287
+ return reply.code(status).send({ error: message(err) });
8288
+ return reply.code(500).send({ error: `the minimum could not be saved: ${message(err)}` });
8289
+ }
8290
+ if (!set) {
8291
+ return reply.code(409).send({ error: `${repo.name} has no code graph yet, so it has no minimum of its own to set` });
8292
+ }
8293
+ const { minimum } = await listRequirementsRead(repo, { offset: 0, limit: 0 }, adapter);
8294
+ return { minimum };
8295
+ });
6977
8296
  app.get(`${V}/repos/:id/requirements/:key`, async (req, reply) => {
6978
8297
  const { id, key } = req.params;
6979
8298
  const repos = await adapter.listRepos();
@@ -7318,158 +8637,8 @@ runtime = {}) {
7318
8637
  return reply.code(201).send({ terminalId: termId, cli, action });
7319
8638
  });
7320
8639
  }
7321
- const containerLoginOutcomes = new Map();
7322
- const containerSeat = (cli) => isContainerSeatFloor() && isContainerLoginCli(cli) && rosterWithStanding().some((seat) => seat.key === cli);
7323
- const loginError = (stderr) => loginDetail(stderr) || 'seat-login failed';
7324
- // One sign-in/sign-out at a time per seat, and a generation every new sign-in and every sign-out
7325
- // bumps (agy crew-r1): an abandoned login terminal that exits later never ingests over a newer
7326
- // sign-in or a sign-out, and an ingest in flight finishes before a sign-out runs.
7327
- const loginGeneration = new Map();
7328
- const seatOps = new Map();
7329
- const serial = (cli, op) => {
7330
- const next = (seatOps.get(cli) ?? Promise.resolve()).then(op, op);
7331
- seatOps.set(cli, next.catch(() => undefined));
7332
- return next;
7333
- };
7334
- const bump = (cli) => {
7335
- const g = (loginGeneration.get(cli) ?? 0) + 1;
7336
- loginGeneration.set(cli, g);
7337
- return g;
7338
- };
7339
- // The one sign-in per seat, reserved synchronously from the request's first await until its
7340
- // ingest settles (codex crew-r1/r2: two sessions would share the engine's login session), and
7341
- // released only by its owner (the generation that reserved it).
7342
- const openLogins = new Map();
7343
- const release = (cli, generation) => {
7344
- if (openLogins.get(cli) === generation)
7345
- openLogins.delete(cli);
7346
- };
7347
- app.post(`${V}/seats/:cli/container-login`, { config: { manifest: { requestType: 'SeatSessionBody', responseType: 'SeatContainerLoginResponse', statusCodes: [201, 400, 404, 502] } } }, async (req, reply) => {
7348
- const { cli } = req.params;
7349
- if (!containerSeat(cli))
7350
- return reply.code(404).send({ error: `container login unavailable for seat: ${cli}` });
7351
- const parsed = SeatSessionSchema.safeParse(req.body ?? {});
7352
- if (!parsed.success)
7353
- return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
7354
- if (openLogins.has(cli)) {
7355
- return reply.code(409).send({ error: `a sign-in is already open for ${cli}; finish or close it first` });
7356
- }
7357
- // Reserved BEFORE the first await (codex crew-r1): a sign-out that lands meanwhile wins.
7358
- const generation = bump(cli);
7359
- openLogins.set(cli, generation);
7360
- containerLoginOutcomes.delete(cli);
7361
- const out = await serial(cli, () => runSeatLogin('argv', cli, seatLoginDeps));
7362
- if (out.rc !== 0) {
7363
- release(cli, generation);
7364
- return reply.code(502).send({ error: loginError(out.stderr) });
7365
- }
7366
- if (loginGeneration.get(cli) !== generation) {
7367
- release(cli, generation);
7368
- return reply.code(409).send({ error: `the ${cli} sign-in was superseded (a sign-out or another sign-in)` });
7369
- }
7370
- let argv;
7371
- try {
7372
- const value = JSON.parse(out.stdout);
7373
- if (!Array.isArray(value) || value.length === 0 || !value.every((arg) => typeof arg === 'string' && arg.length > 0)) {
7374
- throw new Error('seat-login argv must be a non-empty array of non-empty strings');
7375
- }
7376
- argv = value;
7377
- }
7378
- catch (err) {
7379
- release(cli, generation);
7380
- return reply.code(502).send({ error: message(err) });
7381
- }
7382
- let termId = null;
7383
- let completed = false;
7384
- const exitedEarly = new Set();
7385
- const ingest = () => serial(cli, async () => {
7386
- // A newer sign-in or a sign-out superseded this terminal: nothing to ingest or record.
7387
- if (loginGeneration.get(cli) !== generation)
7388
- return;
7389
- // Refusals the OLD credential earned up to now are superseded by this sign-in (codex
7390
- // crew-r2: a 401 during the interactive login must not outlive it).
7391
- const cutoff = Date.now();
7392
- const result = await runSeatLogin('ingest', cli, seatLoginDeps);
7393
- // The broker may have changed whatever happens next: the next reading is its own.
7394
- containerStatus.invalidate(cli);
7395
- rosterWithStanding.reprobe?.(cli);
7396
- const outcome = { cli, ok: result.rc === 0, at: new Date().toISOString() };
7397
- if (result.rc !== 0)
7398
- outcome.error = loginError(result.stderr);
7399
- else {
7400
- try {
7401
- const value = JSON.parse(result.stdout);
7402
- if (value === null || !Array.isArray(value.files) || !value.files.every((file) => typeof file === 'string') ||
7403
- !(value.expires_at === null || (typeof value.expires_at === 'number' && Number.isFinite(value.expires_at)))) {
7404
- throw new Error('invalid seat-login ingest response');
7405
- }
7406
- // Only the public ingest fields cross the wire; raw stdout may contain credentials.
7407
- outcome.files = value.files;
7408
- outcome.expires_at = value.expires_at;
7409
- }
7410
- catch {
7411
- outcome.ok = false;
7412
- outcome.error = 'invalid seat-login ingest response';
7413
- }
7414
- }
7415
- if (outcome.ok) {
7416
- seatHealth.clearAuthFailureBefore(cli, cutoff);
7417
- seatHealth.clearRecentBench(cli);
7418
- }
7419
- // A sign-out (or a newer sign-in) while this ingest ran owns the outcome now.
7420
- if (loginGeneration.get(cli) === generation)
7421
- containerLoginOutcomes.set(cli, outcome);
7422
- }).finally(() => release(cli, generation));
7423
- const done = () => {
7424
- if (completed)
7425
- return;
7426
- completed = true;
7427
- stop();
7428
- void ingest();
7429
- };
7430
- // Subscribe before spawn: an immediate exit still needs exactly one ingest.
7431
- const stop = adapter.onEvent((event) => {
7432
- if (event.type !== 'terminalExited' || typeof event.id !== 'string')
7433
- return;
7434
- if (termId === null)
7435
- exitedEarly.add(event.id);
7436
- else if (event.id === termId)
7437
- done();
7438
- });
7439
- try {
7440
- termId = await adapter.openTerminal(homedir(), argv, parsed.data.cols ?? 100, parsed.data.rows ?? 30, true);
7441
- }
7442
- catch (err) {
7443
- stop();
7444
- release(cli, generation);
7445
- return reply.code(400).send({ error: message(err) });
7446
- }
7447
- if (exitedEarly.has(termId))
7448
- done();
7449
- return reply.code(201).send({ terminalId: termId, cli, action: 'sign_in' });
7450
- });
7451
- app.get(`${V}/seats/:cli/container-login`, { config: { manifest: { responseType: 'SeatContainerLoginOutcome', statusCodes: [200, 404] } } }, async (req, reply) => {
7452
- const { cli } = req.params;
7453
- const outcome = containerSeat(cli) ? containerLoginOutcomes.get(cli) : undefined;
7454
- if (outcome === undefined)
7455
- return reply.code(404).send({ error: `no container login outcome for seat: ${cli}` });
7456
- return reply.send(outcome);
7457
- });
7458
- app.post(`${V}/seats/:cli/container-logout`, { config: { manifest: { responseType: 'SeatContainerLogoutResponse', statusCodes: [200, 404, 502] } } }, async (req, reply) => {
7459
- const { cli } = req.params;
7460
- if (!containerSeat(cli))
7461
- return reply.code(404).send({ error: `container logout unavailable for seat: ${cli}` });
7462
- bump(cli);
7463
- const out = await serial(cli, async () => {
7464
- containerLoginOutcomes.delete(cli);
7465
- return runSeatLogin('sign-out', cli, seatLoginDeps);
7466
- });
7467
- // Whatever the engine managed before failing, the next reading is the broker's (codex crew-r1).
7468
- containerStatus.invalidate(cli);
7469
- rosterWithStanding.reprobe?.(cli);
7470
- if (out.rc !== 0)
7471
- return reply.code(502).send({ error: loginError(out.stderr) });
7472
- return reply.send({ cli, action: 'sign_out' });
8640
+ registerSeatContainerLoginRoutes(app, {
8641
+ adapter, rosterWithStanding, containerStatus, seatHealth, seatLoginDeps, parseSession: (body) => SeatSessionSchema.safeParse(body),
7473
8642
  });
7474
8643
  // Resize a live terminal's PTY.
7475
8644
  app.post(`${V}/terminals/:id/resize`, async (req, reply) => {
@@ -8538,12 +9707,12 @@ runtime = {}) {
8538
9707
  // crew#371: a project's requirements / domain / coverage, folded over its repos' own reads.
8539
9708
  registerProjectAggregateRoutes(app, adapter);
8540
9709
  // crew#372: draft a product plan from selected requirements, as a governed run via POST /runs.
8541
- registerProductRoutes(app, adapter);
9710
+ registerProductRoutes(app, adapter, launchRun);
8542
9711
  // ── Capture (Studio OS behaviour 8) — notes and photos → a project-filed run whose output is
8543
9712
  // proposals in the queue above; the launch is POST /runs itself (api/capture.ts).
8544
9713
  registerCaptureRoutes(app);
8545
9714
  // The Demo experience (studio#373): the demo preset's launch, view, files and script edit.
8546
- registerDemoRoutes(app, adapter);
9715
+ registerDemoRoutes(app, adapter, launchRun, demoDeps);
8547
9716
  // WT-W3: the storyline PUT checks the open gate through the same resolution the gate routes use.
8548
9717
  registerWalkthroughRoutes(app, adapter, { resolveOpenGate, audit });
8549
9718
  // ── Presets (DES-TEAMING-002 §8.4, seam C2) — saved phase selections in the engine's store;
@@ -8638,6 +9807,7 @@ runtime = {}) {
8638
9807
  // directly-driven route set answers 503 unless a test injects one over a fixture root.
8639
9808
  registerSkillsRoutes(app, {
8640
9809
  ...(runtime.skills !== undefined ? { runtime: runtime.skills } : {}),
9810
+ ...(runtime.skillUsage !== undefined ? { usage: runtime.skillUsage } : {}),
8641
9811
  audit,
8642
9812
  actorOf,
8643
9813
  });
@@ -8660,6 +9830,10 @@ runtime = {}) {
8660
9830
  registerMcpRoutes(app, {
8661
9831
  ...(runtime.askServer !== undefined ? { askServer: runtime.askServer } : {}),
8662
9832
  ...(runtime.mcp !== undefined ? { registry: runtime.mcp, toolLister: () => CoreAdapter.mcpToolLister() } : {}),
9833
+ // DES-CATALOG-002 §2.3: a `detect-shape` run is listed no tool (its fence is its identity).
9834
+ fence: daemonRunFence((runId) => adapter.launchedWorkflowOfRun(runId)),
9835
+ // (DES-CATALOG-002 CS10) A unit is listed no tool of a source its job did not pick (the broker refuses the call too).
9836
+ ...(runtime.runSourcePicks !== undefined ? { picks: runtime.runSourcePicks } : {}),
8663
9837
  ...(runtime.mcpBroker !== undefined ? { broker: runtime.mcpBroker } : {}),
8664
9838
  ...(runtime.dataGate !== undefined ? { gate: runtime.dataGate } : {}),
8665
9839
  ...(mcpPolicies !== undefined ? { policies: mcpPolicies } : {}),
@@ -8706,7 +9880,7 @@ runtime = {}) {
8706
9880
  ...(runtime.dataGate !== undefined ? { pm: runtime.dataGate.pm } : {}),
8707
9881
  ...(runtime.trackerAddresses !== undefined ? { addresses: runtime.trackerAddresses } : {}),
8708
9882
  runScope: async (runId) => {
8709
- const run = (await adapter.sessionsDetail()).find((v) => v.session.id === runId);
9883
+ const run = await adapter.runView(runId);
8710
9884
  if (run === undefined)
8711
9885
  return null;
8712
9886
  const projectId = projects.index.projectOf(runId) ?? (await adapter.memberProjects('crew.run', runId).catch(() => []))[0] ?? null;
@@ -9137,6 +10311,25 @@ runtime = {}) {
9137
10311
  log: (m) => app.log.warn(m),
9138
10312
  });
9139
10313
  // A3: the real `create` launcher (§4.3 steps 2-3): one document and one run per proposal identity.
10314
+ if (realRefine) {
10315
+ // A5 (DES §6): the refine launcher — the attempt on the document's binding, then the chat seam's bound refine with the
10316
+ // derived run id and the card's two helpers; crew's landing guard and the head's CAS decide what lands.
10317
+ proposalLaunchers.register('refine', new RefineLauncher({
10318
+ bindings: runtime.docBindings,
10319
+ runExists: async (runId) => (await adapter.sessions()).includes(runId),
10320
+ docsRoot: (projectId) => projectDocsRoot(adapter, projectSettings, projectId),
10321
+ launchBound: runtime.launchBoundRefine,
10322
+ ...(runtime.fenceBoundDraft !== undefined ? { fence: runtime.fenceBoundDraft } : {}),
10323
+ records: (chatId) => chatHistory?.messages(chatId) ?? chatTranscripts?.read(chatId) ?? [],
10324
+ instanceOf: (chatId) => chatHistory?.stateOf(chatId)?.instance ?? null,
10325
+ clisJsonFor: (seats) => {
10326
+ const roster = rosterWithStanding();
10327
+ const picked = seats.map((k) => roster.find((s) => s.key === k));
10328
+ return picked.some((s) => s === undefined) ? null : JSON.stringify(picked);
10329
+ },
10330
+ log: (m) => app.log.warn(m),
10331
+ }));
10332
+ }
9140
10333
  if (realCreate) {
9141
10334
  const bindings = runtime.docBindings;
9142
10335
  proposalLaunchers.register('create', new CreateLauncher({
@@ -9264,6 +10457,8 @@ runtime = {}) {
9264
10457
  // EP-C2: the ONE checks read of a document — the reviewers' recorded verdicts, read-only.
9265
10458
  registerInteractiveDocChecks(app, adapter, {
9266
10459
  reviewsDir: runtime.docReviewsDir ?? (() => join(crewStateHome(), 'interactive-edits', REVIEWS_DIRNAME)),
10460
+ ...(runtime.docLandings !== undefined ? { landings: runtime.docLandings } : {}),
10461
+ docsRoot: (projectId) => projectDocsRoot(adapter, projectSettings, projectId),
9267
10462
  log: (m) => app.log.warn(m),
9268
10463
  });
9269
10464
  // `GET /search` (api-types 0.127.0): one query over every major entity. The index is read lazily,