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
@@ -37,8 +37,15 @@ import { createHash } from 'node:crypto';
37
37
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
38
38
  import { dirname } from 'node:path';
39
39
  import { z } from '../zod.js';
40
+ import { parseCommand, resolveOption } from '../workflow-catalog/build-v2.js';
41
+ import { CATALOG_V2_CARDS } from '../workflow-catalog/catalog-data-v2.js';
42
+ import { REVIEW_CHANGE_WORKFLOW } from './review-change.js';
43
+ import { checksLabel, ownWords, factsOf, JobRefusal, mergeRevision, nounOf, optionFor, personAskedSkip, personPid, proposalKindOf, qeSkipBound, requestDigest, repoOf, resolveJob, SEAT_WORDS, seatProtections, briefOf, inputLines, SELF_SEATED, } from './chat-jobs.js';
40
44
  import { artifactExists, artifactHead, chatMount, parseArtifactRef, UNFILED_MOUNT } from './chat-context.js';
45
+ import { ATTACHMENT_MAX_FILE_BYTES } from './chat-attachments.js';
46
+ import { documentPathPlan } from '../interactive/source-packet.js';
41
47
  import { tornTailPrefix } from './chat-transcripts.js';
48
+ import { catalogDigest, detect, detectable } from '../workflow-catalog/detect.js';
42
49
  // ── the block ──────────────────────────────────────────────────────────────────────────────────────────────────────
43
50
  /** Sources a block may name. */
44
51
  export const PROPOSAL_SOURCES_MAX = 12;
@@ -58,6 +65,11 @@ export const ThemePatchSchema = z.strictObject({
58
65
  .refine((p) => Object.keys(p).length > 0, 'a theme patch changes at least one key');
59
66
  const EntryBlock = z.object({
60
67
  entry: z.string().trim().min(1).max(80),
68
+ // DES-CATALOG-002 §2.3: a job routing block names the card's option, an Investigate card's depth, and how sure the
69
+ // seat is (garden classify's catalog mode). Validated, cross-checked and banded by crew (`workflow-catalog/detect.ts`).
70
+ option: z.string().trim().max(80).nullable().optional(),
71
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
72
+ confidence: z.number().optional(),
61
73
  title: z.string().trim().max(200).optional(),
62
74
  brief: z.string().max(8000).optional(),
63
75
  url: z.string().trim().max(2048).optional(),
@@ -104,6 +116,71 @@ export function parseMakeBlock(body) {
104
116
  const r = ThemeBlock.safeParse(o);
105
117
  return r.success ? { op: 'theme', ...r.data } : null;
106
118
  }
119
+ const InputValueSchema = z.discriminatedUnion('kind', [
120
+ z.strictObject({ kind: z.literal('text'), value: z.string().max(8000) }),
121
+ z.strictObject({ kind: z.literal('url'), value: z.string().max(2048) }),
122
+ z.strictObject({ kind: z.literal('requirements'), refs: z.array(z.strictObject({ repoId: z.string().min(1).max(200), key: z.string().min(1).max(200) })).min(1).max(50) }),
123
+ z.strictObject({ kind: z.literal('documents'), tokens: z.array(z.string().min(1).max(300)).min(1).max(20) }),
124
+ z.strictObject({ kind: z.literal('sources'), ids: z.array(z.string().min(1).max(100)).max(20) }),
125
+ ]);
126
+ /** (DES-CATALOG-002 §4.6) The edits of a {@link ProposalRevision}, as a block or a request carries them. Unknown keys
127
+ * pass through to the merge, which drops each with a note (a refused edit leaves the rest standing). */
128
+ export const RevisionEditsSchema = z.looseObject({
129
+ card: z.string().trim().min(1).max(80).optional(),
130
+ option: z.string().trim().min(1).max(80).nullable().optional(),
131
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
132
+ repoRef: z.string().trim().min(1).max(200).optional(),
133
+ project: z.string().trim().max(128).nullable().optional(),
134
+ lead: z.string().trim().min(1).max(64).optional(),
135
+ addSeats: z.array(z.string().trim().min(1).max(64)).max(8).optional(),
136
+ removeSeats: z.array(z.string().trim().min(1).max(64)).max(8).optional(),
137
+ inputs: z.record(z.string().min(1).max(64), InputValueSchema).optional(),
138
+ detail: z.strictObject({ add: z.array(z.string().max(200)).max(8).optional(), remove: z.array(z.string().max(200)).max(8).optional() }).optional(),
139
+ skipQe: z.strictObject({ reason: z.string().trim().min(1).max(600) }).optional(),
140
+ restoreQe: z.literal(true).optional(),
141
+ confirmLoss: z.union([z.literal(true), z.array(z.string().min(1).max(40)).min(1).max(12)]).optional(),
142
+ });
143
+ /** A seat's typed revision block: `{"revises":"<pid>","edits":{…}}`. `null` for anything else. */
144
+ export function parseRevisionBlock(body) {
145
+ let raw;
146
+ try {
147
+ raw = JSON.parse(body);
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
153
+ return null;
154
+ const o = raw;
155
+ if (typeof o['revises'] !== 'string' || o['revises'] === '' || o['edits'] === null || typeof o['edits'] !== 'object')
156
+ return null;
157
+ const edits = RevisionEditsSchema.safeParse(o['edits']);
158
+ if (!edits.success)
159
+ return null;
160
+ return { revises: o['revises'], edits: edits.data };
161
+ }
162
+ /** (DES-CATALOG-002 §2.4) A seat's plan-edit block at a held plan: `{"planEdit":"<run id>"}`. `null` for anything else. */
163
+ export function parsePlanEditBlock(body) {
164
+ try {
165
+ const o = JSON.parse(body);
166
+ if (o === null || typeof o !== 'object' || Array.isArray(o))
167
+ return null;
168
+ const v = o['planEdit'];
169
+ return typeof v === 'string' && v.trim() !== '' && v.length <= 128 ? v.trim() : null;
170
+ }
171
+ catch {
172
+ return null;
173
+ }
174
+ }
175
+ /** (DES-CATALOG-002 §2.3) The FIRST block of a reply that parses: one request yields at most one actionable card. */
176
+ export function firstValidBlock(bodies) {
177
+ for (const b of bodies) {
178
+ const parsed = parseMakeBlock(b);
179
+ if (parsed !== null)
180
+ return parsed;
181
+ }
182
+ return null;
183
+ }
107
184
  /** The last block of a reply that parses (DES §4.1: the last valid block wins), or `null`. */
108
185
  export function lastValidBlock(bodies) {
109
186
  for (let i = bodies.length - 1; i >= 0; i -= 1) {
@@ -157,16 +234,38 @@ export function foldProposals(records) {
157
234
  }
158
235
  // The newest proposal is the chat's one open proposal: a new pid, or a re-resolution of the newest (which replaces
159
236
  // its frozen choices: the next Go uses the fresh card).
160
- for (const [other, v] of out)
161
- if (other !== pid && v.state === 'open')
237
+ for (const [other, v] of out) {
238
+ if (other !== pid && (v.state === 'open' || v.state === 'revising')) {
162
239
  v.state = 'superseded';
240
+ delete v.hold;
241
+ }
242
+ }
163
243
  out.set(pid, { proposal: r.proposal, state: 'open', turnId: r.turnId });
164
244
  }
245
+ else if (r.kind === 'proposal_revising') {
246
+ // DES-CATALOG-002 §4.6: the person's message holds an open proposal while its seat turn may revise it.
247
+ const v = out.get(r.pid);
248
+ if (v === undefined || v.state !== 'open')
249
+ continue;
250
+ v.state = 'revising';
251
+ v.hold = r.turnId;
252
+ delete v.note;
253
+ }
254
+ else if (r.kind === 'proposal_released') {
255
+ const v = out.get(r.pid);
256
+ if (v === undefined || v.state !== 'revising' || v.hold !== r.turnId)
257
+ continue;
258
+ v.state = 'open';
259
+ delete v.hold;
260
+ if (r.note !== null)
261
+ v.note = r.note;
262
+ }
165
263
  else if (r.kind === 'proposal_accepting') {
166
264
  const v = out.get(r.pid);
167
265
  if (v === undefined || v.state === 'decided')
168
266
  continue;
169
267
  v.state = 'accepting';
268
+ delete v.hold;
170
269
  v.accepting = { pid: r.pid, actor: r.actor, edits: r.edits, resolution: r.resolution, identity: r.identity };
171
270
  }
172
271
  else if (r.kind === 'proposal_decided') {
@@ -186,6 +285,8 @@ export function viewOf(f) {
186
285
  return {
187
286
  proposal: f.accepting !== undefined && (f.state === 'accepting' || (f.state === 'decided' && f.decision === 'go')) ? f.accepting.resolution : f.proposal,
188
287
  state: f.state,
288
+ ...(f.hold !== undefined ? { revisingTurn: f.hold } : {}),
289
+ ...(f.note !== undefined ? { note: f.note } : {}),
189
290
  ...(f.decision !== undefined ? { decision: f.decision } : {}),
190
291
  ...(f.result !== undefined ? { result: f.result } : {}),
191
292
  ...(f.decidedAt !== undefined ? { decidedAt: f.decidedAt } : {}),
@@ -220,6 +321,10 @@ export class LaunchOnceRegistry {
220
321
  register(kind, dispatcher) {
221
322
  this.dispatchers.set(kind, dispatcher);
222
323
  }
324
+ /** Share the registered create launcher's readers with its proposal's document plan. */
325
+ documentPacketDeps() {
326
+ return this.dispatchers.get('create')?.documentPacketDeps?.() ?? null;
327
+ }
223
328
  has(kind) {
224
329
  return this.dispatchers.has(kind);
225
330
  }
@@ -451,6 +556,24 @@ function personWords(records, turnId) {
451
556
  }
452
557
  return out.join('\n');
453
558
  }
559
+ /** (DES-CATALOG-002 §2.3) A proposal whose detection is still unsure (`ask`) holds no Start: its question is the guess's. */
560
+ export function withAskOverlay(p) {
561
+ const q = p.shape?.guess?.band === 'ask' ? p.shape.guess.question : null;
562
+ if (q === null || q === undefined)
563
+ return p;
564
+ return { ...p, blocked: q.text, question: null, suggestions: [], ...(p.sentence !== undefined ? { sentence: { ...p.sentence, ask: q.text } } : {}) };
565
+ }
566
+ /** (DES-CATALOG-002 §2.3) Whether an entry block routes a job card of the v2 catalog (its id is a detectable card's,
567
+ * or it carries the routing fields a job block has). */
568
+ export function isJobCardEntry(block) {
569
+ const card = CATALOG_V2_CARDS.find((c) => c.id === block.entry);
570
+ return (card !== undefined && detectable(card)) || block.option !== undefined || block.confidence !== undefined;
571
+ }
572
+ /** The person's own words of ONE turn (the message the seat's block answers). */
573
+ function turnWords(records, turnId) {
574
+ const r = records.find((x) => x.kind === 'user' && x.turnId === turnId && x.owner === true);
575
+ return r?.text ?? '';
576
+ }
454
577
  /**
455
578
  * Whether the person's own words name a document by its whole ref (`mount/doc`, or `doc:mount/doc`; studio's `default`
456
579
  * mount alias for an Unfiled one): a longer name or path (`mount/doc-2`, `mount/doc_x`, `mount/doc/notes`,
@@ -479,6 +602,19 @@ class EditRefusal extends Error {
479
602
  }
480
603
  /** The one block a person can lift from the card (Change something → two helpers); every other block is the record's. */
481
604
  const NEEDS_HELPER = 'Needs a second helper to check it';
605
+ /** A reshape's immutable context (the held run it replaces, its envelope, inherited reduced assurance) survives every
606
+ * re-resolution of its proposal: a revision, a catalog refresh (codex r1). */
607
+ function keepReshape(next, from) {
608
+ return {
609
+ ...next,
610
+ ...(from.reshapes !== undefined ? { reshapes: from.reshapes } : {}),
611
+ ...(from.relaunch !== undefined ? { relaunch: from.relaunch } : {}),
612
+ ...(from.reducedAssurance === true ? { reducedAssurance: true } : {}),
613
+ ...(from.heldRejected === true ? { heldRejected: true } : {}),
614
+ // The plan version the reshape was offered on stays with every descendant (codex r2 on Lane D).
615
+ ...(from.heldPlan !== undefined ? { heldPlan: from.heldPlan } : {}),
616
+ };
617
+ }
482
618
  export class ChatProposals {
483
619
  deps;
484
620
  lock = new KeyedLock();
@@ -486,6 +622,10 @@ export class ChatProposals {
486
622
  order = new KeyedLock();
487
623
  pending = new Set();
488
624
  costs = new Map();
625
+ /** Holds being written (`<chat>\0<turn>`): a reply to that turn waits for its hold first (codex r2). */
626
+ holding = new Map();
627
+ /** Turns whose reply is being settled (`<chat>\0<turn>` → replies in flight): their holds are not gone. */
628
+ settling = new Map();
489
629
  now;
490
630
  log;
491
631
  constructor(deps) {
@@ -493,8 +633,11 @@ export class ChatProposals {
493
633
  this.now = deps.now ?? Date.now;
494
634
  this.log = deps.log ?? (() => undefined);
495
635
  }
496
- /** What a seat may be told it can make now (`chat-scope.ts`'s per-message digest). */
497
- digest() {
636
+ /** What a seat may be told it can make now (`chat-scope.ts`'s per-message digest). With a chat id, how the chat routes
637
+ * new work too (DES-CATALOG-002 §2.3: job cards for a client that renders them, a command line for an older one).
638
+ * `o.appearance` (A7): whether the message carried the tab's appearance. A client that sends none cannot preview or
639
+ * apply a theme, so its seat is not told it can propose one (absent = not known here: the flag alone decides). */
640
+ digest(chatId, accepts, o = {}) {
498
641
  const f = this.deps.flags();
499
642
  const on = f.proposals;
500
643
  const entries = on
@@ -509,12 +652,14 @@ export class ChatProposals {
509
652
  })
510
653
  : [];
511
654
  // A create or demo with no catalog entry to name is not on (the seat is told nothing it could propose).
655
+ const jobs = chatId === undefined || !this.jobsOn() ? undefined : (accepts ?? this.acceptsJobs(chatId)) ? 'cards' : 'prose';
512
656
  return {
513
657
  create: on && f.create && entries.some((e) => e.kind === 'document'),
514
658
  refine: on && f.refine,
515
- theme: on && f.theme,
659
+ theme: on && f.theme && o.appearance !== false,
516
660
  demo: on && f.demo && entries.some((e) => e.kind === 'demo'),
517
661
  entries,
662
+ ...(jobs !== undefined ? { jobs } : {}),
518
663
  };
519
664
  }
520
665
  /** Resolutions still in flight (tests wait on them). */
@@ -527,11 +672,25 @@ export class ChatProposals {
527
672
  * so it runs off the fold; the record is appended only if the chat is still the same instance.
528
673
  */
529
674
  onReply(frame) {
675
+ // DES-CATALOG-002 §2.3: for a client that draws job cards, one request yields at most one actionable block: the
676
+ // FIRST valid one of any kind (a job, a revision, a plan edit, a refine, a theme), and only it is read (codex r1).
677
+ if (frame.blocks.length > 1 && this.jobsOn() && this.acceptsTurn(frame.chat, frame.turnId)) {
678
+ const first = frame.blocks.find((b) => parseMakeBlock(b) !== null || parseRevisionBlock(b) !== null || parsePlanEditBlock(b) !== null);
679
+ frame = { ...frame, blocks: first === undefined ? [] : [first] };
680
+ }
681
+ // DES-CATALOG-002 §4.6: the turn's revision of a held job proposal (or the hold's release), first.
682
+ this.onTurnReply(frame);
530
683
  if (frame.blocks.length === 0 || frame.turnId === undefined || !frame.ok)
531
684
  return;
532
685
  if (!this.deps.flags().proposals)
533
686
  return;
534
- const block = lastValidBlock(frame.blocks);
687
+ // DES-CATALOG-002 §2.3: with job routing on, one routing protocol: the FIRST valid block is the one actionable card,
688
+ // and at a job's held plan a plan edit or a change of job becomes wicked's offer instead.
689
+ // An older client (no job cards) keeps today's reading: the last valid block, no plan offers it could not draw.
690
+ const jobs = this.jobsOn() && this.acceptsTurn(frame.chat, frame.turnId);
691
+ if (jobs && this.onPlanReply(frame))
692
+ return;
693
+ const block = jobs ? firstValidBlock(frame.blocks) : lastValidBlock(frame.blocks);
535
694
  if (block === null) {
536
695
  this.log(`[proposals] chat ${frame.chat}: ${frame.blocks.length} wicked-make block(s) from ${frame.cliKey}, none valid — no card`);
537
696
  return;
@@ -563,12 +722,28 @@ export class ChatProposals {
563
722
  }
564
723
  if (this.deps.instanceOf(frame.chat) !== instance || has())
565
724
  return;
566
- const proposal = await this.resolve({ chatId: frame.chat, turnId, seat: frame.cliKey, block, records: this.deps.records(frame.chat) });
725
+ // An older client draws no job card: its statement asks for the command in prose, and its artifact entries (the
726
+ // documents and the demo) keep today's path.
727
+ const jobBlock = jobs && block.op === 'entry' && isJobCardEntry(block);
728
+ const proposal = jobBlock
729
+ ? await this.resolveDetected({ chatId: frame.chat, turnId, seat: frame.cliKey, block: block, records: this.deps.records(frame.chat) })
730
+ : await this.resolve({ chatId: frame.chat, turnId, seat: frame.cliKey, block, records: this.deps.records(frame.chat) });
567
731
  if (proposal === null)
568
732
  return;
733
+ // A job card never appears after the person has written again (codex r4): a newer message ("never mind") supersedes a
734
+ // slow reply's detection.
735
+ if (jobBlock && this.newerMessage(frame.chat, turnId)) {
736
+ this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s job card came after a newer message — dropped`);
737
+ return;
738
+ }
569
739
  // Published under the chat's lock, so it never lands between an accept's checks and its record.
570
740
  await this.lock.run(`chat\u0000${instance ?? frame.chat}`, async () => {
571
- if (!has())
741
+ // DES-CATALOG-002 §4.6 (codex r1): a chat whose job lineage is open is changed only through a revision (merged,
742
+ // loss-checked); a seat's root block never replaces it.
743
+ const jobOpen = [...foldProposals(this.deps.records(frame.chat)).values()].some((f) => f.proposal.shape !== undefined && (f.state === 'open' || f.state === 'revising'));
744
+ if (jobOpen)
745
+ this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s block would replace the open job; a change to it is a revision — dropped`);
746
+ else if (!has() && !(jobBlock && this.newerMessage(frame.chat, turnId)))
572
747
  this.write(frame.chat, { at: this.now(), turnId, kind: 'proposal', proposal }, instance);
573
748
  });
574
749
  })
@@ -576,6 +751,12 @@ export class ChatProposals {
576
751
  .finally(() => this.pending.delete(job));
577
752
  this.pending.add(job);
578
753
  }
754
+ /** Whether the person has written again since `turnId` (its reply is then an older one). */
755
+ newerMessage(chatId, turnId) {
756
+ const order = this.deps.records(chatId).filter((r) => r.kind === 'user').map((r) => r.turnId);
757
+ const mine = order.indexOf(turnId);
758
+ return mine !== -1 && mine < order.length - 1;
759
+ }
579
760
  /** Append a record and send it on `/ws` — only while the chat is still the instance the caller acted on. */
580
761
  write(chatId, record, instance) {
581
762
  if (this.deps.instanceOf(chatId) !== instance) {
@@ -637,6 +818,7 @@ export class ChatProposals {
637
818
  return this.refused(chatId, 'refine');
638
819
  const ref = parseArtifactRef(block.refine);
639
820
  let target;
821
+ let protectedList;
640
822
  let projectId = chat.projectId;
641
823
  if (ref === null) {
642
824
  blocked.push(`“${block.refine}” is not a document studio knows`);
@@ -659,10 +841,19 @@ export class ChatProposals {
659
841
  else {
660
842
  target = { ref: ref.ref, title, base: head };
661
843
  projectId = projectOfMount(ref.mount);
844
+ // A5: the person's own edits this revision keeps (Keep it is the default; only they can let one change).
845
+ const touch = [...block.touches, ...(open ? binding?.artifact?.anchors ?? [] : [])];
846
+ const kept = await this.protectedOf(ref.ref, head, touch);
847
+ if ('error' in kept)
848
+ blocked.push(kept.error);
849
+ else
850
+ protectedList = kept.entries;
662
851
  }
663
852
  }
664
853
  }
665
- const sources = await this.resolveSources(block.sources, { chatId, turnId, records, binding, turnHas, chat, words, personNamed: false });
854
+ // A5: a change works from the document and the person's words; extra sources do not reach its run yet, so the
855
+ // card says so instead of showing them as used (codex A5 r1).
856
+ const sources = (await this.resolveSources(block.sources, { chatId, turnId, records, binding, turnHas, chat, words, personNamed: false })).map((src) => src.status === 'ok' ? { ...src, status: 'struck', reason: 'a change works from the document and your words; make a new document to use this source' } : src);
666
857
  const helpers = this.helpers(chat);
667
858
  if (helpers === null)
668
859
  blocked.push(NEEDS_HELPER);
@@ -680,6 +871,7 @@ export class ChatProposals {
680
871
  filedIn: await filedIn(projectId),
681
872
  ...(target !== undefined ? { target } : {}),
682
873
  ...(block.touches.length > 0 ? { touches: block.touches } : {}),
874
+ ...(protectedList !== undefined ? { protected: protectedList } : {}),
683
875
  blocked: blocked[0] ?? null,
684
876
  };
685
877
  }
@@ -855,11 +1047,15 @@ export class ChatProposals {
855
1047
  const strike = (token, label, reason, projectId) => {
856
1048
  push({ token, label, status: 'struck', reason, ...(projectId !== undefined ? { projectId } : {}) });
857
1049
  };
858
- for (const raw of tokens.slice(0, PROPOSAL_SOURCES_MAX)) {
1050
+ for (const raw of ctx.jobDocuments === true ? tokens : tokens.slice(0, PROPOSAL_SOURCES_MAX)) {
859
1051
  const token = raw.trim();
860
1052
  if (seen.has(token))
861
1053
  continue;
862
1054
  seen.add(token);
1055
+ if (ctx.jobDocuments === true && !token.startsWith('attachment:') && !token.startsWith('doc:')) {
1056
+ strike(token, token.slice(0, 40), 'a job reads files and documents only');
1057
+ continue;
1058
+ }
863
1059
  if (token === 'chat') {
864
1060
  push({ token, label: 'this conversation', status: 'ok' });
865
1061
  continue;
@@ -890,9 +1086,9 @@ export class ChatProposals {
890
1086
  const a = this.deps.attachments(ctx.chatId).find((x) => x.id === id);
891
1087
  if (a === undefined)
892
1088
  strike(`attachment:${id}`, `attachment ${id.slice(0, 12)}`, 'not a file attached to this chat');
893
- // A3: the packet's per-file cap (512 KB): a file over it could never reach the draft.
894
- else if (typeof a.bytes === 'number' && a.bytes > 512 * 1024)
895
- strike(`attachment:${a.id}`, a.name, 'too large for a document\'s sources (over 512 KB)');
1089
+ // The document packet keeps its 512 KB cap; a job stages whole files up to the upload cap.
1090
+ else if (ctx.packetDocuments !== true && typeof a.bytes === 'number' && a.bytes > (ctx.jobDocuments === true ? ATTACHMENT_MAX_FILE_BYTES : 512 * 1024))
1091
+ strike(`attachment:${a.id}`, a.name, ctx.jobDocuments === true ? 'too large for a job document (over 10 MB)' : 'too large for a document\'s sources (over 512 KB)');
896
1092
  else
897
1093
  push({ token: `attachment:${a.id}`, label: a.name, status: 'ok' });
898
1094
  continue;
@@ -985,6 +1181,28 @@ export class ChatProposals {
985
1181
  }
986
1182
  return out;
987
1183
  }
1184
+ /** Authorise the files a job reads against this chat, its named documents and its current project scope. */
1185
+ async authorizeDocuments(chatId, tokens) {
1186
+ // Launch-time callers use the latest binding; proposal resolution uses its own turn's snapshot below.
1187
+ return this.authorizeDocumentsAt(chatId, tokens, this.deps.records(chatId), '\u0000');
1188
+ }
1189
+ async authorizeDocumentsAt(chatId, tokens, records, turnId, packetDocuments = false, cache = false) {
1190
+ tokens = tokens.slice(0, 20);
1191
+ const chat = this.deps.chat(chatId);
1192
+ if (chat === null)
1193
+ return [...new Set(tokens.map((t) => t.trim()))].map((token) => ({ token, label: token.slice(0, 40), status: 'struck', reason: 'the chat has ended' }));
1194
+ const scoped = await this.resolveSources(tokens, { chatId, turnId, records, ...bindingOf(records, turnId), chat, words: personWords(records, turnId), personNamed: false, jobDocuments: true, packetDocuments });
1195
+ if (!packetDocuments)
1196
+ return scoped;
1197
+ const deps = this.deps.registry.documentPacketDeps();
1198
+ const planned = deps === null ? [] : await documentPathPlan(scoped.filter((s) => s.status === 'ok').map((s) => s.token), chatId, deps, { cache });
1199
+ return scoped.map((s) => {
1200
+ if (s.status !== 'ok')
1201
+ return s;
1202
+ const plan = planned.find((p) => p.token === s.token);
1203
+ return plan?.status === 'ok' ? s : { ...s, status: 'struck', reason: plan?.reason ?? 'document packet readers are unavailable' };
1204
+ });
1205
+ }
988
1206
  // ── the answer ───────────────────────────────────────────────────────────────────────────────────────────────────
989
1207
  /**
990
1208
  * `POST /chats/:id/proposals/:pid` after the route's capability, person and owner checks. `instance` is the chat
@@ -1007,6 +1225,10 @@ export class ChatProposals {
1007
1225
  if (folded === undefined)
1008
1226
  return { code: 404, body: { error: `no proposal ${pid} in chat ${chatId}` } };
1009
1227
  const kind = folded.proposal.kind;
1228
+ // (api-types 0.196.0) How it runs is a job's Start's choice, and nothing else's.
1229
+ if (body.power !== undefined && (kind !== 'job' || body.decision !== 'go')) {
1230
+ return { code: 400, body: { code: 'power_not_applicable', error: kind !== 'job' ? 'only a job runs as a power run' : 'how a job runs is chosen with Start, not Not now' } };
1231
+ }
1010
1232
  const reread = () => foldProposals(this.deps.records(chatId)).get(pid) ?? folded;
1011
1233
  const ok = (f) => ({ code: 200, body: { view: viewOf(f) } });
1012
1234
  // 1. What already happened, before any state check.
@@ -1033,6 +1255,13 @@ export class ChatProposals {
1033
1255
  return this.gone(chatId);
1034
1256
  return ok(reread());
1035
1257
  }
1258
+ // DES-CATALOG-002 §4.6 (codex r1): a v2 proposal whose run never started is re-checked against the catalog first;
1259
+ // a changed one is refreshed (the person starts the refreshed proposal), never retried on a stale revision.
1260
+ if (acc.resolution.shape !== undefined) {
1261
+ const stale = await this.lock.run(`chat\u0000${instance ?? chatId}`, () => this.jobStale(chatId, folded, instance));
1262
+ if (stale !== null)
1263
+ return stale;
1264
+ }
1036
1265
  // Go again: the frozen choices and identity, re-checked. Only the helpers may change (one may have signed out
1037
1266
  // since); everything else stays as accepted.
1038
1267
  let again = acc.resolution;
@@ -1044,60 +1273,97 @@ export class ChatProposals {
1044
1273
  again = await this.applyEdits(chatId, { ...folded, proposal: acc.resolution }, body.edits);
1045
1274
  }
1046
1275
  catch (err) {
1047
- if (err instanceof EditRefusal)
1048
- return { code: 400, body: { code: 'edits_invalid', error: err.message } };
1276
+ if (err instanceof EditRefusal || err instanceof JobRefusal)
1277
+ return this.refusalOf(err);
1049
1278
  throw err;
1050
1279
  }
1051
1280
  }
1052
- return this.go(chatId, folded, again, again === acc.resolution ? acc.edits : { ...(acc.edits ?? {}), ...body.edits }, acc.identity, actor, instance);
1281
+ return this.go(chatId, folded, again, again === acc.resolution ? acc.edits : { ...(acc.edits ?? {}), ...body.edits }, acc.identity, actor, instance, body.power);
1053
1282
  }
1054
1283
  if (folded.state === 'superseded') {
1055
1284
  return { code: 409, body: { code: 'proposal_superseded', error: 'a newer proposal in this chat replaced this one', view: viewOf(folded) } };
1056
1285
  }
1286
+ // DES-CATALOG-002 §4.6: a typed correction in flight holds Start. A hold whose turn is gone is released with its note
1287
+ // first (the person sees the proposal as it stands, and presses again).
1288
+ if (folded.state === 'revising' && body.decision === 'go') {
1289
+ if (await this.reopenStale(chatId, instance)) {
1290
+ return { code: 409, body: { code: 'proposal_reopened', error: "your typed change wasn't applied: check the job and press Start again", view: viewOf(reread()) } };
1291
+ }
1292
+ return { code: 409, body: { code: 'proposal_revising', error: 'your typed change is still being applied; Start waits for it', view: viewOf(folded) } };
1293
+ }
1057
1294
  // 2. Not now: nothing else is checked.
1058
1295
  if (body.decision === 'not_now') {
1059
1296
  if (!this.decided(chatId, folded.turnId, pid, actor, 'not_now', null, folded.proposal, null, instance))
1060
1297
  return this.gone(chatId);
1061
1298
  return ok(reread());
1062
1299
  }
1300
+ // DES-CATALOG-002 §4.6: a job's Go launches only what is on screen, against the catalog it was proposed on.
1301
+ if (kind === 'job') {
1302
+ if (!this.jobsOn())
1303
+ return { code: 409, body: { code: 'operation_unavailable', error: 'this daemon does not start jobs from a chat', view: viewOf(folded) } };
1304
+ if (folded.proposal.coming !== undefined) {
1305
+ return { code: 409, body: { code: 'card_not_available', error: folded.proposal.blocked ?? `${folded.proposal.what.label} is coming later`, nearest: folded.proposal.coming.nearest, view: viewOf(folded) } };
1306
+ }
1307
+ if (folded.proposal.question !== undefined && folded.proposal.question !== null) {
1308
+ return { code: 409, body: { code: 'proposal_blocked', error: folded.proposal.question.text, view: viewOf(folded) } };
1309
+ }
1310
+ }
1311
+ // Every v2 proposal (a job, or a document's create) starts only on the catalog it was proposed on (codex r1).
1312
+ if (folded.proposal.shape !== undefined) {
1313
+ const stale = await this.lock.run(`chat\u0000${instance ?? chatId}`, () => this.jobStale(chatId, folded, instance));
1314
+ if (stale !== null)
1315
+ return stale;
1316
+ }
1317
+ if (kind === 'job') {
1318
+ // A reshape starts only through its own transition (the held plan answered Reject first; codex r3).
1319
+ // The seats the proposal names can still work, before any edit re-resolves them (codex r3).
1320
+ const can = new Set(this.deps.rosterEligible().map((x) => x.key));
1321
+ const gone = (folded.proposal.seats?.keys ?? []).filter((k) => !can.has(k));
1322
+ if (gone.length > 0 && body.edits?.seats === undefined) {
1323
+ return { code: 409, body: { code: 'helper_unavailable', error: `${gone.join(' and ')} can't work now; change who works on it`, view: viewOf(folded) } };
1324
+ }
1325
+ }
1063
1326
  // 3. A fresh Go: the edits first (the one block a person can lift is a missing second helper), then the block.
1064
1327
  let effective;
1065
1328
  try {
1066
1329
  effective = await this.applyEdits(chatId, folded, body.edits);
1067
1330
  }
1068
1331
  catch (err) {
1069
- if (err instanceof EditRefusal)
1070
- return { code: 400, body: { code: 'edits_invalid', error: err.message } };
1332
+ if (err instanceof EditRefusal || err instanceof JobRefusal)
1333
+ return this.refusalOf(err);
1071
1334
  throw err;
1072
1335
  }
1073
1336
  if (effective.blocked !== null) {
1074
1337
  return { code: 409, body: { code: 'proposal_blocked', error: effective.blocked, view: viewOf(folded) } };
1075
1338
  }
1076
- return this.go(chatId, folded, effective, body.edits ?? null, this.identityOf(effective), actor, instance);
1339
+ return this.go(chatId, folded, effective, body.edits ?? null, this.identityOf(effective), actor, instance, body.power);
1077
1340
  }
1078
1341
  /**
1079
1342
  * The state checks, then `accepting`, the launch, and `decided` — under the chat's lock and the document's, so two
1080
1343
  * proposals of one chat (or two chats changing one document) can never both pass the busy check.
1081
1344
  */
1082
- go(chatId, folded, resolution, edits, identity, actor, instance) {
1345
+ go(chatId, folded, resolution, edits, identity, actor, instance, power) {
1083
1346
  const docKey = (resolution.kind === 'refine' || (resolution.kind === 'create' && resolution.artifactRef !== undefined)) && identity.artifactRef !== null ? identity.artifactRef : null;
1084
1347
  // Keyed by the chat's instance (shared by its original id and an ended chat's archived alias), else its id.
1085
1348
  return this.lock.run(`chat\u0000${instance ?? chatId}`, () => docKey === null
1086
- ? this.goLocked(chatId, folded, resolution, edits, identity, actor, instance)
1087
- : this.lock.run(`doc\u0000${docKey}`, () => this.goLocked(chatId, folded, resolution, edits, identity, actor, instance)));
1349
+ ? this.goLocked(chatId, folded, resolution, edits, identity, actor, instance, power)
1350
+ : this.lock.run(`doc\u0000${docKey}`, () => this.goLocked(chatId, folded, resolution, edits, identity, actor, instance, power)));
1088
1351
  }
1089
- async goLocked(chatId, folded, resolution, edits, identity, actor, instance) {
1352
+ async goLocked(chatId, folded, resolution, edits, identity, actor, instance, power) {
1090
1353
  const kind = resolution.kind;
1091
1354
  const pid = resolution.pid;
1092
1355
  // Under the chat's lock: a newer proposal published while this one was being checked supersedes it.
1093
1356
  if (this.deps.instanceOf(chatId) !== instance)
1094
1357
  return this.gone(chatId);
1095
1358
  const now = foldProposals(this.deps.records(chatId)).get(pid);
1359
+ if (now?.state === 'revising') {
1360
+ return { code: 409, body: { code: 'proposal_revising', error: 'your typed change is still being applied; Start waits for it', view: viewOf(now) } };
1361
+ }
1096
1362
  if (now === undefined || now.state === 'superseded' || now.state === 'decided' || now.state !== folded.state) {
1097
1363
  return { code: 409, body: { code: now?.state === 'decided' ? 'proposal_decided' : 'proposal_superseded', error: 'this proposal changed while it was being answered; check the card again', ...(now !== undefined ? { view: viewOf(now) } : {}) } };
1098
1364
  }
1099
1365
  const flags = this.deps.flags();
1100
- if (!flags.proposals || !flags[kind] || !this.deps.registry.has(kind)) {
1366
+ if (!flags.proposals || !(kind === 'job' ? this.jobsOn() : flags[kind]) || !this.deps.registry.has(kind)) {
1101
1367
  return { code: 409, body: { code: 'operation_unavailable', error: `studio cannot start a ${kind === 'create' ? 'document' : kind} from a chat on this daemon yet`, view: viewOf(folded) } };
1102
1368
  }
1103
1369
  // The helpers can still work (one may have signed out since the card was drawn).
@@ -1108,6 +1374,21 @@ export class ChatProposals {
1108
1374
  return { code: 409, body: { code: 'helper_unavailable', error: `${lost.join(' and ')} can't work now; pick another helper`, view: viewOf(folded) } };
1109
1375
  }
1110
1376
  }
1377
+ // A job's seats can still work: Go never launches with fewer of them than the proposal names (codex r2).
1378
+ if (kind === 'job' && resolution.seats !== undefined && resolution.seats.keys.length > 0) {
1379
+ const can = new Set(this.deps.rosterEligible().map((s) => s.key));
1380
+ const lost = resolution.seats.keys.filter((k) => !can.has(k));
1381
+ if (lost.length > 0) {
1382
+ return { code: 409, body: { code: 'helper_unavailable', error: `${lost.join(' and ')} can't work now; change who works on it`, view: viewOf(folded) } };
1383
+ }
1384
+ }
1385
+ // Only the newest proposal of a lineage starts (a refreshed or revised one supersedes an interrupted one; codex r2).
1386
+ if (resolution.lineage !== undefined) {
1387
+ const newest = [...foldProposals(this.deps.records(chatId)).values()].filter((f) => f.proposal.lineage === resolution.lineage).pop();
1388
+ if (newest !== undefined && newest.proposal.pid !== pid) {
1389
+ return { code: 409, body: { code: 'proposal_superseded', error: 'a newer version of this job replaced this one', view: viewOf(newest) } };
1390
+ }
1391
+ }
1111
1392
  // Where it is filed still exists (a create or demo files into the chat's project).
1112
1393
  if ((kind === 'create' || kind === 'demo') && (await this.deps.docsRoot(resolution.filedIn.projectId ?? 'default')) === null) {
1113
1394
  return { code: 409, body: { code: 'source_gone', error: `${resolution.filedIn.label} is no longer on this daemon`, view: viewOf(folded) } };
@@ -1116,7 +1397,8 @@ export class ChatProposals {
1116
1397
  const gone = await this.firstGone(chatId, resolution);
1117
1398
  if (gone !== null)
1118
1399
  return { code: 409, body: { code: 'source_gone', error: gone, view: viewOf(folded) } };
1119
- const busy = await this.busy(chatId, identity.artifactRef, resolution);
1400
+ // A theme is no job (§15.2): applying colours never waits for a run of this chat.
1401
+ const busy = kind === 'theme' ? null : await this.busy(chatId, identity.artifactRef, resolution);
1120
1402
  if (busy !== null)
1121
1403
  return { code: 409, body: { code: busy.code, error: busy.reason, view: viewOf(folded) } };
1122
1404
  // A refine is on the head it was proposed on; else the card re-resolves (same pid, the new base). Read last, right
@@ -1133,7 +1415,7 @@ export class ChatProposals {
1133
1415
  const pids = [...foldProposals(this.deps.records(chatId)).keys()];
1134
1416
  if (pids.indexOf(pid) < pids.length - 1) {
1135
1417
  const recordedOld = folded.proposal;
1136
- const freshOld = { ...recordedOld, target: { ...(recordedOld.target ?? resolution.target), base: head } };
1418
+ const freshOld = await this.onNewHead({ ...recordedOld, target: { ...(recordedOld.target ?? resolution.target), base: head } });
1137
1419
  if (!this.write(chatId, { at: this.now(), turnId: folded.turnId, kind: 'proposal', proposal: freshOld }, instance))
1138
1420
  return this.gone(chatId);
1139
1421
  const settled = foldProposals(this.deps.records(chatId)).get(pid);
@@ -1141,7 +1423,7 @@ export class ChatProposals {
1141
1423
  }
1142
1424
  // From the proposal as crew recorded it (never the refused request's edits): the person chooses again.
1143
1425
  const recorded = folded.proposal;
1144
- const fresh = { ...recorded, target: { ...(recorded.target ?? resolution.target), base: head } };
1426
+ const fresh = await this.onNewHead({ ...recorded, target: { ...(recorded.target ?? resolution.target), base: head } });
1145
1427
  if (!this.write(chatId, { at: this.now(), turnId: folded.turnId, kind: 'proposal', proposal: fresh }, instance))
1146
1428
  return this.gone(chatId);
1147
1429
  const after = foldProposals(this.deps.records(chatId)).get(pid);
@@ -1151,33 +1433,82 @@ export class ChatProposals {
1151
1433
  };
1152
1434
  }
1153
1435
  }
1436
+ // DES-CATALOG-002 §4.6/§2.5 (codex r4): what can be checked before anything changes is checked first (a Backlog's
1437
+ // requirements, its project's members), so a reshape never answers its held plan for a launch that would refuse.
1438
+ if (kind === 'job' && this.deps.preflight !== undefined) {
1439
+ const why = await this.deps.preflight(resolution);
1440
+ if (why !== null)
1441
+ return { code: 409, body: { code: 'proposal_blocked', error: why, view: viewOf(folded) } };
1442
+ }
1443
+ // (api-types 0.196.0, operator ruling 2026-11-06) A power Start runs as one, or is refused before anything is
1444
+ // recorded: never started phased behind the person's back.
1445
+ if (power === true) {
1446
+ const why = this.deps.powerRefusal === undefined ? "this daemon can't start a chat job as a power run; press Start with Review plan on" : await this.deps.powerRefusal(resolution);
1447
+ if (why !== null)
1448
+ return { code: 409, body: { code: 'power_unavailable', error: why, view: viewOf(folded) } };
1449
+ }
1450
+ // §2.5: a reshape (or its corrected descendant) answers the held plan Reject first, in this one transition; the
1451
+ // proposal then records that it did, so a retry launches without asking again.
1452
+ if (resolution.reshapes !== undefined && resolution.heldRejected !== true) {
1453
+ if (this.deps.reshapeReject === undefined)
1454
+ return { code: 409, body: { code: 'operation_unavailable', error: 'this daemon cannot answer the held plan for a reshape', view: viewOf(folded) } };
1455
+ const refused = await this.deps.reshapeReject(resolution.reshapes, actor, pid, resolution.heldPlan);
1456
+ if (refused !== null)
1457
+ return refused;
1458
+ resolution = { ...resolution, heldRejected: true };
1459
+ if (!this.write(chatId, { at: this.now(), turnId: folded.turnId, kind: 'proposal', proposal: { ...(now.accepting?.resolution ?? now.proposal), heldRejected: true } }, instance))
1460
+ return this.gone(chatId);
1461
+ }
1154
1462
  // Recorded before anything starts.
1155
1463
  const accepting = { at: this.now(), turnId: folded.turnId, kind: 'proposal_accepting', pid, actor: actor.id, edits, resolution, identity };
1156
1464
  if (!this.write(chatId, accepting, instance))
1157
1465
  return this.gone(chatId);
1158
1466
  let result;
1159
1467
  try {
1160
- result = await this.deps.registry.launchOnce({ kind, pid, chatId, actor, identity, resolution });
1468
+ result = await this.deps.registry.launchOnce({ kind, pid, chatId, actor, identity, resolution, ...(power !== undefined ? { power } : {}) });
1161
1469
  }
1162
1470
  catch (err) {
1163
1471
  // Accepting stays recorded: the card shows "Interrupted · Go again", which resumes the same identity.
1164
1472
  const msg = err instanceof Error ? err.message : String(err);
1165
- this.deps.audit('chat.proposal.launch_failed', actor, { chatId, pid, error: msg });
1473
+ this.deps.audit('chat.proposal.launch_failed', actor, { chatId, pid, error: msg, ...(power !== undefined ? { power } : {}) });
1166
1474
  const after = foldProposals(this.deps.records(chatId)).get(pid);
1167
1475
  return { code: 502, body: { code: 'launch_failed', error: `could not start it: ${msg}. Go again resumes the same job.`, ...(after !== undefined ? { view: viewOf(after) } : {}) } };
1168
1476
  }
1169
- if (!this.decided(chatId, folded.turnId, pid, actor, 'go', result, resolution, edits, instance))
1477
+ if (!this.decided(chatId, folded.turnId, pid, actor, 'go', result, resolution, edits, instance, power))
1170
1478
  return this.gone(chatId);
1171
1479
  const after = foldProposals(this.deps.records(chatId)).get(pid) ?? folded;
1172
1480
  return { code: 200, body: { view: viewOf(after) } };
1173
1481
  }
1174
1482
  /** Record the answer (and audit exactly what was answered); `false` when the chat is no longer this instance. */
1175
- decided(chatId, turnId, pid, actor, decision, result, resolution, edits, instance) {
1483
+ decided(chatId, turnId, pid, actor, decision, result, resolution, edits, instance, power) {
1176
1484
  if (!this.write(chatId, { at: this.now(), turnId, kind: 'proposal_decided', pid, actor: actor.id, decision, result }, instance))
1177
1485
  return false;
1178
- this.deps.audit(decision === 'go' ? 'chat.proposal.accepted' : 'chat.proposal.declined', actor, { chatId, pid, kind: resolution.kind, resolution, edits, result });
1486
+ this.deps.audit(decision === 'go' ? 'chat.proposal.accepted' : 'chat.proposal.declined', actor, { chatId, pid, kind: resolution.kind, resolution, edits, result, ...(power !== undefined ? { power } : {}) });
1179
1487
  return true;
1180
1488
  }
1489
+ /** A5: the protected edits of a document at a version, or the reason a refine card is blocked. */
1490
+ async protectedOf(ref, version, touch) {
1491
+ if (this.deps.protectedEdits === undefined)
1492
+ return { entries: [] };
1493
+ const r = await this.deps.protectedEdits(ref, version, touch).catch((err) => ({ ok: false, error: err instanceof Error ? err.message : String(err) }));
1494
+ return r.ok ? { entries: r.entries } : { error: `Your own edits can't be checked on this host, so it can't be changed from chat (${r.error.slice(0, 200)})` };
1495
+ }
1496
+ /** A5: a refine at the document's current head (and that head's protected edits); unchanged when it is gone. */
1497
+ async refreshTarget(p) {
1498
+ const ref = p.target === undefined ? null : parseArtifactRef(p.target.ref);
1499
+ const root = ref === null ? null : await this.deps.docsRoot(ref.projectId);
1500
+ const head = root === null || ref === null ? null : artifactHead(root, ref.doc);
1501
+ if (head === null || p.target === undefined)
1502
+ return p;
1503
+ return this.onNewHead({ ...p, target: { ...p.target, base: head } });
1504
+ }
1505
+ /** A5: a refine card re-resolved on a newer head: its protected edits are those of the new head (Keep preselected). */
1506
+ async onNewHead(p) {
1507
+ if (p.kind !== 'refine' || p.target === undefined)
1508
+ return p;
1509
+ const kept = await this.protectedOf(p.target.ref, p.target.base, p.touches ?? []);
1510
+ return 'error' in kept ? { ...p, protected: [], blocked: kept.error } : { ...p, protected: kept.entries, blocked: p.blocked };
1511
+ }
1181
1512
  /** The identity a Go is named by (DES §4.3 step 2). */
1182
1513
  identityOf(p) {
1183
1514
  const runId = proposalRunId(p.pid);
@@ -1198,6 +1529,11 @@ export class ChatProposals {
1198
1529
  */
1199
1530
  async firstGone(chatId, p) {
1200
1531
  let runs = null;
1532
+ const documents = p.sentence?.tokens.flatMap((t) => t.kind === 'documents' ? t.documents ?? [] : []) ?? [];
1533
+ const checked = documents.length === 0 ? [] : await this.authorizeDocumentsAt(chatId, documents.filter((s) => s.status === 'ok').map((s) => s.token), this.deps.records(chatId), '\u0000', p.kind === 'create');
1534
+ const struck = checked.find((s) => s.status === 'struck');
1535
+ if (struck !== undefined)
1536
+ return `${struck.label} cannot be used (${struck.reason})`;
1201
1537
  // A3: a repository the card names must still be registered (never silently dropped from the launch).
1202
1538
  if ((p.repoRefs ?? []).length > 0 && this.deps.repoIds !== undefined) {
1203
1539
  const have = await this.deps.repoIds();
@@ -1205,7 +1541,7 @@ export class ChatProposals {
1205
1541
  if (lost !== -1)
1206
1542
  return `${p.repos[lost] ?? p.repoRefs[lost]} is no longer registered on this daemon; ask again in the chat`;
1207
1543
  }
1208
- for (const s of p.sources) {
1544
+ for (const s of [...p.sources, ...documents]) {
1209
1545
  if (s.status !== 'ok')
1210
1546
  continue;
1211
1547
  if (s.token.startsWith('run:')) {
@@ -1236,18 +1572,20 @@ export class ChatProposals {
1236
1572
  */
1237
1573
  async busy(chatId, artifactRef, p) {
1238
1574
  const runs = await this.deps.runs();
1575
+ // A reshape's held run is the one it replaces: answered Reject inside this Go, so it does not make the chat busy.
1576
+ const held = p.reshapes !== undefined && p.heldRejected !== true ? p.reshapes : null;
1239
1577
  for (const f of foldProposals(this.deps.records(chatId)).values()) {
1240
1578
  if (f.proposal.pid === p.pid)
1241
1579
  continue;
1242
1580
  // Another proposal of this chat started a job (decided go, or accepting with its run launched) still live.
1243
1581
  const runId = f.state === 'decided' && f.decision === 'go' ? f.result?.runId ?? null
1244
1582
  : f.state === 'accepting' ? f.accepting?.identity.runId ?? null : null;
1245
- if (runId !== null && (await this.deps.registry.live(f.proposal.kind, runId))) {
1583
+ if (runId !== null && runId !== held && (await this.deps.registry.live(f.proposal.kind, runId))) {
1246
1584
  return { code: 'chat_busy', reason: `This chat already has a job running (${f.proposal.what.label}). Wait, or stop that run.` };
1247
1585
  }
1248
1586
  }
1249
1587
  for (const v of runs) {
1250
- if (!isLive(v) || this.deps.chatOfRun(v.session.id) !== chatId || this.deps.isAskPath(v.session.id))
1588
+ if (!isLive(v) || v.session.id === held || this.deps.chatOfRun(v.session.id) !== chatId || this.deps.isAskPath(v.session.id))
1251
1589
  continue;
1252
1590
  return { code: 'chat_busy', reason: `This chat already has a job running (run ${v.session.id.slice(0, 8)}). Wait, or stop that run.` };
1253
1591
  }
@@ -1277,14 +1615,17 @@ export class ChatProposals {
1277
1615
  const p = f.proposal;
1278
1616
  if (edits === undefined)
1279
1617
  return p;
1618
+ if (p.kind === 'job')
1619
+ return this.applyJobEdits(chatId, f, edits);
1280
1620
  const allowed = {
1281
1621
  create: p.artifactRef !== undefined ? ['title', 'brief', 'sources', 'helpers'] : ['title', 'brief', 'sources', 'helpers', 'repos', 'project'],
1282
- refine: ['ask', 'helpers'],
1622
+ refine: ['ask', 'helpers', 'allow'],
1283
1623
  theme: ['name', 'patch'],
1284
1624
  demo: ['audience', 'show', 'helpers'],
1285
1625
  };
1626
+ const kindAllowed = allowed[p.kind];
1286
1627
  for (const k of Object.keys(edits)) {
1287
- if (!allowed[p.kind].includes(k))
1628
+ if (!kindAllowed.includes(k))
1288
1629
  throw new EditRefusal(`${k} can't be changed on a ${p.kind} proposal here yet`);
1289
1630
  }
1290
1631
  let next = { ...p };
@@ -1306,6 +1647,14 @@ export class ChatProposals {
1306
1647
  throw new EditRefusal('the ask must be 1 to 4000 characters');
1307
1648
  next = { ...next, brief: a };
1308
1649
  }
1650
+ if (edits.allow !== undefined) {
1651
+ // A5 (§6.2): only the person releases a protected edit, and only one the card shows them (an id names one exact
1652
+ // value; an edit made since the card was drawn has a new id and is kept).
1653
+ const shown = new Set((p.protected ?? []).map((e) => e.id));
1654
+ if (!Array.isArray(edits.allow) || edits.allow.length > 500 || edits.allow.some((id) => typeof id !== 'string' || !shown.has(id))) {
1655
+ throw new EditRefusal('only edits shown on this card can be let change; check the card again');
1656
+ }
1657
+ }
1309
1658
  if (edits.audience !== undefined || edits.show !== undefined) {
1310
1659
  if ((edits.audience?.length ?? 0) > 400 || (edits.show?.length ?? 0) > 2000)
1311
1660
  throw new EditRefusal('the audience or what to show is too long');
@@ -1465,6 +1814,1192 @@ export class ChatProposals {
1465
1814
  delete out.repoRefs;
1466
1815
  return out;
1467
1816
  }
1817
+ // ── DES-CATALOG-002 §4.6: job proposals ──────────────────────────────────────────────────────────────────────────
1818
+ /** (DES-CATALOG-002 §4.6) Whether a seat's job block may become a job proposal in this chat (its client draws them);
1819
+ * an older client gets the prose command line instead (Lane D's chat statement). */
1820
+ acceptsJobs(chatId) {
1821
+ return this.jobsOn() && this.deps.acceptsJobs?.(chatId) === true;
1822
+ }
1823
+ /** Holds whose release waits for the held-plan path's outcome (`<chat>\0<turn>`). */
1824
+ deferredRelease = new Set();
1825
+ /** Turns whose held-plan work is queued (set before the turn's own release runs; pi r8: a deferral only ever waits on
1826
+ * work that exists). */
1827
+ planScheduled = new Set();
1828
+ /** Per accepted turn: whether its client draws job cards, as the turn's instructions were written (codex r3). */
1829
+ turnAccepts = new Map();
1830
+ /** The route records the declaration a turn's instructions were written for, before the seat can answer it. */
1831
+ noteTurnAccepts(chatId, turnId, accepts) {
1832
+ this.turnAccepts.set(`${chatId}\u0000${turnId}`, accepts);
1833
+ while (this.turnAccepts.size > 2000)
1834
+ this.turnAccepts.delete(this.turnAccepts.keys().next().value);
1835
+ }
1836
+ /** How a reply to `turnId` is read: as its instructions were written, else the chat's declaration now. */
1837
+ acceptsTurn(chatId, turnId) {
1838
+ const noted = turnId === undefined ? undefined : this.turnAccepts.get(`${chatId}\u0000${turnId}`);
1839
+ return this.jobsOn() && (noted ?? this.deps.acceptsJobs?.(chatId) === true);
1840
+ }
1841
+ /**
1842
+ * (DES-CATALOG-002 §2.3) A seat's job routing block → a DETECTED job proposal: the block is a guess like any other,
1843
+ * validated against the catalog, cross-checked with the words layer over the person's own message of that turn and
1844
+ * banded (the chat door is capped at likely unless the words agree). An unsure reading is ONE question: the proposal
1845
+ * holds no Start, and its `shape.guess.question` lists the shapes to pick from (a pick is a person-made proposal).
1846
+ * `null` when nothing can be proposed (the chat ended, an analysis, a refusal).
1847
+ */
1848
+ async resolveDetected(input) {
1849
+ const { chatId, turnId, seat, block, records } = input;
1850
+ const chat = this.deps.chat(chatId);
1851
+ if (chat === null)
1852
+ return null;
1853
+ if (chat.analysis) {
1854
+ this.log(`[proposals] chat ${chatId} is an analysis: it proposes nothing — no card`);
1855
+ return null;
1856
+ }
1857
+ const jc = this.jobChat(chatId);
1858
+ if (jc === null)
1859
+ return null;
1860
+ const pid = `${chatId}:${turnId}`;
1861
+ // The whole message: the job's words are what the person said, never silently clipped (codex r2).
1862
+ const words = turnWords(records, turnId);
1863
+ try {
1864
+ const ctx = await this.jobContext(chatId, pid, turnId, seat, jc, { revises: null, lineage: null, notes: [] });
1865
+ const available = (card, option) => resolveOption(card, option, ctx.served)?.resolved.status === 'available';
1866
+ const d = detect({
1867
+ text: words,
1868
+ seat: { entry: block.entry, option: block.option ?? null, depth: block.depth ?? null, confidence: block.confidence, reason: block.reason },
1869
+ source: 'chat',
1870
+ catalogRev: ctx.served.rev,
1871
+ available,
1872
+ });
1873
+ const g = d.guess;
1874
+ // The repository the block names, when it is one of this chat's (else the chat's own rule picks it).
1875
+ const named = block.repos.map((want) => jc.repos.filter((r) => r.name === want || r.id === want)).find((hits) => hits.length === 1)?.[0];
1876
+ // A demo's address only from the person's own words (DES-CHAT-ARTIFACTS-001 §4.3), never the model's.
1877
+ const inputs = {};
1878
+ if (block.url !== undefined && block.url !== '' && personUrls(words).has(block.url))
1879
+ inputs['url'] = { kind: 'url', value: block.url };
1880
+ const facts = {
1881
+ card: g.card,
1882
+ option: g.option,
1883
+ depth: g.depth,
1884
+ words,
1885
+ details: [],
1886
+ repoRef: named?.id ?? null,
1887
+ projectId: jc.projectId,
1888
+ lead: null,
1889
+ seats: null,
1890
+ inputs,
1891
+ skipQe: null,
1892
+ by: 'detected',
1893
+ source: 'chat',
1894
+ guess: g,
1895
+ };
1896
+ // ONE question, never a Start, while the reading is unsure: each choice names a shape (a pick is a person-made
1897
+ // proposal).
1898
+ const proposal = withAskOverlay(await this.proposalOf(chatId, pid, facts, ctx, records));
1899
+ this.deps.audit('chat.detect', { id: `seat:${seat}`, kind: 'agent', trust: 'observer' }, {
1900
+ chatId, turnId, source: g.source, seat, card: g.card, option: g.option, band: g.band, confidence: g.confidence, dropped: d.seat?.dropped ?? null,
1901
+ });
1902
+ return proposal;
1903
+ }
1904
+ catch (err) {
1905
+ const refused = this.refusalOf(err);
1906
+ if (refused === null)
1907
+ throw err;
1908
+ this.log(`[proposals] chat ${chatId}: turn ${turnId}'s job block could not be proposed (${String(refused.body.code ?? refused.code)})`);
1909
+ return null;
1910
+ }
1911
+ }
1912
+ /** The chat's newest job that Go started: its proposal and run (`null` when none). */
1913
+ launchedJob(chatId) {
1914
+ const folded = [...foldProposals(this.deps.records(chatId)).values()];
1915
+ for (let i = folded.length - 1; i >= 0; i -= 1) {
1916
+ const f = folded[i];
1917
+ if (f.state === 'decided' && f.decision === 'go' && f.result?.runId !== undefined && f.proposal.kind === 'job' && f.proposal.shape !== undefined) {
1918
+ return { proposal: f.accepting?.resolution ?? f.proposal, runId: f.result.runId };
1919
+ }
1920
+ }
1921
+ return null;
1922
+ }
1923
+ /**
1924
+ * (DES-CATALOG-002 §2.4, §2.5) Typed at a job's held plan without Change: the seat's `planEdit` block becomes wicked's
1925
+ * send-back offer quoting the person's own words, and a revision block that changes the job's card, option or depth
1926
+ * becomes the "start it again as…" offer naming what it gives up and what it needs. An offer decides nothing: only the
1927
+ * person's press calls the gate or the reshape route, bound to the plan version. `true` when the reply was one of these
1928
+ * (handled here, whatever the outcome); `false` to read it as anything else.
1929
+ */
1930
+ onPlanReply(frame) {
1931
+ const turnId = frame.turnId;
1932
+ if (turnId === undefined || this.deps.heldPlan === undefined)
1933
+ return false;
1934
+ const job = this.launchedJob(frame.chat);
1935
+ if (job === null)
1936
+ return false;
1937
+ let planEdit = null;
1938
+ let rev = null;
1939
+ for (const b of frame.blocks) {
1940
+ planEdit ??= parsePlanEditBlock(b);
1941
+ const r = parseRevisionBlock(b);
1942
+ if (rev === null && r !== null && r.revises === job.proposal.pid)
1943
+ rev = r;
1944
+ }
1945
+ if (planEdit === null && rev === null)
1946
+ return false;
1947
+ const instance = this.deps.instanceOf(frame.chat);
1948
+ let published = false;
1949
+ const scheduledKey = `${frame.chat}\u0000${turnId}`;
1950
+ this.planScheduled.add(scheduledKey);
1951
+ const work = this.order.run(`chat\u0000${frame.chat}`, async () => {
1952
+ try {
1953
+ await this.planReplyWork(frame, turnId, job, planEdit, rev, instance, () => {
1954
+ published = true;
1955
+ });
1956
+ }
1957
+ finally {
1958
+ this.planScheduled.delete(scheduledKey);
1959
+ // A hold this turn's message took on another open proposal is released now, saying whether the change landed.
1960
+ const key = `${frame.chat}\u0000${turnId}`;
1961
+ if (this.deferredRelease.delete(key)) {
1962
+ try {
1963
+ await this.lock.run(`chat\u0000${instance ?? frame.chat}`, async () => {
1964
+ const f = [...foldProposals(this.deps.records(frame.chat)).values()].find((x) => x.state === 'revising' && x.hold === turnId);
1965
+ if (f !== undefined)
1966
+ this.write(frame.chat, { at: this.now(), turnId, kind: 'proposal_released', pid: f.proposal.pid, note: published ? null : "Your change wasn't applied: say it again." }, instance);
1967
+ });
1968
+ }
1969
+ finally {
1970
+ const n = (this.settling.get(key) ?? 1) - 1;
1971
+ if (n <= 0)
1972
+ this.settling.delete(key);
1973
+ else
1974
+ this.settling.set(key, n);
1975
+ }
1976
+ }
1977
+ }
1978
+ })
1979
+ .catch((err) => this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s plan offer failed: ${err instanceof Error ? err.message : String(err)}`))
1980
+ .finally(() => this.pending.delete(work));
1981
+ this.pending.add(work);
1982
+ return true;
1983
+ }
1984
+ async planReplyWork(frame, turnId, job, planEdit, rev, instance, onPublished) {
1985
+ {
1986
+ if (this.deps.instanceOf(frame.chat) !== instance)
1987
+ return;
1988
+ if (planEdit !== null && planEdit !== job.runId) {
1989
+ this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s plan edit names ${planEdit.slice(0, 64)}, not the chat's job ${job.runId} — dropped`);
1990
+ return;
1991
+ }
1992
+ // One offer per turn, and never from a reply older than the chat's newest message (a slow seat's late answer
1993
+ // must not replace a newer offer on the same plan version).
1994
+ const isNewest = () => {
1995
+ const rs = this.deps.records(frame.chat);
1996
+ const order = rs.filter((r) => r.kind === 'user').map((r) => r.turnId);
1997
+ const mine = order.indexOf(turnId);
1998
+ return !rs.some((r) => r.kind === 'plan_offer' && r.turnId === turnId) && (mine === -1 || mine === order.length - 1);
1999
+ };
2000
+ if (!isNewest())
2001
+ return;
2002
+ const held = await this.deps.heldPlan(job.runId);
2003
+ if (held === null || held.state !== 'held') {
2004
+ this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s plan reply, but job ${job.runId} is not waiting at its plan — no offer`);
2005
+ return;
2006
+ }
2007
+ // The person's words, waited for as the turn's own record (the route writes it after the engine took it).
2008
+ for (let i = 0; i < 25 && turnWords(this.deps.records(frame.chat), turnId) === ''; i += 1)
2009
+ await new Promise((res) => setTimeout(res, 200));
2010
+ const message = turnWords(this.deps.records(frame.chat), turnId).trim();
2011
+ const base = { id: `${frame.chat}:offer:${turnId}`, runId: job.runId, pid: job.proposal.pid, ord: held.ord, planRev: held.planRev };
2012
+ let offer = null;
2013
+ const shapeEdit = rev === null ? null : { ...(rev.edits.card !== undefined ? { card: rev.edits.card } : {}), ...(rev.edits.option !== undefined ? { option: rev.edits.option } : {}), ...(rev.edits.depth !== undefined ? { depth: rev.edits.depth } : {}) };
2014
+ if (shapeEdit !== null && Object.keys(shapeEdit).length > 0) {
2015
+ if (!held.reshapeable) {
2016
+ this.log(`[proposals] chat ${frame.chat}: turn ${turnId} changes the job, but its work plan was already accepted — no reshape offer`);
2017
+ return;
2018
+ }
2019
+ offer = await this.reshapeOffer(frame.chat, job.proposal, shapeEdit, base);
2020
+ }
2021
+ else if (planEdit !== null) {
2022
+ if (message === '')
2023
+ return;
2024
+ const leadKey = held.lead ?? job.proposal.seats?.lead ?? null;
2025
+ const lead = leadKey === null ? 'the lead' : (this.deps.rosterEligible().find((s) => s.key === leadKey)?.name ?? leadKey);
2026
+ // The person's message whole: the lead reads every word of it (only the offer's line shows a preview).
2027
+ const note = message;
2028
+ offer = {
2029
+ ...base,
2030
+ kind: 'send_back',
2031
+ text: `Send it back to ${lead} with: “${note.length > 200 ? `${note.slice(0, 199)}…` : note}”?`,
2032
+ note,
2033
+ choices: [{ label: 'Send it back', action: 'send_back' }, { label: 'No', action: 'dismiss' }],
2034
+ };
2035
+ }
2036
+ if (offer === null)
2037
+ return;
2038
+ // Published under the chat's lock, re-checked there (a newer message may have landed while it resolved).
2039
+ await this.lock.run(`chat\u0000${instance ?? frame.chat}`, async () => {
2040
+ if (this.deps.instanceOf(frame.chat) !== instance || !isNewest())
2041
+ return;
2042
+ if (this.write(frame.chat, { at: this.now(), turnId, kind: 'plan_offer', offer: offer }, instance))
2043
+ onPublished();
2044
+ });
2045
+ }
2046
+ }
2047
+ /** The "start it again as…" offer: the new shape resolved like a revision, its losses and missing inputs named. */
2048
+ async reshapeOffer(chatId, held, edits, base) {
2049
+ const chat = this.jobChat(chatId);
2050
+ if (chat === null)
2051
+ return null;
2052
+ const ctx = await this.jobContext(chatId, base.id, null, 'person', chat, { revises: held.pid, lineage: held.lineage ?? held.pid, notes: [] });
2053
+ const merged = await this.mergeJobRevision(held, edits, ctx);
2054
+ const card = CATALOG_V2_CARDS.find((c) => c.id === merged.facts.card);
2055
+ if (card === undefined || (merged.facts.card === held.shape?.card && optionFor(card, merged.facts.option) === held.shape?.option && merged.facts.depth === held.shape?.depth))
2056
+ return null;
2057
+ const option = optionFor(card, merged.facts.option);
2058
+ let needs = [];
2059
+ let command = card.command;
2060
+ try {
2061
+ const p = await this.proposalOf(chatId, base.id, { ...merged.facts, by: 'person', source: 'reshape' }, ctx, this.deps.records(chatId), false, held);
2062
+ if (p.kind !== 'job') {
2063
+ this.log(`[proposals] chat ${chatId}: a change of job to ${card.id} makes a document — no reshape offer (it is a new proposal)`);
2064
+ return null;
2065
+ }
2066
+ if (p.coming !== undefined)
2067
+ return null;
2068
+ needs = (p.needs ?? []).filter((n) => n.required && n.status === 'missing').map((n) => n.label);
2069
+ command = p.command ?? command;
2070
+ }
2071
+ catch (err) {
2072
+ if (this.refusalOf(err) === null)
2073
+ throw err;
2074
+ return null;
2075
+ }
2076
+ const noun = nounOf(card, option);
2077
+ const words = [...merged.lost.map((g) => checksLabel([g])), ...merged.lostSeats.map((k) => SEAT_WORDS[k])];
2078
+ const lostText = words.length <= 1 ? (words[0] ?? '') : `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}`;
2079
+ const text = [
2080
+ `That's a different job: start it again as ${noun}?`,
2081
+ ...(words.length > 0 ? [`It would no longer have ${lostText}.`] : []),
2082
+ ...(needs.length > 0 ? [`It needs: ${needs.join(', ')}.`] : []),
2083
+ 'Edits to this plan are not carried.',
2084
+ ].join(' ');
2085
+ return {
2086
+ ...base,
2087
+ kind: 'reshape',
2088
+ text,
2089
+ reshape: { card: card.id, option, depth: merged.facts.depth, label: nounOf(card, option), command: command ?? null, lost: merged.lost, lostSeats: merged.lostSeats, needs },
2090
+ choices: [{ label: 'Start again', action: 'reshape' }, { label: 'Keep this plan', action: 'dismiss' }],
2091
+ };
2092
+ }
2093
+ /**
2094
+ * (DES-CATALOG-002 §2.3, §4.6) The per-message job lines for this chat: how it routes new work, the chat catalog
2095
+ * digest, and what is open, held at its plan or running. `null` when job routing is off.
2096
+ */
2097
+ async jobTurn(chatId, accepts) {
2098
+ if (!this.jobsOn())
2099
+ return null;
2100
+ // The earlier turns' proposals are published first (codex r5): the ids this turn is told are the ones its hold binds.
2101
+ await this.order.run(`chat\u0000${chatId}`, async () => undefined);
2102
+ const mode = (accepts ?? this.acceptsJobs(chatId)) ? 'cards' : 'prose';
2103
+ const chat = this.jobChat(chatId);
2104
+ let status;
2105
+ try {
2106
+ const served = await this.deps.served(chat?.projectId ?? null);
2107
+ status = (card, option) => resolveOption(card, option, served)?.resolved.status ?? 'unavailable';
2108
+ }
2109
+ catch {
2110
+ status = undefined;
2111
+ }
2112
+ const context = { digest: catalogDigest('chat', status !== undefined ? { status } : {}) };
2113
+ if (mode === 'prose') {
2114
+ // The command line names the command: the chat digest's cards with their commands.
2115
+ context.digest = `${context.digest}\nCommands: ${CATALOG_V2_CARDS.filter((c) => detectable(c) && c.command !== null).map((c) => `${c.id} ${c.command}`).join('; ')}.`;
2116
+ return { mode, context };
2117
+ }
2118
+ const open = [...foldProposals(this.deps.records(chatId)).values()].find((f) => (f.state === 'open' || f.state === 'revising') && f.proposal.shape !== undefined);
2119
+ if (open !== undefined) {
2120
+ const p = open.proposal;
2121
+ context.open = { pid: p.pid, label: p.what.label, card: p.shape.card, option: p.shape.option, repo: p.repos[0] ?? null, seats: [...(p.seats?.keys ?? [])], checks: checksLabel(p.gate ?? []) };
2122
+ }
2123
+ const job = this.launchedJob(chatId);
2124
+ if (job !== null && this.deps.heldPlan !== undefined) {
2125
+ const held = await this.deps.heldPlan(job.runId).catch(() => null);
2126
+ if (held?.state === 'held') {
2127
+ const leadKey = held.lead ?? job.proposal.seats?.lead ?? null;
2128
+ context.heldPlan = { runId: job.runId, pid: job.proposal.pid, label: job.proposal.what.label, version: held.planRev, lead: leadKey === null ? null : (this.deps.rosterEligible().find((s) => s.key === leadKey)?.name ?? leadKey) };
2129
+ }
2130
+ else if (held?.state === 'running') {
2131
+ context.running = { runId: job.runId, label: job.proposal.what.label };
2132
+ }
2133
+ }
2134
+ return { mode, context };
2135
+ }
2136
+ /** The chat as a job's resolution sees it, or `null` once it has ended. */
2137
+ jobChat(chatId) {
2138
+ const c = this.deps.chat(chatId);
2139
+ return c === null ? null : { projectId: c.projectId, repos: c.repos, lead: c.lead, seats: c.seats };
2140
+ }
2141
+ async jobContext(chatId, pid, turnId, seat, chat, extra) {
2142
+ if (this.deps.served === undefined)
2143
+ throw new JobRefusal('operation_unavailable', 'this daemon cannot read its catalog for a job', 409);
2144
+ let served;
2145
+ try {
2146
+ served = await this.deps.served(chat.projectId);
2147
+ }
2148
+ catch (err) {
2149
+ throw new JobRefusal('catalog_unavailable', err instanceof Error ? err.message : String(err), 409);
2150
+ }
2151
+ const projectLabel = chat.projectId === null ? 'Not in a project · this chat' : ((await this.deps.projectName(chat.projectId)) ?? chat.projectId);
2152
+ const qeOff = (await this.deps.qeOff?.().catch(() => false)) === true;
2153
+ const powerPresets = (await this.deps.powerPresets?.(chat.projectId).catch(() => null)) ?? null;
2154
+ return { chatId, pid, turnId, seat, chat, served, roster: this.deps.rosterEligible(), projectLabel, qeOff, powerPresets, ...extra };
2155
+ }
2156
+ /** Source availability matters only to a card that shows this input. Keep a failed read a named refusal. */
2157
+ async loadJobSources(facts, ctx) {
2158
+ const card = CATALOG_V2_CARDS.find((c) => c.id === facts.card);
2159
+ const r = card === undefined ? null : resolveOption(card.id, optionFor(card, facts.option), ctx.served);
2160
+ if (!r?.resolved.inputs.some((i) => i.id === 'sources') || ctx.jobSources !== undefined)
2161
+ return;
2162
+ try {
2163
+ const sources = await this.deps.jobSources?.(ctx.chat.projectId);
2164
+ if (sources !== undefined)
2165
+ ctx.jobSources = sources;
2166
+ if (sources !== undefined && !sources.some((s) => s.web === true)) {
2167
+ // A reason only: a failed read keeps the plain fallback, never refuses the proposal.
2168
+ const why = await this.deps.webReason?.(ctx.chat.projectId).catch(() => undefined);
2169
+ if (why !== undefined)
2170
+ ctx.webReason = why;
2171
+ }
2172
+ }
2173
+ catch (err) {
2174
+ throw new JobRefusal('sources_unavailable', err instanceof Error ? err.message : String(err), 409);
2175
+ }
2176
+ }
2177
+ /** (CJ13) The last authors read per repository and words, for a short while: a revision and its rebuild, and a run
2178
+ * of swaps, read the change once (a failed read is never kept). */
2179
+ reviewAuthorsSeen = new Map();
2180
+ /**
2181
+ * (CJ13) A review of a change is never led or checked by a seat that wrote it: the launch drops the change's authors
2182
+ * from its roster, so the proposal's seats are chosen without them (the default lead included) and the passage names
2183
+ * none of them. The change is read from the words the launch reads (the brief and its input lines). A read that
2184
+ * fails, or that would leave no seat, keeps the roster: the launch then decides (it refuses an author named as
2185
+ * primary, and a roster of authors only as `no_independent_reviewer`).
2186
+ */
2187
+ async reviewRoster(facts, ctx) {
2188
+ const card = CATALOG_V2_CARDS.find((c) => c.id === facts.card);
2189
+ const r = card === undefined ? null : resolveOption(card.id, optionFor(card, facts.option), ctx.served);
2190
+ const repo = repoOf(facts, ctx.chat);
2191
+ if (r?.workflow !== REVIEW_CHANGE_WORKFLOW || repo === null || this.deps.reviewAuthors === undefined)
2192
+ return ctx;
2193
+ const words = [briefOf(facts), ...inputLines({ inputs: facts.inputs })].join('\n\n');
2194
+ const key = `${repo.id}\u0000${words}`;
2195
+ const now = Date.now();
2196
+ let authors = this.reviewAuthorsSeen.get(key);
2197
+ if (authors === undefined || now - authors.at > 30_000) {
2198
+ const read = await this.deps.reviewAuthors(repo.id, words).catch(() => null);
2199
+ if (read === null)
2200
+ return ctx;
2201
+ authors = { at: now, authors: read };
2202
+ for (const [k, v] of this.reviewAuthorsSeen)
2203
+ if (now - v.at > 30_000)
2204
+ this.reviewAuthorsSeen.delete(k);
2205
+ this.reviewAuthorsSeen.set(key, authors);
2206
+ }
2207
+ const roster = ctx.roster.filter((s) => !authors.authors.includes(s.key));
2208
+ return roster.length === 0 || roster.length === ctx.roster.length ? ctx : { ...ctx, roster };
2209
+ }
2210
+ /** Resolve the revision's shape first, then load only the choices that its input checks need. */
2211
+ async mergeJobRevision(parent, edits, ctx) {
2212
+ const shape = mergeRevision(parent, {
2213
+ ...(edits.card !== undefined ? { card: edits.card } : {}),
2214
+ ...(edits.option !== undefined ? { option: edits.option } : {}),
2215
+ }, ctx).facts;
2216
+ await this.loadJobSources(shape, ctx);
2217
+ // (CJ13) The seats are checked against the authors of the change the revision names (its words, details, inputs
2218
+ // and repository may all move the target), so it is merged once to read them.
2219
+ const reviewCtx = await this.reviewRoster(mergeRevision(parent, edits, ctx).facts, ctx);
2220
+ const merged = mergeRevision(parent, edits, reviewCtx);
2221
+ // Seats carried from a version that reviewed another change may all be the new change's authors: then they are
2222
+ // picked again from the reviewers left (the lead stays when it still may lead). Seats this revision names itself
2223
+ // are the person's choice and are never replaced (a choice of authors only is short, and its Start is refused).
2224
+ const named = edits.lead !== undefined || edits.addSeats !== undefined || edits.removeSeats !== undefined;
2225
+ const left = new Set(reviewCtx.roster.map((s) => s.key));
2226
+ const authors = new Set(ctx.roster.map((s) => s.key).filter((k) => !left.has(k)));
2227
+ const seats = merged.facts.seats;
2228
+ if (reviewCtx !== ctx && !named && seats !== null && seats.length > 0 && seats.every((k) => authors.has(k))) {
2229
+ const lead = merged.facts.lead !== null && left.has(merged.facts.lead) ? merged.facts.lead : null;
2230
+ return { ...merged, facts: { ...merged.facts, seats: null, lead } };
2231
+ }
2232
+ return merged;
2233
+ }
2234
+ /** Job proposals are on: the flag, the catalog read and the operation. */
2235
+ jobsOn() {
2236
+ return this.deps.flags().proposals && this.deps.jobs?.() === true && this.deps.served !== undefined;
2237
+ }
2238
+ /**
2239
+ * A document option picked or reached by a revision is an artifact `create` (§4.6 "Across kinds"): the existing create
2240
+ * resolution (sources, scope, helpers, its own identity), with the conversation's fields on it.
2241
+ */
2242
+ async documentProposal(chatId, pid, facts, ctx, records) {
2243
+ const card = CATALOG_V2_CARDS.find((c) => c.id === facts.card);
2244
+ const r = resolveOption(card.id, optionFor(card, facts.option), ctx.served);
2245
+ const style = r?.style ?? null;
2246
+ const seed = this.deps.catalog.find((c) => c.launch.kind === 'document' && c.launch.style === style);
2247
+ if (r === null || seed === undefined)
2248
+ throw new JobRefusal('operation_unavailable', `${card.title} can't be made from a chat on this daemon`, 409);
2249
+ if (!this.deps.flags().create)
2250
+ throw new JobRefusal('operation_unavailable', 'studio cannot start a document from a chat on this daemon yet', 409);
2251
+ const turnId = ctx.turnId ?? `person:${pid.slice(pid.lastIndexOf(':') + 1)}`;
2252
+ // Crew's kind line goes first, as `withBriefLines` puts it on a run: a long request is cut at its end, never the line.
2253
+ const words = [r.resolved.brief ?? '', briefOf(facts)].filter((x) => x !== '').join('\n\n');
2254
+ const made = await this.resolve({ chatId, turnId, seat: ctx.seat, block: { op: 'entry', entry: seed.id, brief: words, sources: ['chat'], repos: facts.repoRef !== null ? [facts.repoRef] : [] }, records });
2255
+ if (made === null)
2256
+ throw new JobRefusal('operation_unavailable', 'studio cannot start a document from a chat on this daemon yet', 409);
2257
+ const shape = { card: card.id, option: r.option?.id ?? null, depth: null, by: facts.by, source: facts.source, ...(facts.guess !== undefined ? { guess: facts.guess } : {}) };
2258
+ const kindTok = { id: 'kind', kind: (card.variant !== undefined ? 'option' : 'card'), label: nounOf(card, shape.option), swap: null };
2259
+ const checksTok = { id: 'checks', kind: 'checks', label: checksLabel(r.resolved.gate), swap: null };
2260
+ const documentsInput = r.resolved.inputs.find((i) => i.id === 'documents');
2261
+ const documents = ctx.documents ?? [];
2262
+ const ok = documents.filter((s) => s.status === 'ok');
2263
+ const label = `${ok.length} document${ok.length === 1 ? '' : 's'}`;
2264
+ const needs = documentsInput === undefined ? [] : [{ ...documentsInput, status: ok.length > 0 ? 'met' : 'missing', value: label }];
2265
+ const why = documents.find((s) => s.status === 'struck')?.reason;
2266
+ const question = documentsInput?.required === true && ok.length === 0
2267
+ ? { kind: 'missing', text: `Which documents?${why !== undefined ? ` ${why}` : ''}`, choices: [] }
2268
+ : null;
2269
+ const documentsTok = documentsInput === undefined ? [] : [{ id: 'documents', kind: 'documents', label, swap: null, documents }];
2270
+ // A document option this engine cannot draft (Respond and Rework without `interactive-draft-sourced`) is said, with
2271
+ // why, and offers no Start (CS8).
2272
+ const offline = r.resolved.status !== 'available' ? (r.resolved.statusNote ?? `${card.title} can't start on this daemon`) : null;
2273
+ return {
2274
+ ...made,
2275
+ // These tokens passed the document packet's plan, including PDF text and the shared budget. Keep that
2276
+ // decision rather than applying the legacy source count cap or CS4's larger job limits.
2277
+ ...(documentsInput !== undefined ? { sources: [...made.sources, ...ok], inputs: { ...facts.inputs }, needs } : {}),
2278
+ blocked: made.blocked ?? offline ?? question?.text ?? null,
2279
+ pid,
2280
+ turnId: ctx.turnId,
2281
+ // `what.entry` stays the document entry the create launcher reads its style from (codex r1); the card is in `shape`.
2282
+ shape,
2283
+ catalogRev: ctx.served.rev,
2284
+ resolution: r.resolved.resolution,
2285
+ launch: 'document',
2286
+ command: r.option?.command ?? card.command,
2287
+ gate: [...r.resolved.gate],
2288
+ words: facts.words,
2289
+ details: [...facts.details],
2290
+ sentence: { text: `I'll make {kind} from this conversation${documentsInput !== undefined ? ', reading {documents}' : ''}, filed in ${made.filedIn.label}, checked by {checks}.`, tokens: [kindTok, ...documentsTok, checksTok], notes: [...ctx.notes], ask: offline !== null ? null : question?.text ?? (made.blocked === null ? 'Start?' : null) },
2291
+ suggestions: [],
2292
+ question,
2293
+ revises: ctx.revises,
2294
+ lineage: ctx.lineage ?? pid,
2295
+ ...(ctx.answers !== undefined ? { answers: ctx.answers } : {}),
2296
+ ...(ctx.request !== undefined ? { request: ctx.request } : {}),
2297
+ };
2298
+ }
2299
+ /** Resolve facts to their proposal. `previous` marks a rebuild; null is a held job without a stored parent. */
2300
+ async proposalOf(chatId, pid, facts, ctx, records, allowHidden = false, previous) {
2301
+ const card = CATALOG_V2_CARDS.find((c) => c.id === facts.card);
2302
+ const r = card === undefined ? null : resolveOption(card.id, optionFor(card, facts.option), ctx.served);
2303
+ await this.loadJobSources(facts, ctx);
2304
+ ctx = await this.reviewRoster(facts, ctx);
2305
+ if (r?.resolved.inputs.some((i) => i.id === 'documents')) {
2306
+ if (facts.inputs['documents'] === undefined) {
2307
+ const { binding } = bindingOf(records, ctx.turnId ?? '\u0000');
2308
+ // A rebuild never discovers new files. Only a fresh card, or a switch from a card without documents, fills.
2309
+ const fill = previous === undefined || (previous !== null && previous.shape?.card !== facts.card && !previous.needs?.some((n) => n.id === 'documents'));
2310
+ const tokens = fill ? [...new Set([
2311
+ ...this.deps.attachments(chatId).map((a) => `attachment:${a.id}`),
2312
+ ...(binding?.named.docs ?? []).map((ref) => `doc:${ref}`),
2313
+ ...(binding?.artifact !== undefined ? [`doc:${binding.artifact.ref}`] : []),
2314
+ ])].slice(0, 20) : [];
2315
+ // Persist even an empty fill, so factsOf cannot pick up files the person never saw.
2316
+ facts = { ...facts, inputs: { ...facts.inputs, documents: { kind: 'documents', tokens } } };
2317
+ }
2318
+ const input = facts.inputs['documents'];
2319
+ ctx = { ...ctx, documents: await this.authorizeDocumentsAt(chatId, input?.kind === 'documents' ? input.tokens : [], records, ctx.turnId ?? '\u0000', r !== null && proposalKindOf(r) === 'create', true) };
2320
+ }
2321
+ // An unsure reading holds no Start wherever the proposal is rebuilt (a Go's edits, a refresh; codex r4).
2322
+ if (r !== null && proposalKindOf(r) === 'create')
2323
+ return withAskOverlay(await this.documentProposal(chatId, pid, facts, ctx, records));
2324
+ return withAskOverlay(resolveJob(facts, ctx, { allowHidden }));
2325
+ }
2326
+ refusalOf(err) {
2327
+ if (err instanceof JobRefusal)
2328
+ return { code: err.status, body: { code: err.code, error: err.message } };
2329
+ if (err instanceof EditRefusal)
2330
+ return { code: 400, body: { code: 'edits_invalid', error: err.message } };
2331
+ return null;
2332
+ }
2333
+ /** Explicit file edits refuse any struck token; a rebuild refuses a downgrade of a file the person saw as ok. */
2334
+ refuseStruckDocuments(p, previous) {
2335
+ const wasOk = previous?.sentence?.tokens.flatMap((t) => t.kind === 'documents' ? t.documents ?? [] : []).filter((s) => s.status === 'ok').map((s) => s.token) ?? [];
2336
+ const struck = p.sentence?.tokens.flatMap((t) => t.kind === 'documents' ? t.documents ?? [] : []).find((s) => s.status === 'struck' && (previous === undefined || wasOk.includes(s.token)));
2337
+ if (struck === undefined)
2338
+ return;
2339
+ const why = `${struck.label} cannot be used (${struck.reason})`;
2340
+ if (previous !== undefined)
2341
+ throw new JobRefusal('source_gone', why, 409);
2342
+ throw new EditRefusal(why);
2343
+ }
2344
+ /**
2345
+ * `POST /chats/:id/proposals` after the route's capability, person and owner checks: a person-made proposal (a `/`
2346
+ * pick, a typed command, a question's choice) or a revision (a swap, a suggestion, a question's choice). No seat turn
2347
+ * runs. A repeated `requestId` answers the same proposal; another body under it is refused.
2348
+ */
2349
+ propose(chatId, body, actor, instance) {
2350
+ return this.lock.run(`chat\u0000${instance ?? chatId}`, async () => {
2351
+ if (this.deps.instanceOf(chatId) !== instance)
2352
+ return this.gone(chatId);
2353
+ if (!this.jobsOn())
2354
+ return { code: 409, body: { code: 'operation_unavailable', error: 'this daemon does not take job proposals from a chat' } };
2355
+ const pid = personPid(chatId, actor.id, body.requestId);
2356
+ const digest = requestDigest(body);
2357
+ const records = this.deps.records(chatId);
2358
+ const held = foldProposals(records).get(pid);
2359
+ if (held !== undefined) {
2360
+ if (held.proposal.request?.digest === digest)
2361
+ return { code: 201, body: { view: viewOf(held) } };
2362
+ return { code: 409, body: { code: 'request_reused', error: 'this requestId already made a different proposal', view: viewOf(held) } };
2363
+ }
2364
+ try {
2365
+ if ('revises' in body) {
2366
+ return await this.reviseLocked(chatId, { revises: body.revises, edits: body.edits }, { person: actor, source: body.source, pid, request: { id: body.requestId, digest }, turnId: null, message: null }, instance);
2367
+ }
2368
+ const chat = this.jobChat(chatId);
2369
+ if (chat === null)
2370
+ return { code: 409, body: { code: 'chat_gone', error: `chat ${chatId} has ended; start a new one` } };
2371
+ // A command names its card (and maybe its option); an alias is the only way to a hidden card.
2372
+ let card = body.card;
2373
+ let option = body.option;
2374
+ let allowHidden = false;
2375
+ if (card.startsWith('/')) {
2376
+ const hit = parseCommand(card);
2377
+ if (hit === null)
2378
+ return { code: 400, body: { code: 'card_unknown', error: `no job has the command ${card.slice(0, 80)}` } };
2379
+ allowHidden = CATALOG_V2_CARDS.find((c) => c.id === hit.card)?.aliases.some((a) => a.command.toLowerCase() === card.trim().split(/\s+/u)[0].toLowerCase()) === true;
2380
+ card = hit.card;
2381
+ if (option === undefined && hit.option !== undefined)
2382
+ option = hit.option;
2383
+ }
2384
+ const facts = {
2385
+ card,
2386
+ option,
2387
+ depth: body.depth ?? null,
2388
+ words: (body.words ?? '').slice(0, 8000),
2389
+ details: [],
2390
+ repoRef: null,
2391
+ projectId: chat.projectId,
2392
+ lead: null,
2393
+ seats: null,
2394
+ inputs: {},
2395
+ skipQe: null,
2396
+ by: 'person',
2397
+ source: body.source,
2398
+ };
2399
+ const ctx = await this.jobContext(chatId, pid, null, 'person', chat, { revises: null, lineage: null, notes: [], request: { id: body.requestId, digest } });
2400
+ const proposal = await this.proposalOf(chatId, pid, facts, ctx, records, allowHidden);
2401
+ if (!this.write(chatId, { at: this.now(), turnId: `person:${pid.slice(pid.lastIndexOf(':') + 1)}`, kind: 'proposal', proposal }, instance))
2402
+ return this.gone(chatId);
2403
+ const view = foldProposals(this.deps.records(chatId)).get(pid);
2404
+ return { code: 201, body: { view: view !== undefined ? viewOf(view) : { proposal, state: 'open' } } };
2405
+ }
2406
+ catch (err) {
2407
+ const refused = this.refusalOf(err);
2408
+ if (refused !== null)
2409
+ return refused;
2410
+ throw err;
2411
+ }
2412
+ });
2413
+ }
2414
+ /**
2415
+ * A revision of the lineage's open proposal (§4.6), under the chat's lock: the stale-parent check, the merge, the
2416
+ * lost-check question, the re-resolution, and the write that supersedes the parent. `src.person` is the person's
2417
+ * route (only it takes `confirmLoss`); otherwise a seat's block bound to the person's message `src.turnId`.
2418
+ */
2419
+ async reviseLocked(chatId, rev, src, instance) {
2420
+ const records = this.deps.records(chatId);
2421
+ const folded = foldProposals(records);
2422
+ const parent = folded.get(rev.revises);
2423
+ if (parent === undefined)
2424
+ return { code: 404, body: { error: `no proposal ${rev.revises} in chat ${chatId}` } };
2425
+ // The parent must be the lineage's open proposal: superseded, accepted, decided, or held by another turn is stale.
2426
+ const ownHold = parent.state === 'revising' && src.turnId !== null && parent.hold === src.turnId;
2427
+ if (!(parent.state === 'open' || ownHold)) {
2428
+ return { code: 409, body: { code: parent.state === 'revising' ? 'proposal_revising' : 'proposal_stale', error: parent.state === 'revising' ? 'your typed change is still being applied; wait for it' : 'this proposal is no longer the open one in this chat', view: viewOf(parent) } };
2429
+ }
2430
+ if (parent.proposal.shape === undefined)
2431
+ return { code: 400, body: { code: 'edits_invalid', error: 'only a job proposal is revised this way' } };
2432
+ const chat = this.jobChat(chatId);
2433
+ if (chat === null)
2434
+ return { code: 409, body: { code: 'chat_gone', error: `chat ${chatId} has ended; start a new one` } };
2435
+ const fromPerson = src.person !== null;
2436
+ // Only the person's own press can give up a check.
2437
+ const edits = { ...rev.edits };
2438
+ // What the press confirms (codex r4): `true` on a lost-check question covers exactly what that question names; a
2439
+ // swap or suggestion carries the ids its own label named. Anything else covers nothing.
2440
+ const confirmIds = !fromPerson || edits.confirmLoss === undefined
2441
+ ? null
2442
+ : Array.isArray(edits.confirmLoss)
2443
+ ? new Set(edits.confirmLoss)
2444
+ : parent.proposal.question?.kind === 'lost_check'
2445
+ ? new Set([...(parent.proposal.question.lost ?? []), ...(parent.proposal.question.lostSeats ?? [])])
2446
+ : new Set();
2447
+ const confirmed = confirmIds !== null;
2448
+ delete edits.confirmLoss;
2449
+ const ctx0 = await this.jobContext(chatId, src.pid, src.turnId, fromPerson ? 'person' : (parent.proposal.seat ?? 'seat'), chat, {
2450
+ revises: parent.proposal.pid,
2451
+ lineage: parent.proposal.lineage ?? parent.proposal.pid,
2452
+ notes: [],
2453
+ ...(src.turnId !== null ? { answers: src.turnId } : {}),
2454
+ ...(src.request !== undefined ? { request: src.request } : {}),
2455
+ });
2456
+ // A QE skip is never applied from a seat's block (§4.6 step 7, §9.2 (ac)): it becomes wicked's question, with the
2457
+ // person's own reason when their message (the one this turn answers) gives one unquoted, else asking for it. A skip
2458
+ // the person never asked for in their own words changes nothing. On the person's route, only the press applies it.
2459
+ let qe = null;
2460
+ const extraNotes = [];
2461
+ if (edits.skipQe !== undefined && !confirmed) {
2462
+ const reason = edits.skipQe.reason;
2463
+ delete edits.skipQe;
2464
+ if (parent.proposal.gate?.includes('qe-acceptance') !== true)
2465
+ extraNotes.push('Not changed: this job has no QE acceptance to skip.');
2466
+ else if (fromPerson || qeSkipBound(reason, src.message))
2467
+ qe = { reason };
2468
+ else if (personAskedSkip(src.message))
2469
+ qe = { reason: null };
2470
+ else
2471
+ extraNotes.push('Not changed: QE acceptance stays. Skipping it needs your own reason, in your own words.');
2472
+ }
2473
+ // What a seat's block carries into the brief must be the person's own (codex r3): a detail added or removed, and a
2474
+ // text input, appear in their message (outside quotes and reported speech); anything else is refused with a note.
2475
+ if (!fromPerson) {
2476
+ const said = ownWords(src.message ?? '').toLowerCase();
2477
+ const fromThem = (t) => t.trim() !== '' && said.includes(t.trim().toLowerCase());
2478
+ if (edits.detail !== undefined) {
2479
+ const add = (edits.detail.add ?? []).filter((d) => fromThem(d));
2480
+ // A removal needs the person to ask for one, and a carried fact that names a check is never dropped from a
2481
+ // seat's block (codex r4: "keep a separate judge" mentions the detail, it does not remove it).
2482
+ // The removal verb belongs to THIS detail: within a few words before it (pi r5).
2483
+ const asksRemoval = (d) => {
2484
+ const at = said.indexOf(d.trim().toLowerCase());
2485
+ if (at === -1)
2486
+ return false;
2487
+ const before = said.slice(Math.max(0, at - 60), at);
2488
+ // The removal verb in the same clause, right before the detail, and not itself negated ("do not remove …").
2489
+ const m = /\b(?:remove|drop|forget|scrap|undo|take\s+out|no\s+longer|don'?t\s+need)\b(?:\s+[^\s.;,]+){0,4}\s*$/iu.exec(before);
2490
+ // Not negated, and no keeping or new clause between the verb and the detail ("remove X and keep <detail>").
2491
+ return m !== null && !/\b(?:don'?t|do\s+not|never|not)\s+$/iu.test(before.slice(0, m.index)) && !/\b(?:keep|keeping|retain|retaining|and|but|then|while|whilst)\b/iu.test(before.slice(m.index).replace(/^\S+/u, ''));
2492
+ };
2493
+ const namesCheck = (d) => /\b(?:reviews?|reviewers?|judges?|parity|qe|acceptance|tests?|checks?|cited\s+findings|floor|gates?)\b/iu.test(d);
2494
+ const remove = (edits.detail.remove ?? []).filter((d) => fromThem(d) && asksRemoval(d) && !namesCheck(d));
2495
+ for (const d of edits.detail.add ?? [])
2496
+ if (!fromThem(d))
2497
+ extraNotes.push(`Not changed: “${d.slice(0, 60)}” isn't in what you said`);
2498
+ for (const d of edits.detail.remove ?? [])
2499
+ if (!remove.includes(d))
2500
+ extraNotes.push(`Not changed: “${d.slice(0, 60)}” stays (say to remove it${namesCheck(d) ? '; it names a check, so it stays' : ''})`);
2501
+ edits.detail = { ...(add.length > 0 ? { add } : {}), ...(remove.length > 0 ? { remove } : {}) };
2502
+ }
2503
+ if (edits.inputs !== undefined) {
2504
+ const kept = {};
2505
+ for (const [k, v] of Object.entries(edits.inputs)) {
2506
+ if (v.kind === 'requirements' || v.kind === 'documents' || v.kind === 'sources' || fromThem(v.value))
2507
+ kept[k] = v;
2508
+ else
2509
+ extraNotes.push(`Not changed: ${k.slice(0, 40)} must be in your own words`);
2510
+ }
2511
+ edits.inputs = kept;
2512
+ }
2513
+ }
2514
+ // The job's own words are the person's (§4.6 rule 6): a seat's block may fill a missing intent, never replace it
2515
+ // (codex r1 on Lane D: the brief the lead reads is never the seat's rewrite).
2516
+ if (!fromPerson && edits.inputs !== undefined && Object.hasOwn(edits.inputs, 'intent') && (parent.proposal.words ?? '').trim() !== '') {
2517
+ const { intent: _dropped, ...rest } = edits.inputs;
2518
+ void _dropped;
2519
+ edits.inputs = rest;
2520
+ extraNotes.push("Not changed: the job's own words are yours; say them again to change them");
2521
+ }
2522
+ const merged = await this.mergeJobRevision(parent.proposal, edits, ctx0);
2523
+ merged.notes.push(...extraNotes);
2524
+ const ctx = { ...ctx0, notes: merged.notes };
2525
+ // A hidden card stays reachable while the revision keeps it (it was reached by its alias once).
2526
+ const allowHidden = merged.facts.card === parent.proposal.shape.card;
2527
+ // The candidate as it would be written, settings included (a daemon's QE setting can drop QE from it): its checks
2528
+ // are compared with the parent's too, so nothing is lost unseen (codex r2).
2529
+ let candidate = null;
2530
+ let candidateErr = null;
2531
+ // A revision is not the detection any more: a changed card or option drops the guess it no longer describes (codex
2532
+ // r2), and an unsure guess is cleared only by a revision that names the shape (a card or an option: the seat's
2533
+ // reading of the person's clarification, the same card included); a repository or a detail leaves the question
2534
+ // standing (codex r3).
2535
+ const g = merged.facts.guess;
2536
+ const seed = CATALOG_V2_CARDS.find((c) => c.id === merged.facts.card);
2537
+ // Named AND taken: a refused card or option leaves the question standing (codex r4).
2538
+ const namesShape = seed !== undefined
2539
+ && (rev.edits.card !== undefined || rev.edits.option !== undefined)
2540
+ && (rev.edits.card === undefined || rev.edits.card === merged.facts.card)
2541
+ && (rev.edits.option === undefined || optionFor(seed, rev.edits.option ?? undefined) === optionFor(seed, merged.facts.option ?? undefined));
2542
+ const moved = g !== undefined && (seed === undefined || g.card !== merged.facts.card || optionFor(seed, g.option) !== optionFor(seed, merged.facts.option));
2543
+ const stale = g !== undefined && (moved || (g.band === 'ask' && namesShape));
2544
+ try {
2545
+ const { guess: _g, ...unguessed } = merged.facts;
2546
+ void _g;
2547
+ const factsNow = stale ? unguessed : merged.facts;
2548
+ candidate = withAskOverlay(keepReshape(await this.proposalOf(chatId, src.pid, { ...factsNow, by: fromPerson ? 'person' : factsNow.by, source: src.source }, ctx, records, allowHidden, parent.proposal), parent.proposal));
2549
+ }
2550
+ catch (err) {
2551
+ candidateErr = err;
2552
+ }
2553
+ // Losses only the fully resolved candidate shows (a daemon setting since): never covered by an earlier press.
2554
+ const extra = [];
2555
+ for (const g of parent.proposal.gate ?? [])
2556
+ if (candidate !== null && !(candidate.gate ?? []).includes(g) && !merged.lost.includes(g) && !(g === 'qe-acceptance' && merged.facts.skipQe !== null))
2557
+ extra.push(g);
2558
+ merged.lost.push(...extra);
2559
+ const loses = merged.lost.length > 0 || merged.lostSeats.length > 0;
2560
+ // A press confirms exactly what was disclosed to it (codex r3): the question's named losses, or a swap's own
2561
+ // (catalog-derived, named in its label). A loss beyond that asks again.
2562
+ const uncovered = confirmIds === null ? [...merged.lost, ...merged.lostSeats] : [...merged.lost, ...merged.lostSeats].filter((k) => !confirmIds.has(k));
2563
+ const covered = confirmed && uncovered.length === 0;
2564
+ // A candidate the daemon cannot make is said at once, never behind a question it could not honour (codex r4, r5):
2565
+ // a refusal, or a candidate blocked for a reason no answer fixes (unavailable, coming).
2566
+ if (candidate === null && candidateErr !== null && loses && !covered) {
2567
+ const refused = this.refusalOf(candidateErr);
2568
+ if (refused !== null)
2569
+ return refused;
2570
+ }
2571
+ // Unmakeable = coming, or blocked for a reason other than the one question an answer fixes (codex r6).
2572
+ const unmakeable = candidate !== null && (candidate.coming !== undefined || (candidate.blocked !== null && candidate.blocked !== (candidate.question?.text ?? null)));
2573
+ if (candidate !== null && loses && !covered && unmakeable) {
2574
+ return { code: 409, body: { code: 'card_not_available', error: candidate.blocked, view: viewOf(parent) } };
2575
+ }
2576
+ if (qe !== null || (loses && !covered)) {
2577
+ const base = keepReshape(await this.proposalOf(chatId, src.pid, factsOf(parent.proposal), ctx, records, true, parent.proposal), parent.proposal);
2578
+ const newCard = CATALOG_V2_CARDS.find((c) => c.id === merged.facts.card);
2579
+ const oldCard = CATALOG_V2_CARDS.find((c) => c.id === parent.proposal.shape.card);
2580
+ const newNoun = nounOf(newCard, optionFor(newCard, merged.facts.option));
2581
+ const oldNoun = nounOf(oldCard, parent.proposal.shape.option);
2582
+ // The choice carries exactly the edits crew kept (codex r1: never a refused seat skip), plus the press.
2583
+ const lossEdit = { ...edits, confirmLoss: true };
2584
+ let question;
2585
+ if (qe !== null && !loses) {
2586
+ question = qe.reason === null
2587
+ ? { kind: 'lost_check', text: 'Skip QE acceptance? Say why, and the job will be labelled with your reason.', choices: [{ label: 'Keep QE', edit: {} }], lost: ['qe-acceptance'], input: { kind: 'text', label: 'Your reason', edit: 'skipQe.reason' } }
2588
+ : { kind: 'lost_check', text: `Skip QE acceptance? The job will be labelled with your reason: “${qe.reason}”.`, choices: [{ label: 'Skip it', edit: { ...lossEdit, skipQe: { reason: qe.reason } } }, { label: 'Keep QE', edit: {} }], lost: ['qe-acceptance'] };
2589
+ }
2590
+ else {
2591
+ const lost = qe?.reason !== null && qe !== null ? [...new Set(['qe-acceptance', ...merged.lost])] : merged.lost;
2592
+ const choice = qe !== null && qe.reason !== null ? { ...lossEdit, skipQe: { reason: qe.reason } } : lossEdit;
2593
+ const words = [...lost.map((g) => checksLabel([g])), ...merged.lostSeats.map((k) => SEAT_WORDS[k])];
2594
+ const lostText = words.length <= 1 ? (words[0] ?? '') : `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}`;
2595
+ question = {
2596
+ kind: 'lost_check',
2597
+ text: newNoun === oldNoun ? `That would no longer have ${lostText}. Change it anyway?` : `That's ${newNoun}, not ${oldNoun}: it would no longer have ${lostText}. Make it ${newNoun}?`,
2598
+ choices: [{ label: newNoun === oldNoun ? 'Change it' : `Make it ${newNoun}`, edit: choice }, { label: `Keep ${oldNoun}`, edit: {} }],
2599
+ lost,
2600
+ ...(merged.lostSeats.length > 0 ? { lostSeats: merged.lostSeats } : {}),
2601
+ };
2602
+ }
2603
+ const asked = {
2604
+ ...base,
2605
+ // The baseline stays what the person saw (codex r3): a later unrelated revision compares against it.
2606
+ gate: [...new Set([...(parent.proposal.gate ?? []), ...(base.gate ?? [])])],
2607
+ seatRules: [...new Set([...(parent.proposal.seatRules ?? []), ...(base.seatRules ?? [])])],
2608
+ question,
2609
+ suggestions: [],
2610
+ blocked: question.text,
2611
+ ...(base.sentence !== undefined ? { sentence: { ...base.sentence, ask: question.text } } : {}),
2612
+ };
2613
+ if (!this.write(chatId, { at: this.now(), turnId: src.turnId ?? `person:${src.pid.slice(src.pid.lastIndexOf(':') + 1)}`, kind: 'proposal', proposal: asked }, instance))
2614
+ return this.gone(chatId);
2615
+ const view = foldProposals(this.deps.records(chatId)).get(src.pid);
2616
+ return { code: 201, body: { view: view !== undefined ? viewOf(view) : { proposal: asked, state: 'open' } } };
2617
+ }
2618
+ // A seat's revision that changes nothing and says nothing re-proposes nothing ("skip parity": the seat says why).
2619
+ if (!fromPerson && merged.unchanged && merged.notes.length === 0 && !stale)
2620
+ return { code: 200, body: { view: viewOf(parent) } };
2621
+ if (candidate === null)
2622
+ throw candidateErr;
2623
+ const proposal = candidate;
2624
+ if (!this.write(chatId, { at: this.now(), turnId: src.turnId ?? `person:${src.pid.slice(src.pid.lastIndexOf(':') + 1)}`, kind: 'proposal', proposal }, instance))
2625
+ return this.gone(chatId);
2626
+ const view = foldProposals(this.deps.records(chatId)).get(src.pid);
2627
+ return { code: 201, body: { view: view !== undefined ? viewOf(view) : { proposal, state: 'open' } } };
2628
+ }
2629
+ /**
2630
+ * The person's message `turnId` was written (`POST /chats/:id/messages`): the chat's open job proposal is held as
2631
+ * `revising` until that turn settles, under the lock Go takes, so a Go is either before the message (and launches
2632
+ * what was on screen) or after it (and waits).
2633
+ */
2634
+ holdForMessage(chatId, turnId) {
2635
+ const instance = this.deps.instanceOf(chatId);
2636
+ const key = `${chatId}\u0000${turnId}`;
2637
+ const done = this.lock.run(`chat\u0000${instance ?? chatId}`, async () => {
2638
+ if (!this.jobsOn() || this.deps.instanceOf(chatId) !== instance)
2639
+ return;
2640
+ for (const f of foldProposals(this.deps.records(chatId)).values()) {
2641
+ if (f.state !== 'open' || f.proposal.shape === undefined)
2642
+ continue;
2643
+ this.write(chatId, { at: this.now(), turnId, kind: 'proposal_revising', pid: f.proposal.pid }, instance);
2644
+ }
2645
+ });
2646
+ this.holding.set(key, done);
2647
+ void done.finally(() => {
2648
+ if (this.holding.get(key) === done)
2649
+ this.holding.delete(key);
2650
+ }).catch(() => undefined);
2651
+ return done;
2652
+ }
2653
+ /**
2654
+ * A seat's reply to a turn that holds a job proposal: its revision block (bound to that turn's message) is merged and
2655
+ * published, or refused; either way, and when the turn wrote none or failed, the hold ends.
2656
+ */
2657
+ onTurnReply(frame) {
2658
+ const turnId = frame.turnId;
2659
+ if (turnId === undefined || !this.jobsOn())
2660
+ return;
2661
+ // Answered, not gone: a read must not release this hold while its revision is still queued (codex r1).
2662
+ const key = `${frame.chat}\u0000${turnId}`;
2663
+ this.settling.set(key, (this.settling.get(key) ?? 0) + 1);
2664
+ const instance = this.deps.instanceOf(frame.chat);
2665
+ const job = this.order.run(`chat\u0000${frame.chat}`, async () => {
2666
+ // The hold is written with the person's message, which can land just after a fast reply.
2667
+ const heldBy = () => [...foldProposals(this.deps.records(frame.chat)).values()].find((f) => f.state === 'revising' && f.hold === turnId);
2668
+ for (let i = 0; i < 25 && heldBy() === undefined && !this.deps.records(frame.chat).some((r) => r.kind === 'user' && r.turnId === turnId); i += 1) {
2669
+ await new Promise((res) => setTimeout(res, 200));
2670
+ }
2671
+ // The hold is enqueued with the message; a fast reply waits for it to be written, not only for the message.
2672
+ await this.holding.get(`${frame.chat}\u0000${turnId}`);
2673
+ if (heldBy() === undefined)
2674
+ return;
2675
+ await this.lock.run(`chat\u0000${instance ?? frame.chat}`, async () => {
2676
+ if (this.deps.instanceOf(frame.chat) !== instance)
2677
+ return;
2678
+ const held = heldBy();
2679
+ if (held === undefined)
2680
+ return;
2681
+ let note = frame.ok ? null : "Your change wasn't applied: say it again.";
2682
+ if (frame.ok) {
2683
+ let rev = null;
2684
+ for (let i = frame.blocks.length - 1; i >= 0 && rev === null; i -= 1)
2685
+ rev = parseRevisionBlock(frame.blocks[i]);
2686
+ if (rev !== null && rev.revises === held.proposal.pid) {
2687
+ const message = this.deps.records(frame.chat).find((r) => r.kind === 'user' && r.turnId === turnId && r.owner === true)?.text ?? null;
2688
+ try {
2689
+ const out = await this.reviseLocked(frame.chat, rev, { person: null, source: 'chat', pid: `${frame.chat}:${turnId}`, turnId, message }, instance);
2690
+ if (out.code >= 400) {
2691
+ // Said, not only logged (codex r6): the proposal is startable again as it was, and the person knows why.
2692
+ const why = out.body.error;
2693
+ note = `Your change wasn't applied${typeof why === 'string' && why !== '' ? `: ${why.slice(0, 160)}` : ''}.`;
2694
+ this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s revision was refused (${String(out.body.code ?? out.code)})`);
2695
+ }
2696
+ }
2697
+ catch (err) {
2698
+ note = "Your change wasn't applied: say it again.";
2699
+ this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s revision failed: ${err instanceof Error ? err.message : String(err)}`);
2700
+ }
2701
+ }
2702
+ else if (rev !== null) {
2703
+ if (this.planScheduled.has(key)) {
2704
+ // It names the chat's launched job: the held-plan path answers it, and releases this hold after it, saying
2705
+ // whether an offer came of it (codex r7).
2706
+ this.deferredRelease.add(key);
2707
+ // Still settling until the plan path releases it: a chat read must not reopen it first (codex r8).
2708
+ this.settling.set(key, (this.settling.get(key) ?? 0) + 1);
2709
+ return;
2710
+ }
2711
+ // Said, not silently dropped: the person's change did not land (codex r5).
2712
+ note = "Your change wasn't applied: say it again.";
2713
+ this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s revision names ${rev.revises}, not the proposal its message held — dropped`);
2714
+ }
2715
+ }
2716
+ // Released whatever happened (a published revision supersedes the parent; the record is then a no-op).
2717
+ this.write(frame.chat, { at: this.now(), turnId, kind: 'proposal_released', pid: held.proposal.pid, note }, instance);
2718
+ });
2719
+ })
2720
+ .catch((err) => this.log(`[proposals] chat ${frame.chat}: turn ${turnId}'s hold could not be settled: ${err instanceof Error ? err.message : String(err)}`))
2721
+ .finally(() => {
2722
+ this.pending.delete(job);
2723
+ const n = (this.settling.get(key) ?? 1) - 1;
2724
+ if (n <= 0)
2725
+ this.settling.delete(key);
2726
+ else
2727
+ this.settling.set(key, n);
2728
+ });
2729
+ this.pending.add(job);
2730
+ }
2731
+ /**
2732
+ * A hold whose turn is no longer live (it failed or expired, or a restart forgot it) is released with a note, so the
2733
+ * proposal is startable again. Called by a Go and by a read of the chat. `true` when one was released.
2734
+ */
2735
+ async reopenStale(chatId, instance = this.deps.instanceOf(chatId)) {
2736
+ if (this.deps.turnLive === undefined)
2737
+ return false;
2738
+ const gone = (turnId) => !this.deps.turnLive(chatId, turnId) && !this.settling.has(`${chatId}\u0000${turnId}`);
2739
+ const stale = [...foldProposals(this.deps.records(chatId)).values()].filter((f) => f.state === 'revising' && f.hold !== undefined && gone(f.hold));
2740
+ if (stale.length === 0)
2741
+ return false;
2742
+ return this.lock.run(`chat\u0000${instance ?? chatId}`, async () => {
2743
+ let released = false;
2744
+ for (const f of foldProposals(this.deps.records(chatId)).values()) {
2745
+ if (f.state !== 'revising' || f.hold === undefined || !gone(f.hold))
2746
+ continue;
2747
+ released = this.write(chatId, { at: this.now(), turnId: f.hold, kind: 'proposal_released', pid: f.proposal.pid, note: "Your change wasn't applied: say it again." }, instance) || released;
2748
+ }
2749
+ return released;
2750
+ });
2751
+ }
2752
+ /** A job's Go edits (option, depth, repository, seats, inputs) merged by the revision rules: one that loses a check
2753
+ * is refused (that is the person's press on the lost-check question, not an edit at Go). */
2754
+ async applyJobEdits(chatId, f, edits) {
2755
+ const allowed = ['option', 'depth', 'repoRef', 'seats', 'inputs'];
2756
+ for (const k of Object.keys(edits))
2757
+ if (!allowed.includes(k))
2758
+ throw new EditRefusal(`${k} can't be changed on a job proposal`);
2759
+ const chat = this.jobChat(chatId);
2760
+ if (chat === null)
2761
+ throw new EditRefusal('this chat has ended');
2762
+ const rev = {
2763
+ ...(edits.option !== undefined ? { option: edits.option } : {}),
2764
+ ...(edits.depth !== undefined ? { depth: edits.depth } : {}),
2765
+ ...(edits.repoRef !== undefined ? { repoRef: edits.repoRef } : {}),
2766
+ ...(edits.inputs !== undefined ? { inputs: edits.inputs } : {}),
2767
+ };
2768
+ const ctx = await this.jobContext(chatId, f.proposal.pid, f.proposal.turnId, f.proposal.seat, chat, { revises: f.proposal.revises ?? null, lineage: f.proposal.lineage ?? f.proposal.pid, notes: [] });
2769
+ const merged = await this.mergeJobRevision(f.proposal, rev, ctx);
2770
+ if (edits.seats !== undefined) {
2771
+ const sr = f.proposal.shape === undefined ? null : resolveOption(f.proposal.shape.card, f.proposal.shape.option, ctx.served);
2772
+ if (sr?.workflow !== null && sr?.workflow !== undefined && SELF_SEATED.has(sr.workflow))
2773
+ throw new EditRefusal(`${f.proposal.what.title} picks its own seat`);
2774
+ const can = new Set(ctx.roster.map((s) => s.key));
2775
+ if (edits.seats.length === 0 || edits.seats.some((k) => !can.has(k)))
2776
+ throw new EditRefusal('pick seats that can work now');
2777
+ merged.facts.seats = [...new Set(edits.seats)];
2778
+ merged.facts.lead = edits.seats[0];
2779
+ }
2780
+ if (merged.notes.length > 0)
2781
+ throw new EditRefusal(merged.notes[0]);
2782
+ if (merged.lost.length > 0 || merged.lostSeats.length > 0) {
2783
+ throw new EditRefusal(`that would drop ${[...merged.lost.map((g) => checksLabel([g])), ...merged.lostSeats.map((k) => SEAT_WORDS[k])].join(', ')}; ask for it in the chat`);
2784
+ }
2785
+ if (edits.inputs?.['documents'] === undefined) {
2786
+ const gone = await this.firstGone(chatId, f.proposal);
2787
+ if (gone !== null)
2788
+ throw new JobRefusal('source_gone', gone, 409);
2789
+ }
2790
+ const out = keepReshape(await this.proposalOf(chatId, f.proposal.pid, merged.facts, ctx, this.deps.records(chatId), merged.facts.card === f.proposal.shape?.card, f.proposal), f.proposal);
2791
+ this.refuseStruckDocuments(out, edits.inputs?.['documents'] === undefined ? f.proposal : undefined);
2792
+ if (out.kind !== 'job')
2793
+ throw new EditRefusal('that option makes a document: pick it in the chat');
2794
+ const dropped = (f.proposal.gate ?? []).filter((g) => !(out.gate ?? []).includes(g));
2795
+ if (dropped.length > 0)
2796
+ throw new EditRefusal(`that would drop ${checksLabel(dropped)}; check the job again`);
2797
+ if (out.seats !== undefined && out.shape !== undefined) {
2798
+ const r = resolveOption(out.shape.card, out.shape.option, ctx.served);
2799
+ if (r !== null && !(r.workflow !== null && SELF_SEATED.has(r.workflow)) && out.seats.keys.length < 1 + (r.resolved.seats.distinctEvaluator ? 1 : 0) + (r.resolved.seats.distinctJudge ? 1 : 0)) {
2800
+ throw new EditRefusal('this job needs another seat to check the one that builds');
2801
+ }
2802
+ }
2803
+ return out;
2804
+ }
2805
+ /**
2806
+ * Go on a job (§4.6): the frozen catalog revision and resolution are compared with the current catalog first; a
2807
+ * mismatch records the refreshed proposal (superseding this one) and answers 409 `catalog_changed`.
2808
+ */
2809
+ async jobStale(chatId, f0, instance) {
2810
+ // Re-read under the chat's lock: a revision that won the lock first made this one stale (codex r1).
2811
+ const f = foldProposals(this.deps.records(chatId)).get(f0.proposal.pid);
2812
+ if (f === undefined || f.state !== f0.state) {
2813
+ return { code: 409, body: { code: 'proposal_stale', error: 'this proposal changed while it was being started; check it again', ...(f !== undefined ? { view: viewOf(f) } : {}) } };
2814
+ }
2815
+ const p = f.state === 'accepting' && f.accepting !== undefined ? f.accepting.resolution : f.proposal;
2816
+ if (p.shape === undefined)
2817
+ return null;
2818
+ // A chat that has ended is re-checked from the proposal's own facts (codex r2): the check never depends on it being open.
2819
+ const chat = this.jobChat(chatId) ?? {
2820
+ projectId: p.filedIn.projectId,
2821
+ repos: (p.repoRefs ?? []).map((id, i) => ({ id, name: p.repos[i] ?? id })),
2822
+ lead: p.seats?.lead ?? null,
2823
+ seats: p.seats?.keys ?? [],
2824
+ };
2825
+ // One refresh suffix, not one per refresh: the id stays bounded however often the catalog changes (codex r2).
2826
+ const pid = `${p.pid.replace(/(?::c:[0-9a-z]+)+$/u, '')}:c:${this.now().toString(36)}`;
2827
+ let ctx;
2828
+ try {
2829
+ ctx = await this.jobContext(chatId, pid, p.turnId, p.seat, chat, { revises: p.pid, lineage: p.lineage ?? p.pid, notes: ['The catalog changed since this was proposed: check it again before starting.'] });
2830
+ await this.loadJobSources(factsOf(p), ctx);
2831
+ }
2832
+ catch (err) {
2833
+ const refused = this.refusalOf(err);
2834
+ if (refused !== null)
2835
+ return refused;
2836
+ throw err;
2837
+ }
2838
+ const card = CATALOG_V2_CARDS.find((c) => c.id === p.shape.card);
2839
+ const r = card === undefined ? null : resolveOption(card.id, optionFor(card, p.shape.option), ctx.served);
2840
+ if (r !== null && ctx.served.rev === p.catalogRev && r.resolved.resolution === p.resolution)
2841
+ return null;
2842
+ let fresh;
2843
+ try {
2844
+ fresh = keepReshape(await this.proposalOf(chatId, pid, factsOf(p), ctx, this.deps.records(chatId), true, p), p);
2845
+ }
2846
+ catch (err) {
2847
+ const refused = this.refusalOf(err);
2848
+ if (refused !== null)
2849
+ return { code: 409, body: { code: 'catalog_changed', error: `the catalog changed since this was proposed: ${String(refused.body['error'])}`, view: viewOf(f) } };
2850
+ throw err;
2851
+ }
2852
+ // A refresh that would carry fewer checks (or seat protections) than the proposal on screen is not startable until
2853
+ // the person presses the question naming what changed (codex r1).
2854
+ const lost = (p.gate ?? []).filter((g) => !(fresh.gate ?? []).includes(g));
2855
+ const lostSeats = (p.seatRules ?? []).filter((k) => !(fresh.seatRules ?? []).includes(k));
2856
+ if ((lost.length > 0 || lostSeats.length > 0) && fresh.kind === 'job') {
2857
+ const words = [...lost.map((g) => checksLabel([g])), ...lostSeats.map((k) => SEAT_WORDS[k])].join(', ');
2858
+ const text = `The catalog changed: this job would no longer have ${words}. Start it like that?`;
2859
+ // The baseline stays the proposal the person saw, so an unrelated revision cannot clear the question (codex r2).
2860
+ fresh = { ...fresh, gate: [...new Set([...(fresh.gate ?? []), ...lost])], seatRules: [...new Set([...(fresh.seatRules ?? []), ...lostSeats])], question: { kind: 'lost_check', text, choices: [{ label: 'Accept the change', edit: { confirmLoss: true } }], lost, ...(lostSeats.length > 0 ? { lostSeats } : {}) }, suggestions: [], blocked: text, ...(fresh.sentence !== undefined ? { sentence: { ...fresh.sentence, ask: text } } : {}) };
2861
+ }
2862
+ if (!this.write(chatId, { at: this.now(), turnId: f.turnId, kind: 'proposal', proposal: fresh }, instance))
2863
+ return this.gone(chatId);
2864
+ const after = foldProposals(this.deps.records(chatId)).get(pid);
2865
+ return { code: 409, body: { code: 'catalog_changed', error: 'the catalog changed since this was proposed; check the job again and press Start', ...(after !== undefined ? { view: viewOf(after) } : {}) } };
2866
+ }
2867
+ /**
2868
+ * `POST /runs/:id/reshape` (§2.5) after the route's checks (a person, the chat is theirs, the run is held at its first
2869
+ * work-plan approval): under the chat's lock, so another proposal's Start waits for it — the crew-made reshape
2870
+ * proposal `<chatId>:reshape:<run>:<requestId>` is written (or found: a repeated request is idempotent), validated
2871
+ * against the held job's checks, then Go's one reshape transition (preflight, the held plan answered Reject through
2872
+ * `deps.reshapeReject`, `heldRejected` recorded, the launch). A failed launch after the Reject leaves it accepting:
2873
+ * the same request, or Go on it, tries again.
2874
+ */
2875
+ reshape(chatId, x, actor, instance) {
2876
+ return this.lock.run(`pid\u0000${x.pid}`, () => this.lock.run(`chat\u0000${instance ?? chatId}`, async () => {
2877
+ if (this.deps.instanceOf(chatId) !== instance)
2878
+ return this.gone(chatId);
2879
+ if (!this.jobsOn())
2880
+ return { code: 409, body: { code: 'operation_unavailable', error: 'this daemon does not start jobs from a chat' } };
2881
+ let folded = foldProposals(this.deps.records(chatId)).get(x.pid);
2882
+ if (folded !== undefined && folded.proposal.request?.digest !== x.request.digest) {
2883
+ return { code: 409, body: { code: 'request_reused', error: 'this requestId already started the run again as something else', view: viewOf(folded) } };
2884
+ }
2885
+ if (folded?.state === 'decided') {
2886
+ return folded.decision === 'go' ? { code: 200, body: { view: viewOf(folded) } } : { code: 409, body: { code: 'proposal_decided', error: 'this reshape was answered Not now', view: viewOf(folded) } };
2887
+ }
2888
+ if (folded === undefined) {
2889
+ const chat = this.jobChat(chatId);
2890
+ if (chat === null)
2891
+ return { code: 409, body: { code: 'chat_gone', error: `chat ${chatId} has ended; start a new one` } };
2892
+ const parent = x.parentPid === null ? undefined : foldProposals(this.deps.records(chatId)).get(x.parentPid);
2893
+ let proposal;
2894
+ try {
2895
+ const ctx = await this.jobContext(chatId, x.pid, null, 'person', chat, {
2896
+ revises: x.parentPid,
2897
+ lineage: parent?.proposal.lineage ?? x.parentPid ?? x.pid,
2898
+ notes: x.reducedAssurance ? ['Reduced assurance, as the held run had it.'] : [],
2899
+ request: x.request,
2900
+ });
2901
+ // The held job's proposal, merged by the revision rules (its inputs validated against the new card, what
2902
+ // the new card does not take dropped with a note; codex r2). A QE skip is never carried.
2903
+ const heldP = parent?.accepting?.resolution ?? parent?.proposal;
2904
+ let facts = x.facts;
2905
+ if (heldP?.shape !== undefined) {
2906
+ const merged = await this.mergeJobRevision(heldP, x.edits, ctx);
2907
+ // Nothing is answered for a shape, or an input, that is not the one asked for (codex r3, r4).
2908
+ const wantCard = CATALOG_V2_CARDS.find((c) => c.id === (x.edits.card ?? merged.facts.card));
2909
+ const norm = (o) => (wantCard === undefined ? null : o === null || o === undefined ? (wantCard.variant?.default ?? null) : o);
2910
+ const optionOk = wantCard !== undefined && (x.edits.option === undefined || norm(merged.facts.option) === norm(x.edits.option));
2911
+ const depthOk = x.edits.depth === undefined || x.edits.depth === null || merged.facts.depth === x.edits.depth;
2912
+ const inputsOk = merged.refusedInputs.length === 0 && Object.entries(x.edits.inputs ?? {}).every(([k, v]) => (k === 'intent' ? merged.facts.words === (v.kind === 'text' ? v.value.slice(0, 8000) : '') : JSON.stringify(merged.facts.inputs[k]) === JSON.stringify(v)));
2913
+ if (wantCard === undefined || merged.facts.card !== wantCard.id || !optionOk || !depthOk || !inputsOk) {
2914
+ return { code: 400, body: { code: 'edits_invalid', error: merged.notes[0] ?? `there is no ${String(x.edits.card)}${x.edits.option !== undefined && x.edits.option !== null ? ` · ${String(x.edits.option)}` : ''} to start it again as`, notes: merged.notes } };
2915
+ }
2916
+ // A reshape is the person's shape: no detection guess describing the held job rides on it (codex r3).
2917
+ const { guess: _old, ...personFacts } = merged.facts;
2918
+ void _old;
2919
+ facts = { ...personFacts, skipQe: null, by: 'person', source: 'reshape' };
2920
+ ctx.notes.push(...merged.notes);
2921
+ }
2922
+ if (heldP !== undefined && x.edits.inputs?.['documents'] === undefined) {
2923
+ const gone = await this.firstGone(chatId, heldP);
2924
+ if (gone !== null)
2925
+ throw new JobRefusal('source_gone', gone, 409);
2926
+ }
2927
+ proposal = await this.proposalOf(chatId, x.pid, facts, ctx, this.deps.records(chatId), false, heldP ?? null);
2928
+ if (x.edits.inputs?.['documents'] !== undefined)
2929
+ this.refuseStruckDocuments(proposal);
2930
+ else if (heldP !== undefined)
2931
+ this.refuseStruckDocuments(proposal, heldP);
2932
+ }
2933
+ catch (err) {
2934
+ const refused = this.refusalOf(err);
2935
+ if (refused !== null)
2936
+ return refused;
2937
+ throw err;
2938
+ }
2939
+ if (proposal.kind !== 'job')
2940
+ return { code: 400, body: { code: 'shape_mismatch', error: 'a held run starts again as another job, not a document' } };
2941
+ // The held job's checks and seat protections are the parent's; a replacement with fewer is started only on the
2942
+ // person's press naming them (§2.5: the reshape question names the checks given up; codex r1).
2943
+ const held = parent?.accepting?.resolution ?? parent?.proposal;
2944
+ if (held !== undefined) {
2945
+ const lost = (held.gate ?? []).filter((g) => !(proposal.gate ?? []).includes(g));
2946
+ const heldCard = held.shape === undefined ? null : CATALOG_V2_CARDS.find((c) => c.id === held.shape.card) ?? null;
2947
+ const before = held.seatRules ?? (heldCard === null ? [] : seatProtections(resolveOption(heldCard.id, optionFor(heldCard, held.shape.option), (await this.deps.served(chat.projectId)))));
2948
+ const after = proposal.seatRules ?? [];
2949
+ const lostSeats = before.filter((k) => !after.includes(k));
2950
+ // Confirmed only for exactly what the person was shown (a loss since asks again; codex r4).
2951
+ if ([...lost, ...lostSeats].some((k) => !x.confirmLoss.includes(k))) {
2952
+ const words = [...lost.map((g) => checksLabel([g])), ...lostSeats.map((k) => SEAT_WORDS[k])];
2953
+ return { code: 409, body: { code: 'reshape_loses_check', error: `started again like that, it would no longer have ${words.join(', ')}: confirm to give ${words.length === 1 ? 'it' : 'them'} up`, lost, lostSeats } };
2954
+ }
2955
+ }
2956
+ proposal = { ...proposal, reshapes: x.oldRunId, relaunch: x.relaunch, ...(x.reducedAssurance ? { reducedAssurance: true } : {}), ...(x.heldPlan !== undefined ? { heldPlan: x.heldPlan } : {}) };
2957
+ if (!this.write(chatId, { at: this.now(), turnId: `reshape:${x.oldRunId}`, kind: 'proposal', proposal }, instance))
2958
+ return this.gone(chatId);
2959
+ folded = foldProposals(this.deps.records(chatId)).get(x.pid);
2960
+ }
2961
+ const p = folded.state === 'accepting' && folded.accepting !== undefined ? folded.accepting.resolution : folded.proposal;
2962
+ if (folded.state === 'accepting' && folded.accepting !== undefined) {
2963
+ // A retry after the replacement launched (a lost response, a crash before the decision): adopt it (codex r1).
2964
+ const found = await this.deps.registry.find('job', folded.accepting.identity);
2965
+ if (found !== null) {
2966
+ const result = { runId: folded.accepting.identity.runId, artifactRef: null, adopted: true, stub: found.stub };
2967
+ if (!this.decided(chatId, folded.turnId, x.pid, actor, 'go', result, folded.accepting.resolution, folded.accepting.edits, instance))
2968
+ return this.gone(chatId);
2969
+ return { code: 200, body: { view: viewOf(foldProposals(this.deps.records(chatId)).get(x.pid)) } };
2970
+ }
2971
+ }
2972
+ // Only the open (or interrupted) newest proposal of its lineage goes on: checked before any Reject (codex r3).
2973
+ if (folded.state === 'superseded' || folded.state === 'revising') {
2974
+ return { code: 409, body: { code: folded.state === 'revising' ? 'proposal_revising' : 'proposal_superseded', error: 'this reshape changed since; check it again', view: viewOf(folded) } };
2975
+ }
2976
+ const newest = [...foldProposals(this.deps.records(chatId)).values()].filter((f) => f.proposal.lineage === p.lineage).pop();
2977
+ if (newest !== undefined && newest.proposal.pid !== x.pid) {
2978
+ return { code: 409, body: { code: 'proposal_superseded', error: 'a newer version of this job replaced this reshape', view: viewOf(newest) } };
2979
+ }
2980
+ // A retry is checked against the catalog like any Go, interrupted ones included (codex r2, r3).
2981
+ const stale = await this.jobStale(chatId, folded, instance);
2982
+ if (stale !== null)
2983
+ return stale;
2984
+ if (folded.state !== 'accepting') {
2985
+ if (p.blocked !== null)
2986
+ return { code: 409, body: { code: 'proposal_blocked', error: p.blocked, view: viewOf(folded) } };
2987
+ }
2988
+ const current = folded.state === 'accepting' && folded.accepting !== undefined ? folded.accepting.resolution : folded.proposal;
2989
+ const identity = folded.accepting?.identity ?? this.identityOf(current);
2990
+ return this.goLocked(chatId, folded, current, null, identity, actor, instance);
2991
+ }));
2992
+ }
2993
+ /** A proposal of this chat, folded, or `null`. */
2994
+ viewOfPid(chatId, pid) {
2995
+ const f = foldProposals(this.deps.records(chatId)).get(pid);
2996
+ return f === undefined ? null : viewOf(f);
2997
+ }
2998
+ /** The proposal as it was accepted (its effective resolution), else as it stands; `null` when the chat has none. */
2999
+ proposalOfPid(chatId, pid) {
3000
+ const f = foldProposals(this.deps.records(chatId)).get(pid);
3001
+ return f === undefined ? null : (f.accepting?.resolution ?? f.proposal);
3002
+ }
1468
3003
  // ── A3: what the create launcher and the daemon need from the proposals ────────────────────────────────────────────
1469
3004
  /**
1470
3005
  * The accepted proposal a create's `chat_id` + `proposal_id` names, for this actor (§5.2): accepting (or decided go),
@@ -1515,14 +3050,20 @@ export class ChatProposals {
1515
3050
  const pid = `${base.chatId}:retry:${runId}`;
1516
3051
  if (folded.has(pid))
1517
3052
  return pid;
3053
+ // A5 (codex r1): a refine's retry is drawn on the document as it is now (a conflict moved its head), with the
3054
+ // protected edits of that head, Keep preselected for every one.
3055
+ const fresh = base.kind === 'refine' && base.target !== undefined ? await this.refreshTarget(base) : base;
1518
3056
  const retry = {
1519
- ...base,
3057
+ ...fresh,
1520
3058
  pid,
1521
3059
  turnId: null,
1522
3060
  sourceRunId: runId,
1523
3061
  artifactRef,
1524
- reason: `The last attempt ended without a draft: ${reason}. Try again fills the same document.`,
1525
- blocked: null,
3062
+ reason: base.kind === 'refine'
3063
+ ? `The last change was not applied: ${reason}. Try again revises the latest version, and keeps your edits.`
3064
+ : `The last attempt ended without a draft: ${reason}. Try again fills the same document.`,
3065
+ // A refine whose edits cannot be read on the new head stays blocked with why (codex A5 r2).
3066
+ blocked: fresh !== base ? fresh.blocked : null,
1526
3067
  };
1527
3068
  return this.write(chatId, { at: this.now(), turnId: failed.turnId, kind: 'proposal', proposal: retry }, instance) ? pid : null;
1528
3069
  });