oh-my-copilot 5.18.2 → 5.19.2

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 (326) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +206 -104
  4. package/bridge/__pycache__/gyoshu_bridge.cpython-314.pyc +0 -0
  5. package/bridge/claude-md-coordinator.cjs +2 -2
  6. package/bridge/cli.cjs +7155 -4471
  7. package/bridge/mcp-server.cjs +2470 -1027
  8. package/bridge/runtime-cli.cjs +102 -12
  9. package/bridge/team-mcp.cjs +100 -11
  10. package/bridge/team.js +100 -11
  11. package/dist/budget/ledger.d.ts +5 -0
  12. package/dist/budget/ledger.d.ts.map +1 -1
  13. package/dist/budget/ledger.js +2 -1
  14. package/dist/budget/ledger.js.map +1 -1
  15. package/dist/cli/commands/__tests__/factory-forge-cli.test.js +3 -3
  16. package/dist/cli/commands/__tests__/factory-forge-cli.test.js.map +1 -1
  17. package/dist/cli/commands/__tests__/factory-init.test.js +239 -17
  18. package/dist/cli/commands/__tests__/factory-init.test.js.map +1 -1
  19. package/dist/cli/commands/__tests__/factory-run-cli.test.js +103 -2
  20. package/dist/cli/commands/__tests__/factory-run-cli.test.js.map +1 -1
  21. package/dist/cli/commands/factory-board.d.ts +9 -0
  22. package/dist/cli/commands/factory-board.d.ts.map +1 -0
  23. package/dist/cli/commands/factory-board.js +34 -0
  24. package/dist/cli/commands/factory-board.js.map +1 -0
  25. package/dist/cli/commands/factory-check.d.ts +1 -0
  26. package/dist/cli/commands/factory-check.d.ts.map +1 -1
  27. package/dist/cli/commands/factory-check.js +2 -1
  28. package/dist/cli/commands/factory-check.js.map +1 -1
  29. package/dist/cli/commands/factory-poll.d.ts +9 -0
  30. package/dist/cli/commands/factory-poll.d.ts.map +1 -0
  31. package/dist/cli/commands/factory-poll.js +34 -0
  32. package/dist/cli/commands/factory-poll.js.map +1 -0
  33. package/dist/cli/commands/factory-setup.d.ts +2 -0
  34. package/dist/cli/commands/factory-setup.d.ts.map +1 -1
  35. package/dist/cli/commands/factory-setup.js +9 -3
  36. package/dist/cli/commands/factory-setup.js.map +1 -1
  37. package/dist/cli/commands/factory.d.ts +61 -18
  38. package/dist/cli/commands/factory.d.ts.map +1 -1
  39. package/dist/cli/commands/factory.js +325 -53
  40. package/dist/cli/commands/factory.js.map +1 -1
  41. package/dist/factory/__tests__/check-run.test.js +37 -96
  42. package/dist/factory/__tests__/check-run.test.js.map +1 -1
  43. package/dist/factory/__tests__/enqueue-ado.test.d.ts +2 -0
  44. package/dist/factory/__tests__/enqueue-ado.test.d.ts.map +1 -0
  45. package/dist/factory/__tests__/enqueue-ado.test.js +375 -0
  46. package/dist/factory/__tests__/enqueue-ado.test.js.map +1 -0
  47. package/dist/factory/__tests__/enqueue.test.d.ts +2 -0
  48. package/dist/factory/__tests__/enqueue.test.d.ts.map +1 -0
  49. package/dist/factory/__tests__/enqueue.test.js +470 -0
  50. package/dist/factory/__tests__/enqueue.test.js.map +1 -0
  51. package/dist/factory/__tests__/heal-ado.test.d.ts +2 -0
  52. package/dist/factory/__tests__/heal-ado.test.d.ts.map +1 -0
  53. package/dist/factory/__tests__/heal-ado.test.js +237 -0
  54. package/dist/factory/__tests__/heal-ado.test.js.map +1 -0
  55. package/dist/factory/__tests__/listener.test.js +27 -9
  56. package/dist/factory/__tests__/listener.test.js.map +1 -1
  57. package/dist/factory/__tests__/map-frontier.test.js +68 -0
  58. package/dist/factory/__tests__/map-frontier.test.js.map +1 -1
  59. package/dist/factory/__tests__/map-ingest.test.js +4 -3
  60. package/dist/factory/__tests__/map-ingest.test.js.map +1 -1
  61. package/dist/factory/__tests__/poll-ado.test.d.ts +2 -0
  62. package/dist/factory/__tests__/poll-ado.test.d.ts.map +1 -0
  63. package/dist/factory/__tests__/poll-ado.test.js +263 -0
  64. package/dist/factory/__tests__/poll-ado.test.js.map +1 -0
  65. package/dist/factory/__tests__/poll.test.d.ts +2 -0
  66. package/dist/factory/__tests__/poll.test.d.ts.map +1 -0
  67. package/dist/factory/__tests__/poll.test.js +748 -0
  68. package/dist/factory/__tests__/poll.test.js.map +1 -0
  69. package/dist/factory/board/__tests__/board-ado.test.d.ts +2 -0
  70. package/dist/factory/board/__tests__/board-ado.test.d.ts.map +1 -0
  71. package/dist/factory/board/__tests__/board-ado.test.js +194 -0
  72. package/dist/factory/board/__tests__/board-ado.test.js.map +1 -0
  73. package/dist/factory/board/__tests__/board.test.d.ts +2 -0
  74. package/dist/factory/board/__tests__/board.test.d.ts.map +1 -0
  75. package/dist/factory/board/__tests__/board.test.js +287 -0
  76. package/dist/factory/board/__tests__/board.test.js.map +1 -0
  77. package/dist/factory/board/collect.d.ts +145 -0
  78. package/dist/factory/board/collect.d.ts.map +1 -0
  79. package/dist/factory/board/collect.js +330 -0
  80. package/dist/factory/board/collect.js.map +1 -0
  81. package/dist/factory/board/render.d.ts +12 -0
  82. package/dist/factory/board/render.d.ts.map +1 -0
  83. package/dist/factory/board/render.js +93 -0
  84. package/dist/factory/board/render.js.map +1 -0
  85. package/dist/factory/check/__tests__/ado.test.js +14 -1
  86. package/dist/factory/check/__tests__/ado.test.js.map +1 -1
  87. package/dist/factory/check/__tests__/cli.test.js +38 -0
  88. package/dist/factory/check/__tests__/cli.test.js.map +1 -1
  89. package/dist/factory/check/__tests__/rules.test.js +72 -2
  90. package/dist/factory/check/__tests__/rules.test.js.map +1 -1
  91. package/dist/factory/check/cli.d.ts +34 -6
  92. package/dist/factory/check/cli.d.ts.map +1 -1
  93. package/dist/factory/check/cli.js +56 -34
  94. package/dist/factory/check/cli.js.map +1 -1
  95. package/dist/factory/check/rules.d.ts +11 -3
  96. package/dist/factory/check/rules.d.ts.map +1 -1
  97. package/dist/factory/check/rules.js +18 -5
  98. package/dist/factory/check/rules.js.map +1 -1
  99. package/dist/factory/check/score.d.ts +22 -2
  100. package/dist/factory/check/score.d.ts.map +1 -1
  101. package/dist/factory/check/score.js +55 -1
  102. package/dist/factory/check/score.js.map +1 -1
  103. package/dist/factory/enqueue.d.ts +195 -0
  104. package/dist/factory/enqueue.d.ts.map +1 -0
  105. package/dist/factory/enqueue.js +788 -0
  106. package/dist/factory/enqueue.js.map +1 -0
  107. package/dist/factory/heal/cli.d.ts +34 -2
  108. package/dist/factory/heal/cli.d.ts.map +1 -1
  109. package/dist/factory/heal/cli.js +88 -19
  110. package/dist/factory/heal/cli.js.map +1 -1
  111. package/dist/factory/heal/history.d.ts +12 -6
  112. package/dist/factory/heal/history.d.ts.map +1 -1
  113. package/dist/factory/heal/history.js +16 -6
  114. package/dist/factory/heal/history.js.map +1 -1
  115. package/dist/factory/heal/implement.d.ts +3 -1
  116. package/dist/factory/heal/implement.d.ts.map +1 -1
  117. package/dist/factory/heal/implement.js +1 -0
  118. package/dist/factory/heal/implement.js.map +1 -1
  119. package/dist/factory/heal/run.d.ts +3 -0
  120. package/dist/factory/heal/run.d.ts.map +1 -1
  121. package/dist/factory/heal/run.js +1 -1
  122. package/dist/factory/heal/run.js.map +1 -1
  123. package/dist/factory/listener.d.ts +13 -17
  124. package/dist/factory/listener.d.ts.map +1 -1
  125. package/dist/factory/listener.js +37 -63
  126. package/dist/factory/listener.js.map +1 -1
  127. package/dist/factory/map-frontier.d.ts +8 -1
  128. package/dist/factory/map-frontier.d.ts.map +1 -1
  129. package/dist/factory/map-frontier.js +65 -5
  130. package/dist/factory/map-frontier.js.map +1 -1
  131. package/dist/factory/map-ingest.d.ts.map +1 -1
  132. package/dist/factory/map-ingest.js +12 -1
  133. package/dist/factory/map-ingest.js.map +1 -1
  134. package/dist/factory/poll.d.ts +308 -0
  135. package/dist/factory/poll.d.ts.map +1 -0
  136. package/dist/factory/poll.js +677 -0
  137. package/dist/factory/poll.js.map +1 -0
  138. package/dist/factory/run/__tests__/engine.ado.test.js +157 -8
  139. package/dist/factory/run/__tests__/engine.ado.test.js.map +1 -1
  140. package/dist/factory/run/__tests__/engine.outcome.test.d.ts +2 -0
  141. package/dist/factory/run/__tests__/engine.outcome.test.d.ts.map +1 -0
  142. package/dist/factory/run/__tests__/engine.outcome.test.js +223 -0
  143. package/dist/factory/run/__tests__/engine.outcome.test.js.map +1 -0
  144. package/dist/factory/run/__tests__/engine.test.js +91 -0
  145. package/dist/factory/run/__tests__/engine.test.js.map +1 -1
  146. package/dist/factory/run/__tests__/units.test.js +299 -2
  147. package/dist/factory/run/__tests__/units.test.js.map +1 -1
  148. package/dist/factory/run/engine.d.ts +11 -3
  149. package/dist/factory/run/engine.d.ts.map +1 -1
  150. package/dist/factory/run/engine.js +145 -22
  151. package/dist/factory/run/engine.js.map +1 -1
  152. package/dist/factory/run/exec.d.ts +32 -4
  153. package/dist/factory/run/exec.d.ts.map +1 -1
  154. package/dist/factory/run/exec.js +120 -15
  155. package/dist/factory/run/exec.js.map +1 -1
  156. package/dist/factory/run/outcome.d.ts +31 -0
  157. package/dist/factory/run/outcome.d.ts.map +1 -0
  158. package/dist/factory/run/outcome.js +70 -0
  159. package/dist/factory/run/outcome.js.map +1 -0
  160. package/dist/factory/run/review-output.d.ts +6 -1
  161. package/dist/factory/run/review-output.d.ts.map +1 -1
  162. package/dist/factory/run/review-output.js +13 -3
  163. package/dist/factory/run/review-output.js.map +1 -1
  164. package/dist/factory/run/state.d.ts +2 -0
  165. package/dist/factory/run/state.d.ts.map +1 -1
  166. package/dist/factory/run/state.js.map +1 -1
  167. package/dist/factory/setup/__tests__/pipeline-pick.test.d.ts +2 -0
  168. package/dist/factory/setup/__tests__/pipeline-pick.test.d.ts.map +1 -0
  169. package/dist/factory/setup/__tests__/pipeline-pick.test.js +84 -0
  170. package/dist/factory/setup/__tests__/pipeline-pick.test.js.map +1 -0
  171. package/dist/factory/setup/__tests__/setup.test.js +1 -0
  172. package/dist/factory/setup/__tests__/setup.test.js.map +1 -1
  173. package/dist/factory/setup/detect.js +1 -1
  174. package/dist/factory/setup/detect.js.map +1 -1
  175. package/dist/factory/setup/pipeline-pick.d.ts +25 -0
  176. package/dist/factory/setup/pipeline-pick.d.ts.map +1 -0
  177. package/dist/factory/setup/pipeline-pick.js +55 -0
  178. package/dist/factory/setup/pipeline-pick.js.map +1 -0
  179. package/dist/factory/setup/write.d.ts +6 -0
  180. package/dist/factory/setup/write.d.ts.map +1 -1
  181. package/dist/factory/setup/write.js +3 -1
  182. package/dist/factory/setup/write.js.map +1 -1
  183. package/dist/factory/watchdog.d.ts +3 -2
  184. package/dist/factory/watchdog.d.ts.map +1 -1
  185. package/dist/factory/watchdog.js +5 -4
  186. package/dist/factory/watchdog.js.map +1 -1
  187. package/dist/factory/watchdog.test.js +19 -4
  188. package/dist/factory/watchdog.test.js.map +1 -1
  189. package/dist/forge/__tests__/config.test.js +51 -0
  190. package/dist/forge/__tests__/config.test.js.map +1 -1
  191. package/dist/forge/__tests__/gh-argv-baseline.chain.test.js +2 -2
  192. package/dist/forge/__tests__/gh-argv-baseline.chain.test.js.map +1 -1
  193. package/dist/forge/__tests__/gh-argv-baseline.factory.test.js +6 -4
  194. package/dist/forge/__tests__/gh-argv-baseline.factory.test.js.map +1 -1
  195. package/dist/forge/__tests__/gh-argv-baseline.tracker-writes.test.d.ts +2 -0
  196. package/dist/forge/__tests__/gh-argv-baseline.tracker-writes.test.d.ts.map +1 -0
  197. package/dist/forge/__tests__/gh-argv-baseline.tracker-writes.test.js +100 -0
  198. package/dist/forge/__tests__/gh-argv-baseline.tracker-writes.test.js.map +1 -0
  199. package/dist/forge/ado/__tests__/acceptance-scripts.test.js +360 -30
  200. package/dist/forge/ado/__tests__/acceptance-scripts.test.js.map +1 -1
  201. package/dist/forge/ado/__tests__/adapter.test.js +18 -3
  202. package/dist/forge/ado/__tests__/adapter.test.js.map +1 -1
  203. package/dist/forge/ado/__tests__/ci.test.d.ts +2 -0
  204. package/dist/forge/ado/__tests__/ci.test.d.ts.map +1 -0
  205. package/dist/forge/ado/__tests__/ci.test.js +271 -0
  206. package/dist/forge/ado/__tests__/ci.test.js.map +1 -0
  207. package/dist/forge/ado/__tests__/routes.test.js +24 -5
  208. package/dist/forge/ado/__tests__/routes.test.js.map +1 -1
  209. package/dist/forge/ado/__tests__/tracker-writes.test.d.ts +8 -0
  210. package/dist/forge/ado/__tests__/tracker-writes.test.d.ts.map +1 -0
  211. package/dist/forge/ado/__tests__/tracker-writes.test.js +377 -0
  212. package/dist/forge/ado/__tests__/tracker-writes.test.js.map +1 -0
  213. package/dist/forge/ado/__tests__/world.d.ts +4 -0
  214. package/dist/forge/ado/__tests__/world.d.ts.map +1 -1
  215. package/dist/forge/ado/__tests__/world.js +3 -2
  216. package/dist/forge/ado/__tests__/world.js.map +1 -1
  217. package/dist/forge/ado/checks.d.ts +25 -2
  218. package/dist/forge/ado/checks.d.ts.map +1 -1
  219. package/dist/forge/ado/checks.js +47 -23
  220. package/dist/forge/ado/checks.js.map +1 -1
  221. package/dist/forge/ado/ci.d.ts +13 -0
  222. package/dist/forge/ado/ci.d.ts.map +1 -0
  223. package/dist/forge/ado/ci.js +134 -0
  224. package/dist/forge/ado/ci.js.map +1 -0
  225. package/dist/forge/ado/guard.d.ts +19 -6
  226. package/dist/forge/ado/guard.d.ts.map +1 -1
  227. package/dist/forge/ado/guard.js +52 -11
  228. package/dist/forge/ado/guard.js.map +1 -1
  229. package/dist/forge/ado/index.d.ts +7 -1
  230. package/dist/forge/ado/index.d.ts.map +1 -1
  231. package/dist/forge/ado/index.js +16 -3
  232. package/dist/forge/ado/index.js.map +1 -1
  233. package/dist/forge/ado/reviews.d.ts +9 -1
  234. package/dist/forge/ado/reviews.d.ts.map +1 -1
  235. package/dist/forge/ado/reviews.js +45 -1
  236. package/dist/forge/ado/reviews.js.map +1 -1
  237. package/dist/forge/ado/routes.d.ts +35 -5
  238. package/dist/forge/ado/routes.d.ts.map +1 -1
  239. package/dist/forge/ado/routes.js +181 -9
  240. package/dist/forge/ado/routes.js.map +1 -1
  241. package/dist/forge/ado/tracker.d.ts +13 -2
  242. package/dist/forge/ado/tracker.d.ts.map +1 -1
  243. package/dist/forge/ado/tracker.js +139 -3
  244. package/dist/forge/ado/tracker.js.map +1 -1
  245. package/dist/forge/ado/wiql.d.ts +2 -0
  246. package/dist/forge/ado/wiql.d.ts.map +1 -1
  247. package/dist/forge/ado/wiql.js +6 -0
  248. package/dist/forge/ado/wiql.js.map +1 -1
  249. package/dist/forge/body-file.d.ts +17 -0
  250. package/dist/forge/body-file.d.ts.map +1 -0
  251. package/dist/forge/body-file.js +59 -0
  252. package/dist/forge/body-file.js.map +1 -0
  253. package/dist/forge/config.d.ts +3 -1
  254. package/dist/forge/config.d.ts.map +1 -1
  255. package/dist/forge/config.js +37 -2
  256. package/dist/forge/config.js.map +1 -1
  257. package/dist/forge/github/__tests__/argv-parity.test.js +17 -1
  258. package/dist/forge/github/__tests__/argv-parity.test.js.map +1 -1
  259. package/dist/forge/github/gh.d.ts +6 -0
  260. package/dist/forge/github/gh.d.ts.map +1 -1
  261. package/dist/forge/github/gh.js +2 -0
  262. package/dist/forge/github/gh.js.map +1 -1
  263. package/dist/forge/github/reviews.d.ts +2 -0
  264. package/dist/forge/github/reviews.d.ts.map +1 -1
  265. package/dist/forge/github/reviews.js +6 -0
  266. package/dist/forge/github/reviews.js.map +1 -1
  267. package/dist/forge/github/tracker.d.ts +20 -4
  268. package/dist/forge/github/tracker.d.ts.map +1 -1
  269. package/dist/forge/github/tracker.js +59 -5
  270. package/dist/forge/github/tracker.js.map +1 -1
  271. package/dist/forge/types.d.ts +108 -2
  272. package/dist/forge/types.d.ts.map +1 -1
  273. package/dist/forge/types.js +8 -0
  274. package/dist/forge/types.js.map +1 -1
  275. package/dist/graph/schema.d.ts +10 -10
  276. package/dist/hooks/session-end/__tests__/chain-enqueuer.test.js +156 -35
  277. package/dist/hooks/session-end/__tests__/chain-enqueuer.test.js.map +1 -1
  278. package/dist/hooks/session-end/__tests__/check-evidence.test.js +4 -4
  279. package/dist/hooks/session-end/__tests__/check-evidence.test.js.map +1 -1
  280. package/dist/hooks/session-end/__tests__/copilot-liveness.test.js +3 -3
  281. package/dist/hooks/session-end/__tests__/copilot-liveness.test.js.map +1 -1
  282. package/dist/hooks/session-end/__tests__/foreground-bootstrap.test.js +3 -3
  283. package/dist/hooks/session-end/__tests__/foreground-bootstrap.test.js.map +1 -1
  284. package/dist/hooks/session-end/__tests__/routing.test.js +36 -1
  285. package/dist/hooks/session-end/__tests__/routing.test.js.map +1 -1
  286. package/dist/hooks/session-end/__tests__/spawn-next.test.js +96 -5
  287. package/dist/hooks/session-end/__tests__/spawn-next.test.js.map +1 -1
  288. package/dist/hooks/session-end/__tests__/worker.test.js +38 -2
  289. package/dist/hooks/session-end/__tests__/worker.test.js.map +1 -1
  290. package/dist/hooks/session-end/chain-enqueuer.d.ts.map +1 -1
  291. package/dist/hooks/session-end/chain-enqueuer.js +22 -2
  292. package/dist/hooks/session-end/chain-enqueuer.js.map +1 -1
  293. package/dist/hooks/session-end/routing.d.ts +14 -0
  294. package/dist/hooks/session-end/routing.d.ts.map +1 -1
  295. package/dist/hooks/session-end/routing.js +25 -0
  296. package/dist/hooks/session-end/routing.js.map +1 -1
  297. package/dist/hooks/session-end/spawn-next.d.ts +20 -2
  298. package/dist/hooks/session-end/spawn-next.d.ts.map +1 -1
  299. package/dist/hooks/session-end/spawn-next.js +72 -5
  300. package/dist/hooks/session-end/spawn-next.js.map +1 -1
  301. package/dist/smoke/__tests__/copilot-chain-scenario.test.js +2 -1
  302. package/dist/smoke/__tests__/copilot-chain-scenario.test.js.map +1 -1
  303. package/dist/smoke/copilot-chain-scenario.d.ts.map +1 -1
  304. package/dist/smoke/copilot-chain-scenario.js +5 -1
  305. package/dist/smoke/copilot-chain-scenario.js.map +1 -1
  306. package/dist/team/__tests__/worker-launch-ack.test.js +134 -5
  307. package/dist/team/__tests__/worker-launch-ack.test.js.map +1 -1
  308. package/dist/team/worker-launch-ack.d.ts.map +1 -1
  309. package/dist/team/worker-launch-ack.js +19 -4
  310. package/dist/team/worker-launch-ack.js.map +1 -1
  311. package/docs/CLAUDE.md +1 -1
  312. package/docs/MIGRATION.md +26 -0
  313. package/docs/REFERENCE.md +187 -20
  314. package/docs/design/FACTORY-FINAL-DESIGN.md +1 -1
  315. package/docs/shipyard.md +17 -1
  316. package/package.json +2 -2
  317. package/plugin.json +1 -1
  318. package/scripts/ado-acceptance.mjs +309 -70
  319. package/scripts/lib/backlog-to-workitems.mjs +24 -21
  320. package/skills/ask-navigator/SKILL.md +5 -2
  321. package/skills/drydock/SKILL.md +2 -1
  322. package/skills/harbor/SKILL.md +17 -2
  323. package/skills/intent/SKILL.md +4 -0
  324. package/skills/launch/SKILL.md +35 -2
  325. package/skills/map/SKILL.md +2 -1
  326. package/skills/refit/SKILL.md +1 -0
@@ -0,0 +1,677 @@
1
+ /**
2
+ * `omg factory poll [--interval 5m] [--once] [--no-heal] [--no-intake] [--no-prs] [--json]`
3
+ * (ADO parity design §2): a foreground polling loop, forge-neutral (GitHub
4
+ * and Azure DevOps). It replaces webhooks where there is no public endpoint.
5
+ * One tick, in this order:
6
+ *
7
+ * 1. heal: `runHealScan` (classify new red CI runs into heal state), only
8
+ * when `forge.capabilities.heal` (Azure DevOps: factory.heal.pipeline set;
9
+ * without it the tick is skipped with heal scan's message); on Azure DevOps
10
+ * through heal scan's own wiring (adoHealFor), so the read guard pins
11
+ * `definitions` to that pipeline. Never `heal run` or `heal approve`.
12
+ * 2. intake: the source's ids diffed against `.omg/state/factory-poll.json`
13
+ * `seen`; each new id is checked (check's rules) and audited
14
+ * (`intake-new` in `.omg/state/factory-poll-audit.jsonl`).
15
+ * 3. PRs: every run in flight with a PR. A PR a human completed or abandoned
16
+ * prints the resume hint; open human review threads are counted (ADO).
17
+ * 4. board: the board rows that changed since the previous tick
18
+ * (src/factory/board), or with `--json` one JSON object per tick.
19
+ *
20
+ * Steps 1-4 never spawn a session or a lane and never write to the tracker or
21
+ * the forge: every forge call goes through check's read guard with no marker
22
+ * (openReadForge), and the heal scan through the heal guard. It writes local
23
+ * state only: the poll file and its audit; the heal tick also writes heal
24
+ * state under its `scan.lock` and the heal scan records in the ledger
25
+ * directory outside the repository, as `heal scan` does. The tick result says whether the
26
+ * repository was idle (no engine owner, no run in flight, no unreadable run
27
+ * state).
28
+ *
29
+ * 5. auto-start (`factory.intake.autoStart`, trusted layers only, default
30
+ * off; shipyard-factory design D7): after an idle tick whose intake read
31
+ * succeeded and was not rate-limited (a broken run state is never idle),
32
+ * with budget headroom (PollBudget), and once poll's atomic claim of the
33
+ * engine's repo owner lock succeeds (a refusal skips the tick), poll starts one
34
+ * `omg factory run --next --json` and waits for it. It runs as a child
35
+ * `omg` process, not in-process: the run gets the engine's own guard,
36
+ * lock, limits, forge config and signal handling exactly as if the user
37
+ * had typed it, and none of it leaks into the tick's read guard (which
38
+ * refuses `omg`, so a tick still cannot spawn). It never starts the
39
+ * listener chain, `heal run` or `heal approve`, and at most one run per
40
+ * tick. Its budget gate fails closed (defaultPollBudget). Design note: the
41
+ * working-tree `intake.source` / `limit` (and `check.*`) stay
42
+ * allowed, so a working-tree file steers which item an unattended start
43
+ * picks; check's rules still decide what is runnable, and the switch and
44
+ * the budget come only from the trusted layers.
45
+ *
46
+ * One poller per repository (the owner pid in the poll file, under its lock,
47
+ * with a `beatAt` heartbeat each tick; an owner silent for 2 x the 60 min
48
+ * ceiling is stale and taken over).
49
+ * SIGINT / SIGTERM end the loop after the current tick. A rate-limited tick
50
+ * (TF400733, HTTP 429) doubles the interval, up to 60 min; a clean tick
51
+ * resets it. The interval floor is 2 min.
52
+ *
53
+ * Exit codes: 0 (a loop stopped by a signal, or a clean `--once` tick);
54
+ * 1 a read failed in the `--once` tick, or another poller runs; 2 usage;
55
+ * 5 incompatible (as `omg factory check`).
56
+ */
57
+ import { spawn } from 'child_process';
58
+ import { appendFileSync, existsSync, lstatSync, readFileSync } from 'fs';
59
+ import { join } from 'path';
60
+ import { ledgerPath, ledgerTotals, parseLedger } from '../budget/ledger.js';
61
+ import { atomicWriteFileSync, ensureDirSync } from '../lib/atomic-write.js';
62
+ import { lockPathFor, withFileLockSync } from '../lib/file-lock.js';
63
+ import { getOmcRoot } from '../lib/worktree-paths.js';
64
+ import { ADO_RATE_LIMITED } from '../forge/ado/checks.js';
65
+ import { ShipSafetyError } from '../ship/exec.js';
66
+ import { collectBoard, readRuns } from './board/collect.js';
67
+ import { backlogLine, runLine } from './board/render.js';
68
+ import { CheckUsageError, checkEnvFor, defaultResolveAz, openReadForge } from './check/cli.js';
69
+ import { checkItems, plainText } from './check/score.js';
70
+ import { adoHealFor, ciDeps, HEAL_PIPELINE_MISSING, runHealScan } from './heal/cli.js';
71
+ import { HealRunRefused } from './heal/run.js';
72
+ import { DEFAULT_FACTORY_RUN_LIMITS, resolveFactoryRunLimits } from './run/budget.js';
73
+ import { acquireFactoryRepoOwner, defaultOwnerDeps, factoryRepoOwnerPath, runLabel, TERMINAL_FACTORY_PHASES, verifyFactoryIntegrity, } from './run/state.js';
74
+ /** Bumped on any change to the `--json` tick shape (src/factory/__tests__/poll.test.ts pins it). */
75
+ export const POLL_JSON_SCHEMA_VERSION = 1;
76
+ export const POLL_DEFAULT_INTERVAL_MS = 5 * 60_000;
77
+ /** The floor: ADO allows 200 TSTU per sliding 5 minutes per user (design §2.3). */
78
+ export const POLL_MIN_INTERVAL_MS = 2 * 60_000;
79
+ /** The backoff ceiling. */
80
+ export const POLL_MAX_INTERVAL_MS = 60 * 60_000;
81
+ /** An owner whose last heartbeat is older than this is stale (a crashed poller on another host, or a reused pid). */
82
+ export const POLL_OWNER_STALE_MS = 2 * POLL_MAX_INTERVAL_MS;
83
+ export class PollBusyError extends Error {
84
+ }
85
+ export const pollStatePath = (root) => join(getOmcRoot(root), 'state', 'factory-poll.json');
86
+ export const pollAuditPath = (root) => join(getOmcRoot(root), 'state', 'factory-poll-audit.jsonl');
87
+ /** `--interval`: `<n>s`, `<n>m` (also a bare number) or `<n>h`, at least 2 min. */
88
+ export function parseInterval(raw) {
89
+ const m = /^([1-9]\d{0,5})(s|m|h)?$/.exec(raw.trim());
90
+ if (!m)
91
+ throw new CheckUsageError(`--interval ${JSON.stringify(raw)} is not <n>s, <n>m or <n>h`);
92
+ const ms = Number(m[1]) * (m[2] === 's' ? 1_000 : m[2] === 'h' ? 3_600_000 : 60_000);
93
+ if (ms < POLL_MIN_INTERVAL_MS)
94
+ throw new CheckUsageError(`--interval ${raw} is below the 2 min floor (Azure DevOps rate limits)`);
95
+ if (ms > POLL_MAX_INTERVAL_MS)
96
+ throw new CheckUsageError(`--interval ${raw} is above 60 min`);
97
+ return ms;
98
+ }
99
+ /** The wait after a tick: doubled (up to 60 min) after a rate-limited tick, the configured interval after a clean one. */
100
+ export function nextInterval(current, base, rateLimited) {
101
+ return rateLimited ? Math.min(Math.max(current, base) * 2, POLL_MAX_INTERVAL_MS) : base;
102
+ }
103
+ function readPollFile(path) {
104
+ if (!existsSync(path))
105
+ return { seen: [] };
106
+ let raw;
107
+ try {
108
+ raw = JSON.parse(readFileSync(path, 'utf8'));
109
+ }
110
+ catch {
111
+ return { seen: [] };
112
+ }
113
+ const f = (raw && typeof raw === 'object' ? raw : {});
114
+ return {
115
+ // A pid without a hostname cannot be checked: no owner.
116
+ ...(Number.isSafeInteger(f.pid) && typeof f.hostname === 'string' ? { pid: f.pid, hostname: f.hostname } : {}),
117
+ ...(typeof f.startedAt === 'string' ? { startedAt: f.startedAt } : {}),
118
+ ...(typeof f.beatAt === 'string' ? { beatAt: f.beatAt } : {}),
119
+ seen: Array.isArray(f.seen) ? f.seen.filter((n) => Number.isSafeInteger(n) && n > 0) : [],
120
+ ...(typeof f.at === 'string' ? { at: f.at } : {}),
121
+ };
122
+ }
123
+ const writePollFile = (path, f) => atomicWriteFileSync(path, `${JSON.stringify(f, null, 2)}\n`);
124
+ /** The poll file without its owner. */
125
+ const ownerless = (f) => ({ seen: f.seen, ...(f.at ? { at: f.at } : {}) });
126
+ /** The owner's last heartbeat (its start before the first beat) is older than POLL_OWNER_STALE_MS, or unreadable. */
127
+ const stale = (f, now) => {
128
+ const beat = Date.parse(f.beatAt ?? f.startedAt ?? '');
129
+ return !Number.isFinite(beat) || Date.parse(now) - beat > POLL_OWNER_STALE_MS;
130
+ };
131
+ /** A live owner, or one on another host (its pid cannot be checked), holds the file. */
132
+ const heldBy = (f, me) => f.pid !== undefined && (f.hostname !== me.hostname || (f.pid !== me.pid && me.isAlive(f.pid)));
133
+ /**
134
+ * Claim the poller owner (the pid in the poll file, under its lock): a second
135
+ * poller refuses; a dead one on this host is taken over.
136
+ */
137
+ export function acquirePoller(root, now, me = defaultOwnerDeps()) {
138
+ const path = pollStatePath(root);
139
+ ensureDirSync(join(path, '..'));
140
+ withFileLockSync(lockPathFor(path), () => {
141
+ const f = readPollFile(path);
142
+ if (heldBy(f, me) && !stale(f, now)) {
143
+ throw new PollBusyError(`omg factory poll already runs in this repository (pid ${f.pid} on ${f.hostname} since ${f.startedAt}, last beat ${f.beatAt ?? 'none'}); one poller per repository. If no poller runs, delete ${path}`);
144
+ }
145
+ writePollFile(path, { pid: me.pid, hostname: me.hostname, startedAt: now, beatAt: now, ...ownerless(f) });
146
+ }, { timeoutMs: 5_000 });
147
+ return {
148
+ release: () => {
149
+ try {
150
+ withFileLockSync(lockPathFor(path), () => {
151
+ const f = readPollFile(path);
152
+ if (f.pid === me.pid && f.hostname === me.hostname)
153
+ writePollFile(path, ownerless(f));
154
+ }, { timeoutMs: 5_000 });
155
+ }
156
+ catch { /* the next poller takes a dead owner over */ }
157
+ },
158
+ };
159
+ }
160
+ function updateSeen(root, seen, at) {
161
+ const path = pollStatePath(root);
162
+ withFileLockSync(lockPathFor(path), () => writePollFile(path, { ...readPollFile(path), seen: [...seen].sort((a, b) => a - b), at }), { timeoutMs: 5_000 });
163
+ }
164
+ /** The owner's heartbeat; false when another poller has taken the file over. */
165
+ function beat(root, me, at) {
166
+ const path = pollStatePath(root);
167
+ return withFileLockSync(lockPathFor(path), () => {
168
+ const f = readPollFile(path);
169
+ if (f.pid !== me.pid || f.hostname !== me.hostname)
170
+ return false;
171
+ writePollFile(path, { ...f, beatAt: at });
172
+ return true;
173
+ }, { timeoutMs: 5_000 });
174
+ }
175
+ function audit(root, record, at) {
176
+ try {
177
+ const path = pollAuditPath(root);
178
+ ensureDirSync(join(path, '..'));
179
+ // Never append through a link planted at the audit path.
180
+ if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink())
181
+ return;
182
+ appendFileSync(path, `${JSON.stringify({ ...record, at })}\n`, 'utf8');
183
+ }
184
+ catch {
185
+ // best-effort audit trail (as the listener's)
186
+ }
187
+ }
188
+ /** Whether an engine holds the repository (factoryRepoOwnerPath), as acquireFactoryRepoOwner would see it. */
189
+ function engineBusy(root, me) {
190
+ const path = factoryRepoOwnerPath(root);
191
+ if (!existsSync(path))
192
+ return false;
193
+ try {
194
+ return heldBy(JSON.parse(readFileSync(path, 'utf8')), me);
195
+ }
196
+ catch {
197
+ // An unreadable owner file is never taken for a free repository.
198
+ return true;
199
+ }
200
+ }
201
+ /**
202
+ * The production heal tick: `omg factory heal scan` (writing heal state, never
203
+ * a lane) through the heal guard on the raw Exec. On Azure DevOps it is heal
204
+ * scan's wiring (adoHealFor over the tick's forge config): factory.heal.pipeline's
205
+ * reads under the `read` policy, GETs only.
206
+ */
207
+ export function defaultPollHealScan(exec, config, ledgerDir, resolveAz = defaultResolveAz) {
208
+ return (o) => {
209
+ let ado;
210
+ if (o.kind === 'azure-devops') {
211
+ if (!o.forge)
212
+ throw new HealRunRefused(HEAL_PIPELINE_MISSING);
213
+ ado = adoHealFor(o.forge, () => resolveAz(o.root), o.root);
214
+ }
215
+ const heal = config(o.root);
216
+ for (const w of heal.warnings)
217
+ o.warn(w);
218
+ return runHealScan({ exec, root: o.root, base: o.base, config: heal.config, now: o.now, dryRun: false, warn: o.warn, ledgerDir, ...ciDeps({}, ado) });
219
+ };
220
+ }
221
+ /** The child's JSON stdout is the run outcome (state included); more than this is not parsed. */
222
+ const AUTO_START_MAX_STDOUT = 4 * 1024 * 1024;
223
+ /** The run key of poll's claim on the repo owner lock: no item is picked yet (0 is never an issue number). */
224
+ const AUTO_START_CLAIM = 0;
225
+ /** Slack on top of the run's own bounds, for its git and forge calls. */
226
+ const AUTO_START_SLACK_MS = 30 * 60_000;
227
+ /** SIGTERM to SIGKILL when the child outlives its wall-clock limit. */
228
+ const AUTO_START_GRACE_MS = 2 * 60_000;
229
+ /**
230
+ * The child's wall-clock limit: maxRunWallTimeMs + laneTimeoutMs +
231
+ * gatesTimeoutMs + 30 min. The engine checks maxRunWallTimeMs only at step
232
+ * boundaries, so one invocation can overrun it by one step: a lane (its
233
+ * laneTimeoutMs) or a gates phase (its gatesTimeoutMs). The 30 min cover the
234
+ * git and forge calls around them. Defaults: 4 h + 30 min + 90 min + 30 min = 6.5 h.
235
+ */
236
+ export function autoStartTimeoutMs(limits) {
237
+ return limits.maxRunWallTimeMs + limits.laneTimeoutMs + limits.gatesTimeoutMs + AUTO_START_SLACK_MS;
238
+ }
239
+ /**
240
+ * Read `omg factory run --next --json`'s stdout: one of factoryRunJson's
241
+ * documents (src/cli/commands/factory.ts), which all carry `message` or
242
+ * `error`. Anything else is not parsed.
243
+ */
244
+ export function parseRunNextOutcome(stdout) {
245
+ let raw;
246
+ try {
247
+ raw = JSON.parse(stdout);
248
+ }
249
+ catch {
250
+ raw = undefined;
251
+ }
252
+ const o = (raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {});
253
+ const text = typeof o.message === 'string' ? o.message : typeof o.error === 'string' ? o.error : undefined;
254
+ if (text === undefined)
255
+ return { parsed: false, next: null, message: 'no outcome on stdout' };
256
+ return { parsed: true, next: Number.isSafeInteger(o.next) && o.next > 0 ? o.next : null, message: text };
257
+ }
258
+ /**
259
+ * The production auto-start: a child `omg factory run --next --json` (the
260
+ * same node and CLI entry as this poller) in the repository root, stdin
261
+ * closed, stderr shared (the run's progress shows), stdout parsed for the
262
+ * outcome. Poll's stop signals are forwarded, so the run stops after its
263
+ * current poll as when typed by hand. On POSIX the child runs in its own
264
+ * process group, so a Ctrl+C reaches it once (forwarded by poll), not twice;
265
+ * on Windows it shares the console, which delivers Ctrl+C itself, so only
266
+ * SIGTERM is forwarded there. Past timeoutMs it gets SIGTERM, then SIGKILL
267
+ * after graceMs; on POSIX both go to the whole process group, on Windows only
268
+ * to the engine process (its lanes are not reached).
269
+ */
270
+ export function defaultPollAutoStart(entry = process.argv[1], o = {}) {
271
+ return ({ root }) => new Promise((resolve) => {
272
+ if (!entry) {
273
+ resolve({ exitCode: 1, parsed: false, next: null, message: 'cannot locate the omg CLI entry to start omg factory run --next' });
274
+ return;
275
+ }
276
+ const timeoutMs = o.timeoutMs?.(root) ?? autoStartTimeoutMs(DEFAULT_FACTORY_RUN_LIMITS);
277
+ let stdout = '';
278
+ let truncated = false;
279
+ let timedOut = false;
280
+ let settled = false;
281
+ let timer;
282
+ let killer;
283
+ let unsubscribe = () => { };
284
+ const settle = (r) => {
285
+ if (settled)
286
+ return;
287
+ settled = true;
288
+ clearTimeout(timer);
289
+ clearTimeout(killer);
290
+ unsubscribe();
291
+ resolve(r);
292
+ };
293
+ const notStarted = (error) => settle({ exitCode: 1, parsed: false, next: null, message: `omg factory run --next did not start: ${message(error)}` });
294
+ let child;
295
+ try {
296
+ child = spawn(process.execPath, [entry, 'factory', 'run', '--next', '--json'], { cwd: root, stdio: ['ignore', 'pipe', 'inherit'], windowsHide: true, detached: process.platform !== 'win32' });
297
+ }
298
+ catch (error) {
299
+ notStarted(error);
300
+ return;
301
+ }
302
+ // On POSIX the child leads its own process group: signal the group so its lane children die with it.
303
+ const killTree = (sig) => {
304
+ if (process.platform === 'win32' || child.pid === undefined) {
305
+ child.kill(sig);
306
+ return;
307
+ }
308
+ try {
309
+ process.kill(-child.pid, sig);
310
+ }
311
+ catch {
312
+ child.kill(sig);
313
+ }
314
+ };
315
+ child.stdout.setEncoding('utf8');
316
+ child.stdout.on('data', (d) => {
317
+ if (stdout.length + d.length <= AUTO_START_MAX_STDOUT)
318
+ stdout += d;
319
+ else
320
+ truncated = true;
321
+ });
322
+ child.on('error', notStarted);
323
+ child.on('close', (code, signal) => {
324
+ const ended = signal ? ` (ended by ${signal})` : '';
325
+ if (timedOut) {
326
+ settle({ exitCode: code ?? 1, parsed: false, next: null, message: `omg factory run --next ran past its ${Math.round(timeoutMs / 60_000)} min limit and was stopped${ended}` });
327
+ return;
328
+ }
329
+ const out = truncated ? { parsed: false, next: null, message: `the outcome on stdout exceeded ${AUTO_START_MAX_STDOUT} bytes` } : parseRunNextOutcome(stdout);
330
+ settle({ exitCode: code ?? 1, ...out, message: out.parsed ? out.message : `${out.message}${ended}` });
331
+ });
332
+ timer = setTimeout(() => {
333
+ timedOut = true;
334
+ killTree('SIGTERM');
335
+ killer = setTimeout(() => killTree('SIGKILL'), o.graceMs ?? AUTO_START_GRACE_MS);
336
+ }, timeoutMs);
337
+ unsubscribe = o.signals?.((signal) => {
338
+ if (process.platform !== 'win32' || signal !== 'SIGINT')
339
+ child.kill(signal);
340
+ }) ?? unsubscribe;
341
+ });
342
+ }
343
+ function softLimitOf(config, source) {
344
+ const raw = config?.budget?.softLimit;
345
+ if (raw === undefined)
346
+ return undefined;
347
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0)
348
+ throw new Error(`${source}: budget.softLimit must be a positive number (got ${JSON.stringify(raw)})`);
349
+ return raw;
350
+ }
351
+ /**
352
+ * The production budget gate of an unattended start. It fails closed:
353
+ * - the `factory.run` limits must resolve (`omg factory run` refuses without
354
+ * a valid per-lane AI-credit cap);
355
+ * - the governor must be on (`OMC_BUDGET_GOVERNOR=0` means no auto-start);
356
+ * - `budget.softLimit` comes from the user config, then the base branch (as
357
+ * factory.intake.autoStart); the working-tree layer can only lower it
358
+ * (resolveFactoryRunLimits' tighten-only rule). No trusted value, an
359
+ * invalid one, or an unreadable ledger blocks the start;
360
+ * - the AI credits in the ledger must be below it (the governor only warns a
361
+ * human; an unattended start stops at it).
362
+ * A human `omg factory run` never reads this gate.
363
+ */
364
+ export function defaultPollBudget(layers, env = process.env) {
365
+ return (root) => {
366
+ try {
367
+ const l = layers(root);
368
+ resolveFactoryRunLimits(l.trustedUser, l.project);
369
+ if (env.OMC_BUDGET_GOVERNOR === '0')
370
+ return 'the budget governor is off (OMC_BUDGET_GOVERNOR=0); autoStart needs it on';
371
+ const trusted = softLimitOf(l.trustedUser, 'user config') ?? softLimitOf(l.base, 'base-branch .copilot/omg.jsonc');
372
+ if (trusted === undefined)
373
+ return 'autoStart needs budget.softLimit (user config or base branch)';
374
+ const project = softLimitOf(l.project, 'project config');
375
+ const limit = project !== undefined && project < trusted ? project : trusted;
376
+ const path = ledgerPath(root);
377
+ const { ledger, invalid } = parseLedger(path);
378
+ if (invalid)
379
+ return `the budget ledger is unreadable (${path}); autoStart needs it (omg budget status)`;
380
+ const used = ledgerTotals(ledger).credits;
381
+ return used >= limit ? `the AI credits used (${used.toFixed(2)}) reached budget.softLimit ${limit} (omg budget status)` : null;
382
+ }
383
+ catch (error) {
384
+ return message(error);
385
+ }
386
+ };
387
+ }
388
+ const message = (error) => plainText(error instanceof Error ? error.message : String(error));
389
+ const resumeHint = (key) => (typeof key === 'number' ? `omg factory run ${key}` : `omg factory heal approve ${key.slice('heal-'.length)}`);
390
+ /**
391
+ * One tick. Steps 1-4 never spawn and never write to the tracker or forge; a
392
+ * guard refusal propagates (a bug, not an unreadable item). Step 5 is the
393
+ * auto-start, outside the read guard.
394
+ */
395
+ export async function pollTick(ctx) {
396
+ const { forge, config, root } = ctx;
397
+ const at = new Date(ctx.now()).toISOString();
398
+ const errors = [];
399
+ const warnings = [];
400
+ const step = (name, fn) => {
401
+ try {
402
+ return fn();
403
+ }
404
+ catch (error) {
405
+ if (error instanceof ShipSafetyError)
406
+ throw error;
407
+ errors.push(`${name}: ${message(error)}`);
408
+ return undefined;
409
+ }
410
+ };
411
+ ctx.tick += 1;
412
+ if (step('heartbeat', () => beat(root, ctx.owner, at)) === false)
413
+ warnings.push(`another poller owns ${pollStatePath(root)}; stop this one`);
414
+ const ledgerNow = step('ledger', () => existsSync(ledgerPath(root)));
415
+ if (ledgerNow !== undefined) {
416
+ if (ctx.previous.ledger && !ledgerNow)
417
+ warnings.push(`budget ledger ${ledgerPath(root)} disappeared; spend restarts at 0`);
418
+ ctx.previous.ledger = ledgerNow;
419
+ }
420
+ // 1. heal
421
+ let heal;
422
+ if (!ctx.heal)
423
+ heal = { ran: false, reason: '--no-heal' };
424
+ else if (!forge.capabilities.heal)
425
+ heal = { ran: false, reason: forge.kind === 'azure-devops' ? HEAL_PIPELINE_MISSING : 'the forge has no heal capability' };
426
+ else {
427
+ try {
428
+ const r = ctx.healScan({ root, base: ctx.base, kind: forge.kind, forge: config, now: new Date(ctx.now()), warn: (m) => warnings.push(plainText(m)) });
429
+ heal = { ran: true, entries: r.entries.length, recorded: r.entries.filter((e) => e.recorded).length, queued: r.queued };
430
+ }
431
+ catch (error) {
432
+ if (error instanceof ShipSafetyError)
433
+ throw error;
434
+ heal = { ran: false, reason: message(error) };
435
+ if (!(error instanceof HealRunRefused))
436
+ errors.push(`heal: ${message(error)}`);
437
+ }
438
+ }
439
+ // 2. intake
440
+ const source = config.intake.source;
441
+ let ids = [];
442
+ let intake;
443
+ if (!ctx.intake)
444
+ intake = { ran: false, reason: '--no-intake' };
445
+ else if (!source)
446
+ intake = { ran: false, reason: 'no intake source (factory.intake.source)' };
447
+ else {
448
+ const listed = step('intake', () => forge.tracker.queryItems(source, config.intake.limit));
449
+ if (!listed)
450
+ intake = { ran: false, reason: 'the intake query failed' };
451
+ else {
452
+ ids = listed;
453
+ const seen = new Set(readPollFile(pollStatePath(root)).seen);
454
+ const fresh = [...new Set(ids)].filter((id) => !seen.has(id));
455
+ const results = fresh.length ? step('intake check', () => checkItems(forge, fresh, checkEnvFor(ctx.exec, root, config, ctx.base, ctx.baseSha))) : [];
456
+ // A failed check marks nothing seen: the next tick checks every new id again.
457
+ if (!results)
458
+ intake = { ran: false, reason: 'the intake check failed' };
459
+ else {
460
+ for (const r of results) {
461
+ audit(root, { kind: 'intake-new', id: r.id, bucket: r.bucket, reasons: r.reasons }, at);
462
+ if (r.reasons[0] === 'read-failed')
463
+ errors.push(`intake: ${r.detail}`);
464
+ }
465
+ // A read-failed item stays new, so the next tick checks it again.
466
+ const failed = new Set(results.filter((r) => r.reasons[0] === 'read-failed').map((r) => r.id));
467
+ step('intake seen', () => updateSeen(root, ids.filter((id) => !failed.has(id)), at));
468
+ intake = { ran: true, items: ids.length, new: results.map((r) => ({ id: r.id, bucket: r.bucket, reasons: r.reasons })) };
469
+ }
470
+ }
471
+ }
472
+ // 3. PRs (and the idle seam): the runs in flight.
473
+ const { runs, broken } = readRuns(root, warnings);
474
+ const live = [...runs].filter(([, s]) => !TERMINAL_FACTORY_PHASES.includes(s.phase));
475
+ const prs = [];
476
+ if (ctx.prs) {
477
+ for (const [key, s] of live) {
478
+ if (s.pr === undefined)
479
+ continue;
480
+ const pr = s.pr;
481
+ const row = { id: key, pr };
482
+ const view = step(`PR ${pr}`, () => forge.reviews.viewPr(pr));
483
+ if (!view)
484
+ row.error = errors[errors.length - 1];
485
+ else {
486
+ row.state = view.state;
487
+ if (view.state !== 'OPEN')
488
+ row.hint = resumeHint(key);
489
+ else if (forge.reviews.listThreads) {
490
+ const threads = step(`PR ${pr} threads`, () => forge.reviews.listThreads(pr));
491
+ if (threads)
492
+ row.threads = threads.filter((t) => (t.status === 'active' || t.status === 'pending') && t.kind === 'text' && !t.byFactory).length;
493
+ else
494
+ row.error = errors[errors.length - 1];
495
+ }
496
+ }
497
+ const facts = JSON.stringify([row.state, row.threads]);
498
+ if (row.state !== undefined && ctx.previous.prs.get(runLabel(key)) !== facts) {
499
+ if (row.state !== 'OPEN')
500
+ audit(root, { kind: 'pr-done', id: key, pr, state: row.state, hint: row.hint }, at);
501
+ else if (row.threads !== undefined)
502
+ audit(root, { kind: 'pr-threads', id: key, pr, active: row.threads }, at);
503
+ ctx.previous.prs.set(runLabel(key), facts);
504
+ }
505
+ prs.push(row);
506
+ }
507
+ }
508
+ const locked = engineBusy(root, ctx.owner);
509
+ // A run state that is unreadable or fails its integrity seal may hide a run in flight: never idle.
510
+ const unsound = broken.size > 0 || [...runs.values()].some((s) => !verifyFactoryIntegrity(s));
511
+ const idle = !locked && !unsound && !live.some(([, s]) => !s.gate);
512
+ // 4. board: the rows that changed.
513
+ const board = [];
514
+ const shown = step('board', () => collectBoard({ forge, config, root, ids, check: null, now: ctx.now(), warnings }));
515
+ if (shown) {
516
+ const rows = [...shown.columns.flatMap((c) => c.items.map((row) => ({ stage: c.stage, row }))), ...shown.outside.map((row) => ({ stage: 'outside', row }))];
517
+ const next = new Map();
518
+ for (const r of rows) {
519
+ const sig = JSON.stringify(r);
520
+ next.set(runLabel(r.row.id), sig);
521
+ if (ctx.previous.board.get(runLabel(r.row.id)) !== sig)
522
+ board.push(r);
523
+ }
524
+ ctx.previous.board = next;
525
+ }
526
+ const rateLimited = [...errors, ...warnings].some((m) => ADO_RATE_LIMITED.test(m));
527
+ // 5. auto-start: at most one run, on an idle tick only.
528
+ let autoStart;
529
+ const blocked = !config.intake.autoStart ? 'factory.intake.autoStart is off'
530
+ : locked ? 'the run lock is held: an engine runs in this repository'
531
+ : unsound ? 'a run state is unreadable or fails its integrity check'
532
+ : !idle ? 'a run is in flight'
533
+ : !intake.ran ? `no intake read this tick (${intake.reason})`
534
+ : rateLimited ? 'the tick was rate-limited'
535
+ : null;
536
+ if (blocked)
537
+ autoStart = { started: false, reason: blocked };
538
+ else {
539
+ let reason = ctx.budget(root);
540
+ if (!reason) {
541
+ // `idle` is advisory: claim the engine's repo owner lock atomically (as an engine would); a refusal skips this
542
+ // tick. It is released for the child, whose own claim at start is the binding one: an engine that slips in
543
+ // between makes that claim refuse, so two engines never run.
544
+ try {
545
+ acquireFactoryRepoOwner(root, AUTO_START_CLAIM, at, ctx.owner).release();
546
+ }
547
+ catch (error) {
548
+ reason = `the run lock is held: ${message(error)}`;
549
+ }
550
+ }
551
+ if (reason)
552
+ autoStart = { started: false, reason: plainText(reason) };
553
+ else {
554
+ audit(root, { kind: 'auto-start' }, at);
555
+ const r = await ctx.autoStart({ root });
556
+ audit(root, { kind: 'auto-start-done', ...(r.parsed ? { next: r.next } : { outcome: 'unreadable' }), exitCode: r.exitCode }, new Date(ctx.now()).toISOString());
557
+ autoStart = { started: true, parsed: r.parsed, next: r.parsed ? r.next : null, exitCode: r.exitCode, message: plainText(r.message) };
558
+ }
559
+ }
560
+ return {
561
+ schemaVersion: POLL_JSON_SCHEMA_VERSION, tick: ctx.tick, at, forge: config.kind, repo: config.repo.url,
562
+ heal, intake, prs, board, idle, autoStart, rateLimited, errors: errors.map(plainText), warnings: warnings.map(plainText),
563
+ };
564
+ }
565
+ export function renderTick(t) {
566
+ const prefix = t.forge === 'azure-devops' ? '!' : '#';
567
+ const lines = [`factory poll tick ${t.tick} ${t.at} ${t.forge} ${t.repo}${t.idle ? ' idle' : ''}${t.nextIntervalMs ? ` next in ${Math.round(t.nextIntervalMs / 60_000)} min` : ''}${t.rateLimited ? ' rate-limited: backing off' : ''}`];
568
+ if (t.heal.ran && t.heal.entries > 0)
569
+ lines.push(` heal: ${t.heal.entries} run(s) scanned, ${t.heal.recorded} recorded${t.heal.queued ? `, ${t.heal.queued} queued` : ''} (omg factory heal status)`);
570
+ if (t.intake.ran)
571
+ for (const n of t.intake.new)
572
+ lines.push(` intake: new #${n.id} ${n.bucket}${n.reasons[0] ? ` ${n.reasons[0]}` : ''}`);
573
+ for (const p of t.prs) {
574
+ if (p.hint)
575
+ lines.push(` PR ${prefix}${p.pr} of ${runLabel(p.id)} is ${p.state === 'MERGED' ? 'merged' : 'closed'} by a human: run \`${p.hint}\` to record it`);
576
+ else if (p.threads)
577
+ lines.push(` PR ${prefix}${p.pr} of ${runLabel(p.id)}: ${p.threads} open human thread(s)`);
578
+ }
579
+ for (const b of t.board)
580
+ lines.push(` ${b.stage.toUpperCase()}${b.stage === 'backlog' ? backlogLine(b.row) : runLine(b.row, prefix)}`);
581
+ if (t.autoStart.started) {
582
+ const a = t.autoStart;
583
+ const took = !a.parsed ? 'outcome unreadable' : a.next !== null ? `took #${a.next}` : a.exitCode === 0 ? 'found nothing runnable' : 'took no item';
584
+ lines.push(` auto-start: omg factory run --next ${took}, exit ${a.exitCode}: ${a.message}`);
585
+ }
586
+ return lines.join('\n');
587
+ }
588
+ const defaultSleep = (ms, wake) => new Promise((resolve) => {
589
+ if (wake.aborted) {
590
+ resolve();
591
+ return;
592
+ }
593
+ const timer = setTimeout(resolve, ms);
594
+ wake.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
595
+ });
596
+ const defaultOnStop = (handler) => {
597
+ process.on('SIGINT', handler);
598
+ process.on('SIGTERM', handler);
599
+ return () => { process.off('SIGINT', handler); process.off('SIGTERM', handler); };
600
+ };
601
+ /** Run the poller until a stop signal (or one tick with --once); returns the exit code. */
602
+ export async function runFactoryPoll(o, deps) {
603
+ const base = o.interval === undefined ? POLL_DEFAULT_INTERVAL_MS : parseInterval(o.interval);
604
+ const now = deps.now ?? Date.now;
605
+ const warnings = [];
606
+ const checkDeps = { ...deps, isTTY: () => false, confirm: async () => false };
607
+ const read = openReadForge({}, checkDeps, warnings, 'omg factory poll');
608
+ for (const w of warnings)
609
+ deps.err(plainText(w));
610
+ const owner = deps.owner ?? defaultOwnerDeps();
611
+ // The budget gate's layers and the child's limits, read once like the rest of the config.
612
+ const layers = { trustedUser: deps.trustedUser(), base: read.baseConfig, project: deps.projectConfig(read.root) };
613
+ const runLimits = () => {
614
+ try {
615
+ return resolveFactoryRunLimits(layers.trustedUser, layers.project).limits;
616
+ }
617
+ catch {
618
+ return DEFAULT_FACTORY_RUN_LIMITS; // the budget gate refuses the start first
619
+ }
620
+ };
621
+ const { release } = acquirePoller(read.root, new Date(now()).toISOString(), owner);
622
+ let stopping = 0;
623
+ const wake = new AbortController();
624
+ // An auto-started run in flight gets every stop signal too (defaultPollAutoStart), the second before the exit.
625
+ const forwards = new Set();
626
+ const off = (deps.onStop ?? defaultOnStop)((signal = 'SIGTERM') => {
627
+ stopping += 1;
628
+ for (const forward of forwards)
629
+ forward(signal);
630
+ if (stopping > 1)
631
+ process.exit(130);
632
+ deps.err('omg factory poll: stopping after the current tick; press again to exit at once');
633
+ wake.abort();
634
+ });
635
+ const ctx = {
636
+ forge: read.forge, config: read.config, root: read.root, base: read.base, exec: read.exec, baseSha: read.baseSha,
637
+ heal: o.heal !== false, intake: o.intake !== false, prs: o.prs !== false,
638
+ healScan: deps.healScan,
639
+ autoStart: deps.autoStart ?? defaultPollAutoStart(process.argv[1], {
640
+ timeoutMs: () => autoStartTimeoutMs(runLimits()),
641
+ signals: (forward) => { forwards.add(forward); return () => { forwards.delete(forward); }; },
642
+ }),
643
+ budget: deps.budget ?? defaultPollBudget(() => layers),
644
+ owner, now, previous: { board: new Map(), prs: new Map() }, tick: 0,
645
+ };
646
+ let interval = base;
647
+ try {
648
+ for (;;) {
649
+ const t = await pollTick(ctx);
650
+ if (!o.once) {
651
+ interval = nextInterval(interval, base, t.rateLimited);
652
+ t.nextIntervalMs = interval;
653
+ }
654
+ if (o.json)
655
+ deps.out(JSON.stringify(t));
656
+ else {
657
+ for (const w of t.warnings)
658
+ deps.err(w);
659
+ for (const e of t.errors)
660
+ deps.err(`omg factory poll: ${e}`);
661
+ deps.out(renderTick(t));
662
+ }
663
+ if (o.once)
664
+ return t.errors.length ? 1 : 0;
665
+ if (stopping)
666
+ return 0;
667
+ await (deps.sleep ?? defaultSleep)(interval, wake.signal);
668
+ if (stopping)
669
+ return 0;
670
+ }
671
+ }
672
+ finally {
673
+ off();
674
+ release();
675
+ }
676
+ }
677
+ //# sourceMappingURL=poll.js.map