wicked-crew 0.18.21 → 0.18.23

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 (297) hide show
  1. package/dist/api/audit-view.d.ts.map +1 -1
  2. package/dist/api/audit-view.js +1 -0
  3. package/dist/api/audit-view.js.map +1 -1
  4. package/dist/api/audit.d.ts +28 -1
  5. package/dist/api/audit.d.ts.map +1 -1
  6. package/dist/api/audit.js +90 -9
  7. package/dist/api/audit.js.map +1 -1
  8. package/dist/api/auth.d.ts +7 -0
  9. package/dist/api/auth.d.ts.map +1 -1
  10. package/dist/api/auth.js +53 -10
  11. package/dist/api/auth.js.map +1 -1
  12. package/dist/api/capture.d.ts +11 -2
  13. package/dist/api/capture.d.ts.map +1 -1
  14. package/dist/api/capture.js +7 -2
  15. package/dist/api/capture.js.map +1 -1
  16. package/dist/api/chat-context.d.ts +6 -1
  17. package/dist/api/chat-context.d.ts.map +1 -1
  18. package/dist/api/chat-context.js +45 -11
  19. package/dist/api/chat-context.js.map +1 -1
  20. package/dist/api/chat-proposals.d.ts +24 -7
  21. package/dist/api/chat-proposals.d.ts.map +1 -1
  22. package/dist/api/chat-proposals.js +98 -18
  23. package/dist/api/chat-proposals.js.map +1 -1
  24. package/dist/api/chat-scope.d.ts +6 -2
  25. package/dist/api/chat-scope.d.ts.map +1 -1
  26. package/dist/api/chat-scope.js +13 -7
  27. package/dist/api/chat-scope.js.map +1 -1
  28. package/dist/api/cluster-status.d.ts +17 -0
  29. package/dist/api/cluster-status.d.ts.map +1 -1
  30. package/dist/api/cluster-status.js +70 -3
  31. package/dist/api/cluster-status.js.map +1 -1
  32. package/dist/api/compose-facts.d.ts +35 -0
  33. package/dist/api/compose-facts.d.ts.map +1 -0
  34. package/dist/api/compose-facts.js +46 -0
  35. package/dist/api/compose-facts.js.map +1 -0
  36. package/dist/api/cut-read.d.ts +62 -0
  37. package/dist/api/cut-read.d.ts.map +1 -0
  38. package/dist/api/cut-read.js +101 -0
  39. package/dist/api/cut-read.js.map +1 -0
  40. package/dist/api/desk-snoozes.d.ts +77 -0
  41. package/dist/api/desk-snoozes.d.ts.map +1 -0
  42. package/dist/api/desk-snoozes.js +220 -0
  43. package/dist/api/desk-snoozes.js.map +1 -0
  44. package/dist/api/diagnostics.d.ts +4 -0
  45. package/dist/api/diagnostics.d.ts.map +1 -1
  46. package/dist/api/diagnostics.js +15 -7
  47. package/dist/api/diagnostics.js.map +1 -1
  48. package/dist/api/disk-stores.d.ts +66 -0
  49. package/dist/api/disk-stores.d.ts.map +1 -0
  50. package/dist/api/disk-stores.js +206 -0
  51. package/dist/api/disk-stores.js.map +1 -0
  52. package/dist/api/domain-model.d.ts +56 -0
  53. package/dist/api/domain-model.d.ts.map +1 -0
  54. package/dist/api/domain-model.js +281 -0
  55. package/dist/api/domain-model.js.map +1 -0
  56. package/dist/api/domain-scope.d.ts +52 -0
  57. package/dist/api/domain-scope.d.ts.map +1 -0
  58. package/dist/api/domain-scope.js +156 -0
  59. package/dist/api/domain-scope.js.map +1 -0
  60. package/dist/api/eval-rule-store.d.ts +32 -0
  61. package/dist/api/eval-rule-store.d.ts.map +1 -0
  62. package/dist/api/eval-rule-store.js +77 -0
  63. package/dist/api/eval-rule-store.js.map +1 -0
  64. package/dist/api/gate-cache.d.ts +8 -0
  65. package/dist/api/gate-cache.d.ts.map +1 -1
  66. package/dist/api/gate-cache.js +8 -1
  67. package/dist/api/gate-cache.js.map +1 -1
  68. package/dist/api/mcp.d.ts +19 -0
  69. package/dist/api/mcp.d.ts.map +1 -1
  70. package/dist/api/mcp.js +166 -3
  71. package/dist/api/mcp.js.map +1 -1
  72. package/dist/api/needs.d.ts +3 -0
  73. package/dist/api/needs.d.ts.map +1 -1
  74. package/dist/api/needs.js +7 -3
  75. package/dist/api/needs.js.map +1 -1
  76. package/dist/api/post-hoc-deliver.d.ts +7 -0
  77. package/dist/api/post-hoc-deliver.d.ts.map +1 -1
  78. package/dist/api/post-hoc-deliver.js +16 -5
  79. package/dist/api/post-hoc-deliver.js.map +1 -1
  80. package/dist/api/product-publish.d.ts +242 -0
  81. package/dist/api/product-publish.d.ts.map +1 -0
  82. package/dist/api/product-publish.js +902 -0
  83. package/dist/api/product-publish.js.map +1 -0
  84. package/dist/api/product.d.ts +5 -6
  85. package/dist/api/product.d.ts.map +1 -1
  86. package/dist/api/product.js +4 -4
  87. package/dist/api/product.js.map +1 -1
  88. package/dist/api/proposal-cut.d.ts +95 -0
  89. package/dist/api/proposal-cut.d.ts.map +1 -0
  90. package/dist/api/proposal-cut.js +231 -0
  91. package/dist/api/proposal-cut.js.map +1 -0
  92. package/dist/api/requirements.d.ts +6 -4
  93. package/dist/api/requirements.d.ts.map +1 -1
  94. package/dist/api/requirements.js +6 -3
  95. package/dist/api/requirements.js.map +1 -1
  96. package/dist/api/routes.d.ts +21 -0
  97. package/dist/api/routes.d.ts.map +1 -1
  98. package/dist/api/routes.js +578 -94
  99. package/dist/api/routes.js.map +1 -1
  100. package/dist/api/run-liveness.d.ts.map +1 -1
  101. package/dist/api/run-liveness.js +3 -1
  102. package/dist/api/run-liveness.js.map +1 -1
  103. package/dist/api/run-timing-index.d.ts +10 -0
  104. package/dist/api/run-timing-index.d.ts.map +1 -1
  105. package/dist/api/run-timing-index.js +29 -9
  106. package/dist/api/run-timing-index.js.map +1 -1
  107. package/dist/api/seat-container-login.d.ts +11 -17
  108. package/dist/api/seat-container-login.d.ts.map +1 -1
  109. package/dist/api/seat-container-login.js +36 -69
  110. package/dist/api/seat-container-login.js.map +1 -1
  111. package/dist/api/server.d.ts.map +1 -1
  112. package/dist/api/server.js +1 -0
  113. package/dist/api/server.js.map +1 -1
  114. package/dist/api/system-snapshot.d.ts +5 -2
  115. package/dist/api/system-snapshot.d.ts.map +1 -1
  116. package/dist/api/system-snapshot.js +18 -6
  117. package/dist/api/system-snapshot.js.map +1 -1
  118. package/dist/api/testing.d.ts.map +1 -1
  119. package/dist/api/testing.js +11 -8
  120. package/dist/api/testing.js.map +1 -1
  121. package/dist/api/ui-text.d.ts.map +1 -1
  122. package/dist/api/ui-text.js +3 -1
  123. package/dist/api/ui-text.js.map +1 -1
  124. package/dist/apps/actions/write-path.d.ts +6 -2
  125. package/dist/apps/actions/write-path.d.ts.map +1 -1
  126. package/dist/apps/actions/write-path.js +7 -3
  127. package/dist/apps/actions/write-path.js.map +1 -1
  128. package/dist/apps/store.d.ts +11 -0
  129. package/dist/apps/store.d.ts.map +1 -1
  130. package/dist/apps/store.js +47 -0
  131. package/dist/apps/store.js.map +1 -1
  132. package/dist/apps-server/server/lib/bundle/server.mjs +19 -5
  133. package/dist/cli/index.d.ts.map +1 -1
  134. package/dist/cli/index.js +38 -52
  135. package/dist/cli/index.js.map +1 -1
  136. package/dist/cli/mcp.d.ts +14 -0
  137. package/dist/cli/mcp.d.ts.map +1 -1
  138. package/dist/cli/mcp.js +27 -10
  139. package/dist/cli/mcp.js.map +1 -1
  140. package/dist/cli/start-stand-ins.d.ts +13 -0
  141. package/dist/cli/start-stand-ins.d.ts.map +1 -0
  142. package/dist/cli/start-stand-ins.js +30 -0
  143. package/dist/cli/start-stand-ins.js.map +1 -0
  144. package/dist/core/adapter.d.ts +57 -6
  145. package/dist/core/adapter.d.ts.map +1 -1
  146. package/dist/core/adapter.js +208 -30
  147. package/dist/core/adapter.js.map +1 -1
  148. package/dist/core/ado-env.d.ts +17 -0
  149. package/dist/core/ado-env.d.ts.map +1 -0
  150. package/dist/core/ado-env.js +34 -0
  151. package/dist/core/ado-env.js.map +1 -0
  152. package/dist/core/deliver-text.d.ts +17 -0
  153. package/dist/core/deliver-text.d.ts.map +1 -1
  154. package/dist/core/deliver-text.js +76 -1
  155. package/dist/core/deliver-text.js.map +1 -1
  156. package/dist/core/deliver.d.ts +6 -0
  157. package/dist/core/deliver.d.ts.map +1 -1
  158. package/dist/core/deliver.js +12 -4
  159. package/dist/core/deliver.js.map +1 -1
  160. package/dist/core/exec.d.ts +1 -10
  161. package/dist/core/exec.d.ts.map +1 -1
  162. package/dist/core/exec.js +4 -17
  163. package/dist/core/exec.js.map +1 -1
  164. package/dist/core/governance-store.d.ts +3 -1
  165. package/dist/core/governance-store.d.ts.map +1 -1
  166. package/dist/core/governance-store.js +7 -2
  167. package/dist/core/governance-store.js.map +1 -1
  168. package/dist/core/launch-posture.d.ts +3 -0
  169. package/dist/core/launch-posture.d.ts.map +1 -1
  170. package/dist/core/launch-posture.js +4 -0
  171. package/dist/core/launch-posture.js.map +1 -1
  172. package/dist/core/repo-clone.d.ts.map +1 -1
  173. package/dist/core/repo-clone.js +2 -1
  174. package/dist/core/repo-clone.js.map +1 -1
  175. package/dist/core/run-log-facts.d.ts +56 -0
  176. package/dist/core/run-log-facts.d.ts.map +1 -0
  177. package/dist/core/run-log-facts.js +230 -0
  178. package/dist/core/run-log-facts.js.map +1 -0
  179. package/dist/core/shutdown.d.ts +27 -0
  180. package/dist/core/shutdown.d.ts.map +1 -1
  181. package/dist/core/shutdown.js +72 -0
  182. package/dist/core/shutdown.js.map +1 -1
  183. package/dist/core/stand-in.d.ts +62 -0
  184. package/dist/core/stand-in.d.ts.map +1 -0
  185. package/dist/core/stand-in.js +153 -0
  186. package/dist/core/stand-in.js.map +1 -0
  187. package/dist/core/types.d.ts +22 -0
  188. package/dist/core/types.d.ts.map +1 -1
  189. package/dist/core/types.js.map +1 -1
  190. package/dist/editors/pack-extras.d.ts +162 -0
  191. package/dist/editors/pack-extras.d.ts.map +1 -0
  192. package/dist/editors/pack-extras.js +596 -0
  193. package/dist/editors/pack-extras.js.map +1 -0
  194. package/dist/editors/pack-install.d.ts +15 -7
  195. package/dist/editors/pack-install.d.ts.map +1 -1
  196. package/dist/editors/pack-install.js +140 -19
  197. package/dist/editors/pack-install.js.map +1 -1
  198. package/dist/editors/registry.d.ts +42 -3
  199. package/dist/editors/registry.d.ts.map +1 -1
  200. package/dist/editors/registry.js +114 -11
  201. package/dist/editors/registry.js.map +1 -1
  202. package/dist/editors/routes.d.ts +10 -5
  203. package/dist/editors/routes.d.ts.map +1 -1
  204. package/dist/editors/routes.js +45 -11
  205. package/dist/editors/routes.js.map +1 -1
  206. package/dist/interactive/bridge-pool.d.ts +5 -2
  207. package/dist/interactive/bridge-pool.d.ts.map +1 -1
  208. package/dist/interactive/bridge-pool.js +4 -1
  209. package/dist/interactive/bridge-pool.js.map +1 -1
  210. package/dist/interactive/landing-guard.d.ts.map +1 -1
  211. package/dist/interactive/landing-guard.js +79 -5
  212. package/dist/interactive/landing-guard.js.map +1 -1
  213. package/dist/knowledge/adapters/toolbox/memory.d.ts.map +1 -1
  214. package/dist/knowledge/adapters/toolbox/memory.js +3 -2
  215. package/dist/knowledge/adapters/toolbox/memory.js.map +1 -1
  216. package/dist/knowledge/trackers/set.d.ts +28 -0
  217. package/dist/knowledge/trackers/set.d.ts.map +1 -1
  218. package/dist/knowledge/trackers/set.js +26 -0
  219. package/dist/knowledge/trackers/set.js.map +1 -1
  220. package/dist/mcp/policies.d.ts +44 -0
  221. package/dist/mcp/policies.d.ts.map +1 -1
  222. package/dist/mcp/policies.js +153 -1
  223. package/dist/mcp/policies.js.map +1 -1
  224. package/dist/mcp/registry-store.d.ts +10 -0
  225. package/dist/mcp/registry-store.d.ts.map +1 -1
  226. package/dist/mcp/registry-store.js.map +1 -1
  227. package/dist/mcp/registry.d.ts +43 -3
  228. package/dist/mcp/registry.d.ts.map +1 -1
  229. package/dist/mcp/registry.js +224 -16
  230. package/dist/mcp/registry.js.map +1 -1
  231. package/dist/mcp/trigger-names.d.ts +32 -0
  232. package/dist/mcp/trigger-names.d.ts.map +1 -0
  233. package/dist/mcp/trigger-names.js +529 -0
  234. package/dist/mcp/trigger-names.js.map +1 -0
  235. package/dist/persona/routes.d.ts +1 -1
  236. package/dist/persona/store.d.ts +1 -1
  237. package/dist/schedules/routes.d.ts.map +1 -1
  238. package/dist/schedules/routes.js +6 -0
  239. package/dist/schedules/routes.js.map +1 -1
  240. package/dist/skills/store.d.ts +11 -1
  241. package/dist/skills/store.d.ts.map +1 -1
  242. package/dist/skills/store.js +37 -3
  243. package/dist/skills/store.js.map +1 -1
  244. package/dist/sources/routes.d.ts +2 -2
  245. package/dist/sources/routes.d.ts.map +1 -1
  246. package/dist/studio/apps-standalone/fixture.js +3 -3
  247. package/dist/studio/assets/{KnowledgeGraph-yP4WsnST.js → KnowledgeGraph-BrHcKpFT.js} +1 -1
  248. package/dist/studio/assets/index-BCVvMebl.css +32 -0
  249. package/dist/studio/assets/{index-DW53FKuT.js → index-BqB2Ydq-.js} +337 -311
  250. package/dist/studio/editors/wicked-apps/editor.json +1 -1
  251. package/dist/studio/editors/wicked-apps/index.html +1 -1
  252. package/dist/studio/editors/wicked-deck/editor.json +1 -1
  253. package/dist/studio/editors/wicked-deck/index.html +1 -1
  254. package/dist/studio/editors/wicked-doc/editor.json +1 -1
  255. package/dist/studio/editors/wicked-doc/index.html +1 -1
  256. package/dist/studio/editors/wicked-insights/editor.json +1 -1
  257. package/dist/studio/editors/wicked-insights/index.html +1 -1
  258. package/dist/studio/editors/wicked-page/editor.json +1 -1
  259. package/dist/studio/editors/wicked-page/index.html +1 -1
  260. package/dist/studio/editors/wicked-video/editor.json +1 -1
  261. package/dist/studio/editors/wicked-video/index.html +1 -1
  262. package/dist/studio/index.html +2 -2
  263. package/dist/studio/testid-inventory.json +953 -107
  264. package/dist/team/routes.d.ts +4 -1
  265. package/dist/team/routes.d.ts.map +1 -1
  266. package/dist/team/routes.js +1 -1
  267. package/dist/team/routes.js.map +1 -1
  268. package/dist/voice/tts.d.ts +6 -0
  269. package/dist/voice/tts.d.ts.map +1 -1
  270. package/dist/voice/tts.js +16 -1
  271. package/dist/voice/tts.js.map +1 -1
  272. package/endpoint-manifest.json +100 -6
  273. package/package.json +4 -4
  274. package/voice-locks/darwin-arm64-cp310.txt +12 -0
  275. package/voice-locks/darwin-arm64-cp311.txt +8 -0
  276. package/voice-locks/darwin-arm64-cp312.txt +8 -0
  277. package/voice-locks/darwin-arm64-cp313.txt +8 -0
  278. package/voice-locks/darwin-arm64-cp314.txt +8 -0
  279. package/voice-locks/darwin-arm64-cp39.txt +12 -0
  280. package/voice-locks/darwin-x64-cp310.txt +12 -0
  281. package/voice-locks/darwin-x64-cp311.txt +12 -0
  282. package/voice-locks/darwin-x64-cp312.txt +12 -0
  283. package/voice-locks/darwin-x64-cp313.txt +12 -0
  284. package/voice-locks/darwin-x64-cp39.txt +12 -0
  285. package/voice-locks/linux-arm64-cp310.txt +12 -0
  286. package/voice-locks/linux-arm64-cp311.txt +8 -0
  287. package/voice-locks/linux-arm64-cp312.txt +8 -0
  288. package/voice-locks/linux-arm64-cp313.txt +8 -0
  289. package/voice-locks/linux-arm64-cp314.txt +8 -0
  290. package/voice-locks/linux-arm64-cp39.txt +12 -0
  291. package/voice-locks/linux-x64-cp310.txt +12 -0
  292. package/voice-locks/linux-x64-cp311.txt +8 -0
  293. package/voice-locks/linux-x64-cp312.txt +8 -0
  294. package/voice-locks/linux-x64-cp313.txt +8 -0
  295. package/voice-locks/linux-x64-cp314.txt +8 -0
  296. package/voice-locks/linux-x64-cp39.txt +12 -0
  297. package/dist/studio/assets/index-DNaLjJ7M.css +0 -32
@@ -0,0 +1,902 @@
1
+ /**
2
+ * (crew#372, DES-372 rev 4) Product publish: a finished compose run's plan becomes GitHub issues in a repository linked
3
+ * to the project, by a person, card first.
4
+ *
5
+ * POST /projects/:id/product/publish HUMAN (operator) without `confirm`: the card and its `publishHash`,
6
+ * nothing sent; with `confirm` = that hash: the
7
+ * missing items are created, then read back; with
8
+ * `resolve`: a person settles one `unsure` item
9
+ * GET /projects/:id/product/publish/:runId HUMAN (operator) whether the run can be published (and why not), the
10
+ * project's GitHub repositories, and every publication
11
+ * of the run, read back as `readBackOf` allows (crew#1911)
12
+ *
13
+ * The plan is read only from a run whose launch recorded compose facts ({@link ComposeFacts}) and whose draft and
14
+ * review units still match them: a plan edited at its gate is refused, in plain words. The repository is the project's
15
+ * own GitHub tracker ({@link projectGithubTracker}); the write is the tracker write path's (`vendorRead` as the person,
16
+ * admission re-read before each call, the credential the card was read with pinned). Each item is journaled, flushed,
17
+ * before and after it is sent (`<mcp state>/product-publish/<sha256(runId)>/<publication>.ndjson`), so a crash never
18
+ * resends: an item whose outcome crew cannot prove is `unsure` until a person resolves it. "Published" is the journal
19
+ * plus a read-back of every created issue, never the run's own claim.
20
+ *
21
+ * A publication is sent or resolved by one request at a time IN THIS DAEMON (the slot), as tracker actions are
22
+ * (`actions.ts` inFlight) and settings writes (`adapter.ts` updateSettings): the state-home fence does not make one
23
+ * daemon per home, and a second daemon on the same state home is not covered here either.
24
+ */
25
+ import { mkdir, open, readdir, readFile } from 'node:fs/promises';
26
+ import { dirname, join } from 'node:path';
27
+ import { z } from '../zod.js';
28
+ import { API_PREFIX } from './api-prefix.js';
29
+ import { appendLineSynced } from './audit.js';
30
+ import { trustAtLeast } from './auth.js';
31
+ import { sha256Hex } from './compose-facts.js';
32
+ import { canonicalJson } from '../mcp/classify.js';
33
+ import { configOf, pmDescriptorHash } from '../mcp/registry.js';
34
+ import { mcpStateDir } from '../mcp/registry-store.js';
35
+ import { bindingInForce, githubUrlIdentity, readPayload, vendorText } from '../knowledge/trackers/bindings.js';
36
+ import { liveTool, projectOptsVia } from '../knowledge/trackers/gate-pm.js';
37
+ import { pmEntriesOf, projectGithubTargets, projectGithubTracker, parseRepoSelector } from '../knowledge/trackers/set.js';
38
+ const V = API_PREFIX;
39
+ /** The most items (epics, features and stories) one publication creates. */
40
+ export const PUBLISH_ITEMS_MAX = 200;
41
+ /** What the GitHub projector keeps of a body (`PM_TEXT_MAX`): a body is budgeted whole against it. */
42
+ export const PUBLISH_BODY_MAX = 6_000;
43
+ /** A parent reference at its widest: `#` and ten digits. */
44
+ const PARENT_REF_MAX = '#9999999999';
45
+ const PARENT = '{{parent}}';
46
+ // ── The plan ───────────────────────────────────────────────────────────────────────────────────────────
47
+ const Title = z.string().min(1).max(256);
48
+ const PlanSchema = z.strictObject({
49
+ epics: z
50
+ .array(z.strictObject({
51
+ title: Title,
52
+ features: z
53
+ .array(z.strictObject({
54
+ title: Title,
55
+ requirementRefs: z.array(z.strictObject({ repoId: z.string().min(1).max(200), key: z.string().min(1).max(200) })).min(1),
56
+ stories: z
57
+ .array(z.strictObject({
58
+ title: Title,
59
+ acceptance: z.array(z.string().min(1).max(1_000)).max(20),
60
+ tasks: z.array(z.strictObject({ title: Title })).max(30).optional(),
61
+ }))
62
+ .max(50)
63
+ .optional(),
64
+ }))
65
+ .max(50),
66
+ }))
67
+ .min(1)
68
+ .max(50),
69
+ });
70
+ const refuse = (status, code, error, extra) => ({ ok: false, status, code, error, ...(extra !== undefined ? { extra } : {}) });
71
+ /** The plain-words refusal of a run whose plan crew cannot take as the compose launched it (coord ruling, 2026-11-24). */
72
+ const EDITED = "this plan was edited at its gate; publishing an edited plan isn't supported yet, compose again to publish";
73
+ /** The last fenced ```json block of a draft's output, or `null`. */
74
+ export function lastJsonBlock(text) {
75
+ let last = null;
76
+ for (const m of text.matchAll(/^[ \t]*```json[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*$/gm))
77
+ last = m[1];
78
+ return last;
79
+ }
80
+ const oneLine = (s) => s.replace(/\s+/gu, ' ').trim();
81
+ /** Text as the projector keeps it (line endings, control characters), whole. */
82
+ const normal = (s) => vendorText(s, Number.POSITIVE_INFINITY) ?? '';
83
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;
84
+ const isSelector = (cp) => (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0xe0100 && cp <= 0xe01ef);
85
+ const hex = (cp) => `U+${cp.toString(16).toUpperCase().padStart(4, '0')}`;
86
+ /**
87
+ * The first character github-mcp-server would take out of `s` before crew reads it back, or `null`. Its
88
+ * `sanitize.FilterInvisibleCharacters` (pkg/sanitize/sanitize.go, applied to titles by `sanitize.PlainText` and to
89
+ * bodies by `sanitize.Content`, pkg/github/minimal_types.go) removes U+200B, U+200C, U+200E, U+200F, U+061C, U+00AD,
90
+ * U+FEFF, U+180E, U+2060..U+2064, U+202A..U+202E, U+2066..U+2069, U+E0001 and U+E0020..U+E007F (all Unicode category
91
+ * Cf; crew refuses the whole category), and a variation selector (U+FE00..U+FE0F, U+E0100..U+E01EF) unless it follows
92
+ * a graphic, non-space base that is not itself a selector: a Han base for U+E0100 and up, and only `#`, `*` or a digit
93
+ * with U+FE0E or U+FE0F for an ASCII base. Invalid UTF-16 (a lone surrogate) would become U+FFFD.
94
+ */
95
+ export function strippedCharacter(s) {
96
+ const cf = /\p{Cf}/u.exec(s);
97
+ if (cf !== null)
98
+ return hex(cf[0].codePointAt(0));
99
+ const lone = LONE_SURROGATE.exec(s);
100
+ if (lone !== null)
101
+ return hex(lone[0].charCodeAt(0));
102
+ const chars = [...s];
103
+ for (let i = 0; i < chars.length; i++) {
104
+ const cp = chars[i].codePointAt(0);
105
+ if (!isSelector(cp))
106
+ continue;
107
+ const prev = i > 0 ? chars[i - 1] : null;
108
+ const pcp = prev === null ? -1 : prev.codePointAt(0);
109
+ const base = prev !== null && !isSelector(pcp) && /^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u.test(prev);
110
+ const kept = base && (cp >= 0xe0100 ? /^\p{Script=Han}$/u.test(prev) : pcp < 0x80 ? /^[#*0-9]$/.test(prev) && (cp === 0xfe0e || cp === 0xfe0f) : true);
111
+ if (!kept)
112
+ return hex(cp);
113
+ }
114
+ return null;
115
+ }
116
+ /**
117
+ * Why a title would not read back as written, or `null`. Besides {@link strippedCharacter}, the server's
118
+ * `sanitize.PlainText` drops HTML tags and code-fence info from a title, decodes character references, and escapes
119
+ * `&`, `<` and `>` (crew reads those back decoded).
120
+ */
121
+ function titleRefusal(t) {
122
+ const c = strippedCharacter(t);
123
+ if (c !== null)
124
+ return `has an invisible character (${c}) that GitHub's server removes`;
125
+ if (/<[A-Za-z/!?]/.test(t))
126
+ return 'has text GitHub reads as an HTML tag (a "<" before a letter)';
127
+ // PlainText decodes an entity before it escapes the text again, so `&lt;` (or `&#60`, `&amp`) would come back as
128
+ // another character. Every entity name has at least two characters, so `Q&A` and `R&D` stay as written.
129
+ if (/&(#|[A-Za-z]{2})/.test(t))
130
+ return 'has "&" right before "#" or a word, which GitHub reads as an HTML character reference';
131
+ // The projector keeps 400 characters of the title as the server answers it, escaped.
132
+ if (t.replace(/&/g, '&amp;').replace(/[<>]/g, '&lt;').length > 400)
133
+ return 'is too long once GitHub escapes its "&", "<" and ">"';
134
+ if (/^\s*```/.test(t))
135
+ return 'starts with a code fence';
136
+ if (t.includes(PARENT))
137
+ return `has the text ${PARENT}, which crew uses for the parent issue`;
138
+ return null;
139
+ }
140
+ /** The footer every body ends with: a visible line and a marker naming the run and the item. */
141
+ export function publishFooter(runId, key) {
142
+ return `\n\n---\nPublished by wicked-crew from run ${runId}\n<!-- wicked-publish run=${runId} key=${key} -->`;
143
+ }
144
+ /** The card's items from a plan, or the first item that cannot be published as written. */
145
+ export function publishItems(runId, plan, facts) {
146
+ const selected = new Set(facts.requirements.map((r) => `${r.repoId}\u0000${r.key}`));
147
+ const covered = new Set();
148
+ const items = [];
149
+ const title = (key, raw) => {
150
+ const t = oneLine(normal(raw));
151
+ if (t === '')
152
+ return { error: `${key} has an empty title` };
153
+ const why = titleRefusal(t);
154
+ return why === null ? t : { error: `the title of ${key} ${why}` };
155
+ };
156
+ const text = (key, raw) => {
157
+ const t = oneLine(normal(raw));
158
+ const c = strippedCharacter(t);
159
+ if (c !== null)
160
+ return { error: `${key} has an invisible character (${c}) that GitHub's server removes` };
161
+ if (t.includes(PARENT))
162
+ return { error: `${key} has the text ${PARENT}, which crew uses for the parent issue` };
163
+ return t;
164
+ };
165
+ const push = (key, kind, t, lines, parentKey) => {
166
+ const body = `${lines.join('\n')}${parentKey !== null ? `\n\nPart of ${PARENT}` : ''}${publishFooter(runId, key)}`;
167
+ if (body.split(PARENT).join(PARENT_REF_MAX).length > PUBLISH_BODY_MAX)
168
+ return `${kind} ${key} is too long to publish`;
169
+ items.push({ key, kind, title: t, body, parentKey });
170
+ return null;
171
+ };
172
+ for (const [ei, epic] of plan.epics.entries()) {
173
+ const ek = `e${ei + 1}`;
174
+ const et = title(ek, epic.title);
175
+ if (typeof et !== 'string')
176
+ return { ok: false, ...et };
177
+ const ftitles = [];
178
+ for (const [fi, f] of epic.features.entries()) {
179
+ const ft = title(`${ek}.f${fi + 1}`, f.title);
180
+ if (typeof ft !== 'string')
181
+ return { ok: false, ...ft };
182
+ ftitles.push(ft);
183
+ }
184
+ const eerr = push(ek, 'epic', et, ftitles.length === 0 ? ['This epic has no features yet.'] : ['Features:', ...ftitles.map((t) => `- ${t}`)], null);
185
+ if (eerr !== null)
186
+ return { ok: false, error: eerr };
187
+ for (const [fi, f] of epic.features.entries()) {
188
+ const fk = `${ek}.f${fi + 1}`;
189
+ for (const r of f.requirementRefs) {
190
+ const id = `${r.repoId}\u0000${r.key}`;
191
+ if (!selected.has(id))
192
+ return { ok: false, error: `${fk} names requirement ${r.repoId} ${r.key}, which this compose was not given` };
193
+ covered.add(id);
194
+ }
195
+ if (facts.level === 'epics' && (f.stories ?? []).length > 0)
196
+ return { ok: false, error: `${fk} has stories, but this compose drafted epics and features only` };
197
+ const refLines = [];
198
+ for (const r of f.requirementRefs) {
199
+ const t = text(`${fk} (requirement ${r.repoId} ${r.key})`, `${r.repoId} ${r.key}`);
200
+ if (typeof t !== 'string')
201
+ return { ok: false, ...t };
202
+ refLines.push(`- ${t}`);
203
+ }
204
+ const ferr = push(fk, 'feature', ftitles[fi], ['Requirements:', ...refLines], ek);
205
+ if (ferr !== null)
206
+ return { ok: false, error: ferr };
207
+ for (const [si, s] of (f.stories ?? []).entries()) {
208
+ const sk = `${fk}.s${si + 1}`;
209
+ if (facts.level !== 'tasks' && (s.tasks ?? []).length > 0)
210
+ return { ok: false, error: `${sk} has tasks, but this compose drafted ${facts.level} only` };
211
+ const st = title(sk, s.title);
212
+ if (typeof st !== 'string')
213
+ return { ok: false, ...st };
214
+ const lines = ['Acceptance criteria:'];
215
+ if (s.acceptance.length === 0)
216
+ lines.push('- [ ] (none given)');
217
+ for (const a of s.acceptance) {
218
+ const t = text(sk, a);
219
+ if (typeof t !== 'string')
220
+ return { ok: false, ...t };
221
+ lines.push(`- [ ] ${t}`);
222
+ }
223
+ if ((s.tasks ?? []).length > 0) {
224
+ lines.push('', 'Tasks:');
225
+ for (const [ti, task] of (s.tasks ?? []).entries()) {
226
+ const tt = title(`${sk} task ${ti + 1}`, task.title);
227
+ if (typeof tt !== 'string')
228
+ return { ok: false, ...tt };
229
+ lines.push(`- [ ] ${tt}`);
230
+ }
231
+ }
232
+ const serr = push(sk, 'story', st, lines, fk);
233
+ if (serr !== null)
234
+ return { ok: false, error: serr };
235
+ }
236
+ }
237
+ }
238
+ for (const r of facts.requirements)
239
+ if (!covered.has(`${r.repoId}\u0000${r.key}`))
240
+ return { ok: false, error: `no feature covers requirement ${r.repoId} ${r.key}, which this compose was given` };
241
+ if (items.length > PUBLISH_ITEMS_MAX)
242
+ return { ok: false, error: `the plan has ${items.length} items; at most ${PUBLISH_ITEMS_MAX} are published at once` };
243
+ return { ok: true, items };
244
+ }
245
+ /** The ordered publication content, each body a template (`{{parent}}` for the parent's issue). */
246
+ export function contentShaOf(items) {
247
+ return sha256Hex(canonicalJson(items.map((i) => ({ key: i.key, kind: i.kind, title: i.title, body: i.body, parentKey: i.parentKey }))));
248
+ }
249
+ /** One run published to one repository, whatever connector reaches it. */
250
+ export function publicationOf(runId, repo) {
251
+ return sha256Hex(`${runId}\u0000${repo.toLowerCase()}`);
252
+ }
253
+ const sameGate = (g) => typeof g === 'object' && g !== null && canonicalJson(g) === canonicalJson({ human_confirm: { unconditional: true } });
254
+ /**
255
+ * The run's plan as the compose launched it, or why not. Its draft and review units must be the steps the compose
256
+ * recorded (same catalog, same instructions, no amendments), the review the evaluator behind an unconditional human
257
+ * gate; the engine's own units around them (scope, test plan, design) are its to add.
258
+ */
259
+ export async function composedPlan(deps, projectId, runId) {
260
+ const view = await deps.runView(runId);
261
+ if (view === undefined)
262
+ return refuse(404, 'run_not_found', `no run ${runId}`);
263
+ const facts = deps.composeOf(runId);
264
+ if (facts === undefined || facts.projectId !== projectId) {
265
+ return refuse(409, 'not_a_compose', "this run was not composed for this project, or it was composed before publishing was added; compose again to publish");
266
+ }
267
+ // A run still working has no units to judge yet (they appear once its scope is planned): say it is not finished.
268
+ if (view.session.status !== 'completed')
269
+ return refuse(409, 'run_not_finished', `this compose has not finished (it is ${view.session.status}); publish it once its review is confirmed`);
270
+ const unverified = (detail, edited = false) => refuse(409, 'compose_unverified', edited ? EDITED : `crew cannot confirm this is the compose as it was launched (${detail}); compose again to publish`, { detail });
271
+ const draft = view.units.filter((u) => u.id === `${runId}:draft`);
272
+ const review = view.units.filter((u) => u.id === `${runId}:review`);
273
+ if (draft.length !== 1 || review.length !== 1)
274
+ return unverified('the run does not have exactly one draft step and one review step');
275
+ const d = draft[0];
276
+ const r = review[0];
277
+ if (d.ord > r.ord)
278
+ return unverified('the review step runs before the draft step');
279
+ for (const [u, id] of [[d, 'draft'], [r, 'review']]) {
280
+ const step = facts.steps.find((s) => s.id === id);
281
+ if (step === undefined || u.catalog !== step.catalog)
282
+ return unverified(`the ${id} step is not the ${step?.catalog ?? id} step Compose launched`, true);
283
+ if (u.structured_description !== true || typeof u.instructions !== 'string')
284
+ return unverified(`the engine did not record the ${id} step's instructions`);
285
+ if (sha256Hex(u.instructions) !== step.instructionsSha)
286
+ return unverified(`the ${id} step's instructions are not the ones Compose wrote`, true);
287
+ if ((u.amendments ?? []).length > 0)
288
+ return unverified(`the ${id} step was amended`, true);
289
+ }
290
+ if (r.role !== 'evaluator' || !sameGate(r.gate))
291
+ return unverified("the review step is not the evaluator behind a person's confirmation", true);
292
+ if (d.status !== 'done' || r.status !== 'done')
293
+ return unverified('the draft or its review did not finish');
294
+ const out = await deps.workOutput(`${runId}:draft`);
295
+ if (out === null || out.trim() === '')
296
+ return refuse(409, 'plan_unreadable', 'the draft step left no output to publish');
297
+ const block = lastJsonBlock(out);
298
+ if (block === null)
299
+ return refuse(409, 'plan_unreadable', 'the draft does not end with a ```json plan block');
300
+ let raw;
301
+ try {
302
+ raw = JSON.parse(block);
303
+ }
304
+ catch {
305
+ return refuse(409, 'plan_unreadable', "the draft's plan block is not valid JSON");
306
+ }
307
+ const parsed = PlanSchema.safeParse(raw);
308
+ if (!parsed.success) {
309
+ const why = parsed.error.issues.slice(0, 3).map((i) => `${i.path.join('.') || 'plan'}: ${i.message}`).join('; ');
310
+ return refuse(409, 'plan_unreadable', `the draft's plan is not the shape Compose asks for (${why})`);
311
+ }
312
+ const items = publishItems(runId, parsed.data, facts);
313
+ if (!items.ok)
314
+ return refuse(409, 'plan_unreadable', items.error);
315
+ return { ok: true, facts, items: items.items };
316
+ }
317
+ // ── The journal ────────────────────────────────────────────────────────────────────────────────────────
318
+ const ItemSchema = z.strictObject({ key: z.string().min(1).max(40), kind: z.enum(['epic', 'feature', 'story']), title: z.string(), body: z.string(), parentKey: z.string().nullable() });
319
+ const CardSchema = z.strictObject({ runId: z.string(), projectId: z.string(), repo: z.string(), source: z.string(), identity: z.string(), items: z.array(ItemSchema).min(1).max(PUBLISH_ITEMS_MAX) });
320
+ const Envelope = { v: z.literal(1), publication: z.string(), runId: z.string(), projectId: z.string(), repo: z.string(), at: z.string(), by: z.string() };
321
+ const LineSchema = z.discriminatedUnion('kind', [
322
+ z.strictObject({ ...Envelope, kind: z.literal('approved'), publishHash: z.string(), contentSha: z.string(), card: CardSchema, sourceId: z.string(), trackerId: z.string(), descriptor: z.string(), principal: z.string() }),
323
+ z.strictObject({ ...Envelope, kind: z.literal('sending'), key: z.string() }),
324
+ z.strictObject({ ...Envelope, kind: z.literal('created'), key: z.string(), number: z.number().int().positive(), url: z.string() }),
325
+ z.strictObject({ ...Envelope, kind: z.literal('not_sent'), key: z.string(), reason: z.string() }),
326
+ z.strictObject({ ...Envelope, kind: z.literal('unsure'), key: z.string(), why: z.string() }),
327
+ z.strictObject({ ...Envelope, kind: z.literal('resolved'), key: z.string(), number: z.number().int().positive().nullable(), url: z.string().nullable() }),
328
+ ]);
329
+ class JournalUnreadable extends Error {
330
+ }
331
+ /** Where a publication's journal is. */
332
+ function journalPath(dir, runId, publication) {
333
+ return join(dir, 'product-publish', sha256Hex(runId), `${publication}.ndjson`);
334
+ }
335
+ /**
336
+ * Fold one journal. A dangling `sending` (no outcome after it) is `unsure` unless `live` (this daemon is sending it
337
+ * now, read just after the journal). A line cut short by a crash mid-append (it does not end its object: its barrier never returned, so nothing was
338
+ * sent on it, and every line's absence leaves an item no further along) is skipped; any other line crew cannot read
339
+ * throws {@link JournalUnreadable}: a damaged journal is never read as empty.
340
+ */
341
+ async function fold(path, publication, live) {
342
+ let text;
343
+ let sendingNow = false;
344
+ try {
345
+ text = await readFile(path, 'utf8');
346
+ // Read after the journal: a send that started meanwhile shows `sending`, not a stop.
347
+ sendingNow = live();
348
+ }
349
+ catch (err) {
350
+ if (err.code === 'ENOENT')
351
+ return { first: null, last: null, items: new Map() };
352
+ throw new JournalUnreadable(`the publish journal could not be read (${err.code ?? 'error'})`);
353
+ }
354
+ const out = { first: null, last: null, items: new Map() };
355
+ const lines = text.split('\n');
356
+ for (const [i, raw] of lines.entries()) {
357
+ const l = raw.trim();
358
+ if (l === '')
359
+ continue;
360
+ let v;
361
+ try {
362
+ v = JSON.parse(l);
363
+ }
364
+ catch {
365
+ if (!l.endsWith('}'))
366
+ continue; // torn by a crash mid-append (doc)
367
+ throw new JournalUnreadable(`line ${i + 1} of the publish journal does not parse`);
368
+ }
369
+ const p = LineSchema.safeParse(v);
370
+ if (!p.success || p.data.publication !== publication)
371
+ throw new JournalUnreadable(`line ${i + 1} of the publish journal is not one crew wrote for this publication`);
372
+ const line = p.data;
373
+ if (line.kind === 'approved') {
374
+ if (out.first === null)
375
+ out.first = line;
376
+ out.last = line;
377
+ continue;
378
+ }
379
+ if (out.first === null || !out.first.card.items.some((x) => x.key === line.key))
380
+ throw new JournalUnreadable(`line ${i + 1} of the publish journal names an item no approval lists`);
381
+ const s = line.kind === 'sending' ? { state: 'sending', number: null, url: null, why: null }
382
+ : line.kind === 'created' ? { state: 'created', number: line.number, url: line.url, why: null }
383
+ : line.kind === 'not_sent' ? { state: 'not_sent', number: null, url: null, why: line.reason }
384
+ : line.kind === 'unsure' ? { state: 'unsure', number: null, url: null, why: line.why }
385
+ : line.number === null ? { state: 'absent', number: null, url: null, why: null }
386
+ : { state: 'created', number: line.number, url: line.url, why: null };
387
+ out.items.set(line.key, s);
388
+ }
389
+ if (!sendingNow) {
390
+ for (const [k, s] of out.items) {
391
+ if (s.state === 'sending')
392
+ out.items.set(k, { state: 'unsure', number: null, url: null, why: 'crew stopped after sending it and before it could record the answer' });
393
+ }
394
+ }
395
+ return out;
396
+ }
397
+ // ── Read-back ──────────────────────────────────────────────────────────────────────────────────────────
398
+ /** The server's title escaping, read back (`&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, `&#34;`, `&#x27;`), once. */
399
+ const decodeTitle = (s) => s.replace(/&(amp|lt|gt|quot|#39|#34|#x27);/g, (_, e) => ({ amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", '#34': '"', '#x27': "'" })[e] ?? `&${e};`);
400
+ /** A body with its parent reference resolved. */
401
+ const bodyWith = (body, parent) => (parent === null ? body : body.split(PARENT).join(`#${parent}`));
402
+ /** Read one issue of the tracker through its bound read and projector (the reading an agent gets). */
403
+ async function readIssue(pm, e, t, number) {
404
+ const stored = e.record.tools.find((x) => x.name === 'issue_read' && x.present);
405
+ const binding = stored === undefined ? null : bindingInForce('github', stored);
406
+ if (binding === null)
407
+ return { ok: false };
408
+ const [owner, repo] = t.key.split('/');
409
+ const prepared = binding.bindArgs({ method: 'get', owner, repo, issue_number: number }, [{ trackerId: t.trackerId, tenant: t.tenant, key: t.key, siteHost: t.siteHost }]);
410
+ if (!prepared.ok)
411
+ return { ok: false };
412
+ const r = await pm.vendorRead(e, 'issue_read', prepared.args, 'person');
413
+ if (!r.ok)
414
+ return { ok: false };
415
+ const p = binding.project(r.result, prepared, await projectOptsVia(pm, e, r.credential));
416
+ const v = p.ok && p.items.length === 1 ? p.items[0].value : null;
417
+ if (v === null || typeof v['title'] !== 'string' || typeof v['url'] !== 'string')
418
+ return { ok: false };
419
+ return { ok: true, title: decodeTitle(v['title']), body: typeof v['body'] === 'string' ? v['body'] : '', url: v['url'] };
420
+ }
421
+ /** fsync a directory (where the platform can open one). */
422
+ async function syncDir(d) {
423
+ let fh;
424
+ try {
425
+ fh = await open(d, 'r');
426
+ }
427
+ catch (err) {
428
+ if (process.platform === 'win32')
429
+ return;
430
+ throw err;
431
+ }
432
+ try {
433
+ await fh.sync();
434
+ }
435
+ catch (err) {
436
+ if (process.platform !== 'win32')
437
+ throw err;
438
+ }
439
+ finally {
440
+ await fh.close();
441
+ }
442
+ }
443
+ /**
444
+ * Make a journal durable where it lives: its directory (the file's entry), the run's directory and `product-publish/`
445
+ * (their entries), every call, so a retry or a concurrent caller never relies on a sync another one made. Strict: a
446
+ * failure stops the send.
447
+ */
448
+ async function syncChain(path) {
449
+ for (let d = dirname(path), i = 0; i < 3; d = dirname(d), i++)
450
+ await syncDir(d);
451
+ }
452
+ // ── The routes ─────────────────────────────────────────────────────────────────────────────────────────
453
+ const RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
454
+ export const ProductPublishSchema = z
455
+ .strictObject({
456
+ runId: z.string().regex(RUN_ID, 'a run id'),
457
+ repo: z.string().min(3).max(250),
458
+ confirm: z.string().regex(/^[0-9a-f]{64}$/).optional(),
459
+ resolve: z
460
+ .strictObject({
461
+ key: z.string().regex(/^e[1-9][0-9]{0,2}(\.f[1-9][0-9]{0,2}(\.s[1-9][0-9]{0,2})?)?$/, 'an item key (e1, e1.f2, e1.f2.s3)'),
462
+ issue: z.number().int().min(1).max(9_999_999_999).nullable(),
463
+ })
464
+ .optional(),
465
+ })
466
+ .refine((b) => b.confirm === undefined || b.resolve === undefined, { error: 'confirm and resolve are separate requests' });
467
+ /**
468
+ * Codes `vendorRead` answers before anything is sent, from crew's own state: the only outcomes that prove an issue was
469
+ * not created. (`changed` too, but only when publish's own admission refused it: see `revoked`.)
470
+ */
471
+ const NOT_SENT = new Set(['source_off', 'busy', 'rate_limited', 'remote_work_pending', 'secret_missing', 'credential_changed', 'gh_not_installed', 'gh_signed_out', 'gh_token_unavailable']);
472
+ /** How long an issue read back as matching is trusted before it is read again (crew#1911). */
473
+ export const READ_BACK_FRESH_MS = 60_000;
474
+ export function registerProductPublishRoutes(app, deps) {
475
+ /** Publications being sent or resolved now, taken before the first await (DES Send step 1). */
476
+ const slots = new Set();
477
+ /**
478
+ * (crew#1911) The last read-back of each created issue, by publication and item key, for the number and content it
479
+ * was read against. Who reads GitHub:
480
+ * - the slot owner (a send or resolve) reads each issue without a fresh `ok` read-back, the send right after each
481
+ * create, in turn with its creates;
482
+ * - an observer (a GET, a card, a refusal outside the slot) reads one only while no publication is being sent or
483
+ * resolved in this daemon, and a new slot waits for observer reads already running to finish. While a slot is held an
484
+ * observer answers the last read-back, or `null` (not checked yet) for an issue not read yet (crew#1919).
485
+ * So a panel's polling never queues reads beside a create on the source's scheduler (knowledge/gate/scheduler.ts
486
+ * refuses a full queue `busy`), for this publication or another on the same source.
487
+ */
488
+ const readBacks = new Map();
489
+ // Monotonic (crew#1919): a wall clock stepped back never keeps a read-back fresh. `now` is the tests' clock.
490
+ const clock = () => (deps.now !== undefined ? deps.now() : performance.now());
491
+ /** Observer reads running now, and the slots waiting for them to finish. */
492
+ let observing = 0;
493
+ const drained = [];
494
+ const dir = () => deps.journalDir ?? mcpStateDir();
495
+ const nowIso = () => new Date((deps.now ?? Date.now)()).toISOString();
496
+ const humanOnly = (actor) => ({
497
+ error: actor.kind === 'human' ? `publishing to a tracker needs operator trust; you are ${actor.trust}` : `only a person publishes to a tracker; you are ${actor.kind}/${actor.trust}`,
498
+ code: 'publish_human_only',
499
+ });
500
+ const allowed = (actor) => actor.kind === 'human' && trustAtLeast(actor, 'operator');
501
+ const send = (reply, r) => reply.code(r.status).send({ error: r.error, code: r.code, ...(r.extra ?? {}) });
502
+ async function entries() {
503
+ if (deps.store === undefined || deps.pm === undefined)
504
+ return refuse(503, 'registry_unavailable', 'this daemon has no tracker registry');
505
+ try {
506
+ return pmEntriesOf(await deps.store.read());
507
+ }
508
+ catch {
509
+ return refuse(503, 'registry_unavailable', 'the tracker registry could not be read now');
510
+ }
511
+ }
512
+ /** One created issue read back against what was sent, or the last read-back of it when that is trusted for `reads`. */
513
+ async function readBackOf(publication, reader, it, number, parent, reads) {
514
+ const expectBody = normal(bodyWith(it.body, parent));
515
+ const expect = sha256Hex(`${it.title}\u0000${expectBody}`);
516
+ const key = `${publication}\u0000${it.key}`;
517
+ const memo = readBacks.get(key);
518
+ const known = memo !== undefined && memo.number === number && memo.expect === expect ? memo : undefined;
519
+ if (known !== undefined && known.readBack === 'ok' && clock() - known.at < READ_BACK_FRESH_MS)
520
+ return { readBack: 'ok', url: known.url };
521
+ // Checked before every read, not once per answer: a slot taken meanwhile stops this observer's next read.
522
+ // One not read yet is not checked yet (null), never `unreadable`, which reads as deleted (crew#1919).
523
+ if (reads === 'observer' && slots.size > 0)
524
+ return known !== undefined ? { readBack: known.readBack, url: known.url } : { readBack: null, url: null };
525
+ let read;
526
+ if (reader === null)
527
+ read = { ok: false };
528
+ else if (reads === 'owner')
529
+ read = await readIssue(deps.pm, reader.e, reader.t, number);
530
+ else {
531
+ observing++;
532
+ try {
533
+ read = await readIssue(deps.pm, reader.e, reader.t, number);
534
+ }
535
+ finally {
536
+ if (--observing === 0)
537
+ for (const w of drained.splice(0))
538
+ w();
539
+ }
540
+ }
541
+ const readBack = !read.ok ? 'unreadable' : read.title === it.title && read.body === expectBody ? 'ok' : 'differs';
542
+ const url = read.ok ? read.url : null;
543
+ readBacks.set(key, { number, expect, readBack, url, at: clock() });
544
+ return { readBack, url };
545
+ }
546
+ /** A publication's state now: its journal, each created issue read back as {@link readBackOf} allows `reads`. */
547
+ async function stateOf(f, projectId, sel, es, reads) {
548
+ const approved = f.last;
549
+ const card = f.first.card;
550
+ let reader = null;
551
+ if (es !== null) {
552
+ const adm = projectGithubTracker(es, projectId, { source: approved.card.source, repo: sel.repo });
553
+ if (adm.ok && adm.e.id === approved.sourceId)
554
+ reader = { e: adm.e, t: adm.t };
555
+ }
556
+ const numbers = new Map();
557
+ for (const [k, s] of f.items)
558
+ if (s.state === 'created' && s.number !== null)
559
+ numbers.set(k, s.number);
560
+ const items = [];
561
+ for (const it of card.items) {
562
+ const s = f.items.get(it.key);
563
+ const state = s?.state ?? 'missing';
564
+ let readBack = null;
565
+ let url = s?.url ?? null;
566
+ if (state === 'created' && s.number !== null) {
567
+ const parent = it.parentKey === null ? null : (numbers.get(it.parentKey) ?? null);
568
+ const got = await readBackOf(f.first.publication, reader, it, s.number, parent, reads);
569
+ readBack = got.readBack;
570
+ if (got.url !== null)
571
+ url = got.url;
572
+ }
573
+ items.push({ key: it.key, kind: it.kind, title: it.title, state, number: s?.number ?? null, url, readBack, ...(s?.why != null ? { why: s.why } : {}) });
574
+ }
575
+ return { repo: card.repo, source: approved.card.source, publishHash: approved.publishHash, items, published: items.every((i) => i.state === 'created' && i.readBack === 'ok') };
576
+ }
577
+ /** The card for `sel` built NOW (DES "The card"), or why there is none. */
578
+ async function build(projectId, runId, sel, holding) {
579
+ if (!(await deps.projectExists(projectId)))
580
+ return refuse(404, 'project_not_found', `no project ${projectId}`);
581
+ const plan = await composedPlan(deps, projectId, runId);
582
+ if (!plan.ok)
583
+ return plan;
584
+ const es = await entries();
585
+ if (!Array.isArray(es))
586
+ return es;
587
+ const adm = projectGithubTracker(es, projectId, sel);
588
+ if (!adm.ok)
589
+ return refuse(adm.code === 'ambiguous' ? 409 : 404, adm.code, adm.error);
590
+ const { e, t } = adm;
591
+ if (!liveTool(e.record.tools.find((x) => x.name === 'issue_write' && x.present))) {
592
+ return refuse(409, 'write_tool_off', `${e.name} has no saved, switched-on issue_write tool: a person grants it on the source's sheet`);
593
+ }
594
+ const publication = publicationOf(runId, t.key);
595
+ const path = journalPath(dir(), runId, publication);
596
+ let f;
597
+ try {
598
+ f = await fold(path, publication, holding ? () => false : () => slots.has(publication));
599
+ }
600
+ catch (err) {
601
+ if (err instanceof JournalUnreadable)
602
+ return refuse(409, 'journal_unreadable', `${err.message}; nothing is sent until it is repaired`);
603
+ throw err;
604
+ }
605
+ const contentSha = contentShaOf(plan.items);
606
+ if (f.first !== null && f.first.contentSha !== contentSha) {
607
+ return refuse(409, 'publication_differs', `this run was already published to ${t.key} with other content; nothing more is sent to it`, { publication: await stateOf(f, projectId, sel, es, holding ? 'owner' : 'observer') });
608
+ }
609
+ const who = await deps.pm.vendorRead(e, 'get_me', {}, 'person');
610
+ const me = who.ok ? readPayload(who.result, e.name, 'github') : null;
611
+ const m = me !== null && me.ok && typeof me.payload === 'object' && me.payload !== null ? me.payload : null;
612
+ const identity = m !== null && typeof m['login'] === 'string' && m['login'] !== '' ? m['login'] : null;
613
+ if (identity === null || !who.ok)
614
+ return refuse(503, 'source_unavailable', `${e.name} could not say which account it posts as now, so no card is offered`);
615
+ if (who.credential === null)
616
+ return refuse(409, 'credential_unpinned', `${e.name} has no credential of its own to pin, so crew cannot be sure which account would post; give the source its own credential`);
617
+ const principal = String(m['id'] ?? identity);
618
+ const card = { runId, projectId, repo: t.key.toLowerCase(), source: e.name, identity, items: plan.items };
619
+ const descriptor = pmDescriptorHash(configOf(e.record));
620
+ const publishHash = sha256Hex(canonicalJson({ v: 1, card, contentSha, sourceId: e.id, trackerId: t.trackerId, descriptor, principal, credential: who.credential }));
621
+ return { ok: true, b: { card, publishHash, contentSha, e, t, descriptor, principal, credential: who.credential, es, f, publication, path } };
622
+ }
623
+ const envelope = (b, actor) => ({ v: 1, publication: b.publication, runId: b.runId, projectId: b.projectId, repo: b.repo, at: nowIso(), by: actor.id });
624
+ const write = async (path, line) => {
625
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
626
+ await (deps.appendLine ?? appendLineSynced)(path, `${JSON.stringify(line)}\n`, 0o600);
627
+ };
628
+ async function confirm(projectId, runId, sel, hash, actor, log) {
629
+ const built = await build(projectId, runId, sel, true);
630
+ if (!built.ok)
631
+ return built;
632
+ const b = built.b;
633
+ if ([...b.f.items.values()].some((s) => s.state === 'unsure')) {
634
+ return refuse(409, 'unresolved', 'an earlier publish could not tell whether some issues were created; say for each whether it exists (resolve) before publishing again', { publication: await stateOf(b.f, projectId, sel, b.es, 'owner') });
635
+ }
636
+ if (hash !== b.publishHash) {
637
+ return refuse(409, 'card_changed', 'the card changed since it was shown (the plan, the account, the source or the link); nothing was sent: look at it again', { card: b.card, publishHash: b.publishHash });
638
+ }
639
+ const env = { publication: b.publication, runId, projectId, repo: b.card.repo };
640
+ try {
641
+ await write(b.path, { ...envelope(env, actor), kind: 'approved', publishHash: b.publishHash, contentSha: b.contentSha, card: b.card, sourceId: b.e.id, trackerId: b.t.trackerId, descriptor: b.descriptor, principal: b.principal });
642
+ await (deps.syncJournalDirs ?? syncChain)(b.path);
643
+ }
644
+ catch (err) {
645
+ log.warn(`[publish] the approval for ${runId} could not be recorded: ${err instanceof Error ? err.message : String(err)}`);
646
+ return refuse(503, 'journal_unavailable', 'crew could not record the approval, so nothing was sent');
647
+ }
648
+ /** Whether THIS item's admission was refused here (a `changed` answer proves nothing was sent only then). */
649
+ let revoked = false;
650
+ /** Immediately before each create, with the source's slot taken: still this project's tracker, unchanged, writable. */
651
+ const admittedFor = async () => {
652
+ const e = await admission();
653
+ if (e === null)
654
+ revoked = true;
655
+ return e;
656
+ };
657
+ const admission = async () => {
658
+ try {
659
+ const es = pmEntriesOf(await deps.store.read());
660
+ const adm = projectGithubTracker(es, projectId, sel);
661
+ if (!adm.ok || adm.e.id !== b.e.id || adm.t.trackerId !== b.t.trackerId || !adm.e.enabled)
662
+ return null;
663
+ if (pmDescriptorHash(configOf(adm.e.record)) !== b.descriptor)
664
+ return null;
665
+ if (!liveTool(adm.e.record.tools.find((x) => x.name === 'issue_write' && x.present)))
666
+ return null;
667
+ return adm.e;
668
+ }
669
+ catch {
670
+ return null;
671
+ }
672
+ };
673
+ const numbers = new Map();
674
+ for (const [k, s] of b.f.items)
675
+ if (s.state === 'created' && s.number !== null)
676
+ numbers.set(k, s.number);
677
+ const tally = { created: 0, refused: 0, unsure: 0 };
678
+ const [owner, repo] = b.t.key.split('/');
679
+ for (const it of b.card.items) {
680
+ if (numbers.has(it.key))
681
+ continue;
682
+ const parent = it.parentKey === null ? null : (numbers.get(it.parentKey) ?? null);
683
+ if (it.parentKey !== null && parent === null)
684
+ break;
685
+ try {
686
+ await write(b.path, { ...envelope(env, actor), kind: 'sending', key: it.key });
687
+ }
688
+ catch (err) {
689
+ log.warn(`[publish] the send of ${it.key} could not be recorded, so it was not sent: ${err instanceof Error ? err.message : String(err)}`);
690
+ break;
691
+ }
692
+ revoked = false;
693
+ const r = await deps.pm.vendorRead(b.e, 'issue_write', { method: 'create', owner, repo, title: it.title, body: bodyWith(it.body, parent) }, 'person', admittedFor, b.credential);
694
+ let outcome;
695
+ // `changed` is a refusal before dispatch only when this admission said so: never read from the vendor's words.
696
+ if (!r.ok && (r.code === 'changed' ? revoked : NOT_SENT.has(r.code))) {
697
+ outcome = { kind: 'not_sent', key: it.key, reason: r.reason };
698
+ tally.refused++;
699
+ }
700
+ else {
701
+ const a = r.ok ? readPayload(r.result, b.e.name, 'github') : null;
702
+ const p = a !== null && a.ok && typeof a.payload === 'object' && a.payload !== null ? a.payload : null;
703
+ const url = p === null ? null : p['url'];
704
+ const id = githubUrlIdentity(url);
705
+ if (id !== null && /^https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/[1-9][0-9]{0,9}$/.test(String(url)) && id.repo === b.t.key.toLowerCase()) {
706
+ outcome = { kind: 'created', key: it.key, number: id.number, url };
707
+ numbers.set(it.key, id.number);
708
+ tally.created++;
709
+ }
710
+ else {
711
+ const why = !r.ok
712
+ ? `${r.reason}; GitHub may have created it`
713
+ : a !== null && !a.ok && a.code === 'vendor_error'
714
+ ? `GitHub answered an error, which it also does after it created an issue (${a.reason})`
715
+ : 'GitHub answered in a shape crew could not read as this repository\'s new issue';
716
+ outcome = { kind: 'unsure', key: it.key, why };
717
+ tally.unsure++;
718
+ }
719
+ }
720
+ try {
721
+ await write(b.path, { ...envelope(env, actor), ...outcome });
722
+ }
723
+ catch (err) {
724
+ log.warn(`[publish] the outcome of ${it.key} could not be recorded; sending stops: ${err instanceof Error ? err.message : String(err)}`);
725
+ break;
726
+ }
727
+ if (outcome['kind'] !== 'created')
728
+ break;
729
+ // (crew#1911) Read it back now, inside the slot and in turn with the creates, so no GET has to.
730
+ await readBackOf(b.publication, { e: b.e, t: b.t }, it, outcome['number'], parent, 'owner');
731
+ }
732
+ let f;
733
+ try {
734
+ f = await fold(b.path, b.publication, () => false);
735
+ }
736
+ catch (err) {
737
+ if (err instanceof JournalUnreadable)
738
+ return refuse(409, 'journal_unreadable', `${err.message}; nothing more is sent until it is repaired`);
739
+ throw err;
740
+ }
741
+ const publication = await stateOf(f, projectId, sel, b.es, 'owner');
742
+ deps.audit.record('product.publish', actor, { runId, detail: { projectId, repo: b.card.repo, source: b.e.name, identity: b.card.identity, ...tally, published: publication.published } });
743
+ return { ok: true, body: { done: true, card: b.card, publication } };
744
+ }
745
+ async function resolve(projectId, runId, sel, want, actor) {
746
+ if (!(await deps.projectExists(projectId)))
747
+ return refuse(404, 'project_not_found', `no project ${projectId}`);
748
+ const es = await entries();
749
+ if (!Array.isArray(es))
750
+ return es;
751
+ const publication = publicationOf(runId, sel.repo);
752
+ const path = journalPath(dir(), runId, publication);
753
+ let f;
754
+ try {
755
+ f = await fold(path, publication, () => false);
756
+ }
757
+ catch (err) {
758
+ if (err instanceof JournalUnreadable)
759
+ return refuse(409, 'journal_unreadable', `${err.message}; nothing is changed until it is repaired`);
760
+ throw err;
761
+ }
762
+ if (f.first === null || f.first.projectId !== projectId)
763
+ return refuse(409, 'not_unsure', `this run has no publication to ${sel.repo} in this project`);
764
+ const s = f.items.get(want.key);
765
+ const it = f.first.card.items.find((x) => x.key === want.key);
766
+ if (it === undefined || s === undefined || s.state !== 'unsure')
767
+ return refuse(409, 'not_unsure', `${want.key} is not waiting to be resolved (it is ${s?.state ?? (it === undefined ? 'not an item of this publication' : 'missing')})`);
768
+ const env = { publication, runId, projectId, repo: f.first.card.repo };
769
+ let line;
770
+ if (want.issue === null) {
771
+ line = { ...envelope(env, actor), kind: 'resolved', key: it.key, number: null, url: null };
772
+ }
773
+ else {
774
+ const adm = projectGithubTracker(es, projectId, { source: f.last.card.source, repo: sel.repo });
775
+ if (!adm.ok || adm.e.id !== f.last.sourceId)
776
+ return refuse(adm.ok ? 404 : adm.code === 'ambiguous' ? 409 : 404, adm.ok ? 'repo_not_linked' : adm.code, adm.ok ? `${sel.repo} is no longer reached through ${f.last.card.source}` : adm.error);
777
+ const read = await readIssue(deps.pm, adm.e, adm.t, want.issue);
778
+ if (!read.ok)
779
+ return refuse(503, 'source_unavailable', `${adm.e.name} could not read #${want.issue} now`);
780
+ const numbers = new Map();
781
+ for (const [k, x] of f.items)
782
+ if (x.state === 'created' && x.number !== null)
783
+ numbers.set(k, x.number);
784
+ const parent = it.parentKey === null ? null : (numbers.get(it.parentKey) ?? null);
785
+ if (read.title !== it.title || read.body !== normal(bodyWith(it.body, parent))) {
786
+ return refuse(409, 'resolve_differs', `#${want.issue} is not ${it.key}: its title or body is not what was approved for it`);
787
+ }
788
+ line = { ...envelope(env, actor), kind: 'resolved', key: it.key, number: want.issue, url: read.url };
789
+ }
790
+ try {
791
+ await write(path, line);
792
+ }
793
+ catch {
794
+ return refuse(503, 'journal_unavailable', 'crew could not record the answer; nothing changed');
795
+ }
796
+ deps.audit.record('product.publish.resolve', actor, { runId, detail: { projectId, repo: f.first.card.repo, key: it.key, issue: want.issue } });
797
+ const after = await fold(path, publication, () => false);
798
+ return { ok: true, body: { done: true, card: after.last.card, publication: await stateOf(after, projectId, sel, es, 'owner') } };
799
+ }
800
+ app.post(`${V}/projects/:id/product/publish`, { config: { manifest: { requestType: 'ProductPublishBody', responseType: 'ProductPublishResponse', statusCodes: [200, 400, 403, 404, 409, 503] } } }, async (req, reply) => {
801
+ const actor = deps.actorOf(req);
802
+ if (!allowed(actor))
803
+ return reply.code(403).send(humanOnly(actor));
804
+ const parsed = ProductPublishSchema.safeParse(req.body);
805
+ if (!parsed.success)
806
+ return reply.code(400).send({ error: parsed.error.issues.map((i) => `${i.path.join('.') || 'body'}: ${i.message}`).join('; '), code: 'bad_request' });
807
+ const sel = parseRepoSelector(parsed.data.repo);
808
+ if (sel === null)
809
+ return reply.code(400).send({ error: 'repo: owner/repo, or <source>:owner/repo', code: 'bad_request' });
810
+ const { runId, confirm: hash, resolve: want } = parsed.data;
811
+ const projectId = req.params.id;
812
+ if (hash === undefined && want === undefined) {
813
+ // (crew#1911) A card asks GitHub which account posts (`get_me`): an observer read, so none while anything is
814
+ // being sent or resolved here, and a slot taken meanwhile waits for it.
815
+ if (slots.size > 0)
816
+ return reply.code(409).send({ error: 'a publish is being sent or resolved right now; ask for the card again in a moment', code: 'in_progress' });
817
+ observing++;
818
+ try {
819
+ const built = await build(projectId, runId, sel, false);
820
+ if (!built.ok)
821
+ return send(reply, built);
822
+ const b = built.b;
823
+ const answer = { done: false, card: b.card, publishHash: b.publishHash, publication: b.f.first === null ? null : await stateOf(b.f, projectId, sel, b.es, 'observer') };
824
+ return answer;
825
+ }
826
+ finally {
827
+ if (--observing === 0)
828
+ for (const w of drained.splice(0))
829
+ w();
830
+ }
831
+ }
832
+ // Taken synchronously, before any await: a second send or resolve of this publication is refused here.
833
+ const slot = publicationOf(runId, sel.repo);
834
+ if (slots.has(slot))
835
+ return reply.code(409).send({ error: 'this publication is being sent or resolved right now; look again in a moment', code: 'in_progress' });
836
+ slots.add(slot);
837
+ let out;
838
+ // Released BEFORE the answer is sent: a client that acts on the answer at once finds the publication free.
839
+ try {
840
+ // (crew#1911) No observer read starts once a slot is held; wait for any already on the source's queue.
841
+ while (observing > 0)
842
+ await new Promise((r) => drained.push(r));
843
+ out = want !== undefined ? await resolve(projectId, runId, sel, want, actor) : await confirm(projectId, runId, sel, hash, actor, req.log);
844
+ }
845
+ finally {
846
+ slots.delete(slot);
847
+ }
848
+ if (!out.ok)
849
+ return send(reply, out);
850
+ return out.body;
851
+ });
852
+ app.get(`${V}/projects/:id/product/publish/:runId`, { config: { manifest: { responseType: 'ProductPublicationsResponse', statusCodes: [200, 400, 403, 404, 409, 503] } } }, async (req, reply) => {
853
+ const actor = deps.actorOf(req);
854
+ if (!allowed(actor))
855
+ return reply.code(403).send(humanOnly(actor));
856
+ const { id: projectId, runId } = req.params;
857
+ if (!RUN_ID.test(runId))
858
+ return reply.code(400).send({ error: 'runId: a run id', code: 'bad_request' });
859
+ if (!(await deps.projectExists(projectId)))
860
+ return reply.code(404).send({ error: `no project ${projectId}`, code: 'project_not_found' });
861
+ const plan = await composedPlan(deps, projectId, runId);
862
+ if (!plan.ok && plan.code === 'run_not_found')
863
+ return send(reply, plan);
864
+ const es = await entries();
865
+ if (!Array.isArray(es))
866
+ return send(reply, es);
867
+ const list = es;
868
+ const runDir = join(dir(), 'product-publish', sha256Hex(runId));
869
+ let files = [];
870
+ try {
871
+ files = (await readdir(runDir)).filter((n) => /^[0-9a-f]{64}\.ndjson$/.test(n)).sort();
872
+ }
873
+ catch (err) {
874
+ if (err.code !== 'ENOENT')
875
+ return reply.code(503).send({ error: 'the publish journal could not be read now', code: 'journal_unavailable' });
876
+ }
877
+ const publications = [];
878
+ for (const n of files) {
879
+ const publication = n.slice(0, 64);
880
+ let f;
881
+ try {
882
+ f = await fold(join(runDir, n), publication, () => slots.has(publication));
883
+ }
884
+ catch (err) {
885
+ if (err instanceof JournalUnreadable)
886
+ return reply.code(409).send({ error: `${err.message}; nothing is sent until it is repaired`, code: 'journal_unreadable' });
887
+ throw err;
888
+ }
889
+ if (f.first === null || f.first.projectId !== projectId || f.first.runId !== runId)
890
+ continue;
891
+ publications.push(await stateOf(f, projectId, { source: null, repo: f.first.card.repo }, list, 'observer'));
892
+ }
893
+ const answer = {
894
+ runId,
895
+ publishable: plan.ok ? { ok: true, items: plan.items.length } : { ok: false, code: plan.code, error: plan.error },
896
+ targets: projectGithubTargets(list, projectId),
897
+ publications,
898
+ };
899
+ return answer;
900
+ });
901
+ }
902
+ //# sourceMappingURL=product-publish.js.map