symphony-forge 1.2.44__py3-none-any.whl

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 (623) hide show
  1. forge/__init__.py +4 -0
  2. forge/app_baseline.py +148 -0
  3. forge/approval.py +298 -0
  4. forge/autoreview.py +139 -0
  5. forge/backfill.py +298 -0
  6. forge/board.py +1197 -0
  7. forge/board_app/app.js +276 -0
  8. forge/board_app/assign.css +91 -0
  9. forge/board_app/assign.js +157 -0
  10. forge/board_app/insights.js +80 -0
  11. forge/board_app/item.css +380 -0
  12. forge/board_app/item.js +594 -0
  13. forge/board_app/markdown.js +110 -0
  14. forge/board_app/now.css +417 -0
  15. forge/board_app/now.js +248 -0
  16. forge/board_app/pages.css +178 -0
  17. forge/board_app/releases.js +203 -0
  18. forge/board_app/shell.html +31 -0
  19. forge/board_app/tokens.css +220 -0
  20. forge/board_facts.py +696 -0
  21. forge/board_graph.py +38 -0
  22. forge/board_server.py +431 -0
  23. forge/board_trends.py +105 -0
  24. forge/box.py +54 -0
  25. forge/box_ssh.py +209 -0
  26. forge/checks.py +743 -0
  27. forge/citime.py +259 -0
  28. forge/claude_sdk.py +56 -0
  29. forge/claude_turn.py +62 -0
  30. forge/cli.py +185 -0
  31. forge/close.py +1193 -0
  32. forge/close_remote.py +85 -0
  33. forge/codex.py +1200 -0
  34. forge/codex_turn.py +346 -0
  35. forge/deny.py +253 -0
  36. forge/design.py +201 -0
  37. forge/design_skills.py +16 -0
  38. forge/docskip.py +175 -0
  39. forge/doctor.py +578 -0
  40. forge/event_log.py +128 -0
  41. forge/fasttest.py +846 -0
  42. forge/feature.py +318 -0
  43. forge/feature_api.py +593 -0
  44. forge/feature_python.py +1107 -0
  45. forge/feature_python_contracts.py +268 -0
  46. forge/feature_python_tests.py +1134 -0
  47. forge/feature_python_tools.py +81 -0
  48. forge/feature_remove.py +189 -0
  49. forge/feature_schema.py +156 -0
  50. forge/feature_tests.py +1062 -0
  51. forge/fullrun.py +166 -0
  52. forge/gaps.py +109 -0
  53. forge/githooks.py +251 -0
  54. forge/github.py +191 -0
  55. forge/init.py +494 -0
  56. forge/intake.py +226 -0
  57. forge/journey.py +126 -0
  58. forge/known_issues.py +165 -0
  59. forge/land.py +882 -0
  60. forge/machine.py +821 -0
  61. forge/merge.py +530 -0
  62. forge/merge_review.py +84 -0
  63. forge/merge_timings.py +46 -0
  64. forge/migrate.py +673 -0
  65. forge/migration_warnings.py +108 -0
  66. forge/mod/.claude-plugin/plugin.json +20 -0
  67. forge/mod/hooks/hooks.json +3 -0
  68. forge/mod/hooks/pane.test.ts +608 -0
  69. forge/mod/hooks/register.ts +413 -0
  70. forge/mod/tsconfig.json +18 -0
  71. forge/native.py +306 -0
  72. forge/nextstep.py +1184 -0
  73. forge/node_workers.cjs +26 -0
  74. forge/noise.py +40 -0
  75. forge/open_decisions.py +205 -0
  76. forge/owner_choices.py +167 -0
  77. forge/payback.py +97 -0
  78. forge/plain_english.py +20 -0
  79. forge/plan_scope.py +76 -0
  80. forge/prcheck.py +640 -0
  81. forge/quicktest.py +198 -0
  82. forge/records.py +912 -0
  83. forge/releases.py +100 -0
  84. forge/repo.py +1154 -0
  85. forge/review.py +1199 -0
  86. forge/review_process.py +86 -0
  87. forge/review_skip.py +116 -0
  88. forge/roles.py +141 -0
  89. forge/round_limits.py +7 -0
  90. forge/score.py +192 -0
  91. forge/spotted.py +271 -0
  92. forge/standards.md +318 -0
  93. forge/story.py +1200 -0
  94. forge/sync.py +783 -0
  95. forge/task.py +1082 -0
  96. forge/templates/adapters/AGENTS.md +98 -0
  97. forge/templates/brief.md +834 -0
  98. forge/templates/cold-read.md +324 -0
  99. forge/templates/conventions/api.md +144 -0
  100. forge/templates/conventions/backend.md +171 -0
  101. forge/templates/conventions/database.md +81 -0
  102. forge/templates/conventions/demo-data.md +61 -0
  103. forge/templates/conventions/deploy.md +114 -0
  104. forge/templates/conventions/frontend.md +187 -0
  105. forge/templates/conventions/python.md +336 -0
  106. forge/templates/conventions/security.md +44 -0
  107. forge/templates/conventions/stack.md +96 -0
  108. forge/templates/conventions/testing.md +165 -0
  109. forge/templates/delegation.md +3 -0
  110. forge/templates/design/render-check.d.mts +25 -0
  111. forge/templates/design/render-check.mjs +113 -0
  112. forge/templates/design/support.js +159 -0
  113. forge/templates/design/ui-checks.js +111 -0
  114. forge/templates/fde.md +218 -0
  115. forge/templates/feature/kinds.toml +140 -0
  116. forge/templates/handover.md +26 -0
  117. forge/templates/migrate-skill.md +87 -0
  118. forge/templates/records-only-action.yml +16 -0
  119. forge/templates/review-light.md +48 -0
  120. forge/templates/review-tests.py +200 -0
  121. forge/templates/review.md +661 -0
  122. forge/templates/run-reference.md +328 -0
  123. forge/templates/skeleton/.dockerignore +18 -0
  124. forge/templates/skeleton/Dockerfile +10 -0
  125. forge/templates/skeleton/docs/decisions/README.md +13 -0
  126. forge/templates/skeleton/docs/product/BRIEF.md +47 -0
  127. forge/templates/skeleton/docs/product/DISCOVERY.md +46 -0
  128. forge/templates/skeleton/docs/specs/README.md +41 -0
  129. forge/templates/skeleton/services.toml +6 -0
  130. forge/templates/skill.md +2753 -0
  131. forge/templates/skills/agents/SKILL.md +446 -0
  132. forge/templates/skills/agents/assistant-module/python/apps/api/app/assistant/README.md +131 -0
  133. forge/templates/skills/agents/assistant-module/python/apps/api/app/assistant/__init__.py +5 -0
  134. forge/templates/skills/agents/assistant-module/python/apps/api/app/assistant/chats.py +60 -0
  135. forge/templates/skills/agents/assistant-module/python/apps/api/app/assistant/cleanup.py +91 -0
  136. forge/templates/skills/agents/assistant-module/python/apps/api/app/assistant/models.py +57 -0
  137. forge/templates/skills/agents/assistant-module/python/apps/api/migrations/versions/20261106_assistant.py +90 -0
  138. forge/templates/skills/agents/assistant-module/python/apps/api/tests/test_assistant_chats.py +173 -0
  139. forge/templates/skills/agents/assistant-module/typescript/apps/api/prisma/migrations/20261106000000_assistant/migration.sql +17 -0
  140. forge/templates/skills/agents/assistant-module/typescript/apps/api/prisma/schema/assistant.prisma +19 -0
  141. forge/templates/skills/agents/assistant-module/typescript/apps/api/test/assistant-api.e2e-spec.ts +185 -0
  142. forge/templates/skills/agents/assistant-module/typescript/apps/api/test/assistant-chats.e2e-spec.ts +75 -0
  143. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/README.md +107 -0
  144. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/contracts/package.json +10 -0
  145. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/contracts/src/index.ts +66 -0
  146. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/contracts/tsconfig.json +12 -0
  147. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/server/package.json +23 -0
  148. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/server/src/assistant.chats.controller.ts +54 -0
  149. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/server/src/assistant.chats.service.ts +140 -0
  150. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/server/src/assistant.cleanup.ts +34 -0
  151. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/server/src/assistant.module.ts +20 -0
  152. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/server/src/index.ts +3 -0
  153. forge/templates/skills/agents/assistant-module/typescript/libs/assistant/server/tsconfig.json +15 -0
  154. forge/templates/skills/app-baseline/SKILL.md +241 -0
  155. forge/templates/skills/database/SKILL.md +155 -0
  156. forge/templates/skills/emil-design-eng/FORGE-NOTICE.md +9 -0
  157. forge/templates/skills/emil-design-eng/LICENSE +21 -0
  158. forge/templates/skills/emil-design-eng/SKILL.md +674 -0
  159. forge/templates/skills/impeccable/FORGE-NOTICE.md +10 -0
  160. forge/templates/skills/impeccable/LICENSE +191 -0
  161. forge/templates/skills/impeccable/NOTICE.md +11 -0
  162. forge/templates/skills/impeccable/SKILL.md +88 -0
  163. forge/templates/skills/impeccable/reference/adapt.md +318 -0
  164. forge/templates/skills/impeccable/reference/adapt.native.md +58 -0
  165. forge/templates/skills/impeccable/reference/android.md +46 -0
  166. forge/templates/skills/impeccable/reference/animate.md +89 -0
  167. forge/templates/skills/impeccable/reference/audit.md +139 -0
  168. forge/templates/skills/impeccable/reference/audit.native.md +139 -0
  169. forge/templates/skills/impeccable/reference/bolder.md +33 -0
  170. forge/templates/skills/impeccable/reference/clarify.md +94 -0
  171. forge/templates/skills/impeccable/reference/colorize.md +86 -0
  172. forge/templates/skills/impeccable/reference/component-review.md +63 -0
  173. forge/templates/skills/impeccable/reference/craft-floor.md +44 -0
  174. forge/templates/skills/impeccable/reference/craft.md +5 -0
  175. forge/templates/skills/impeccable/reference/critique.md +819 -0
  176. forge/templates/skills/impeccable/reference/degraded/asset-producer.md +42 -0
  177. forge/templates/skills/impeccable/reference/degraded/documenter.md +24 -0
  178. forge/templates/skills/impeccable/reference/degraded/finish-reviewer.md +38 -0
  179. forge/templates/skills/impeccable/reference/degraded/manual-edit-applier.md +92 -0
  180. forge/templates/skills/impeccable/reference/delight.md +70 -0
  181. forge/templates/skills/impeccable/reference/distill.md +111 -0
  182. forge/templates/skills/impeccable/reference/doctor.md +54 -0
  183. forge/templates/skills/impeccable/reference/document.md +416 -0
  184. forge/templates/skills/impeccable/reference/extract.md +69 -0
  185. forge/templates/skills/impeccable/reference/generate.md +101 -0
  186. forge/templates/skills/impeccable/reference/harden.md +362 -0
  187. forge/templates/skills/impeccable/reference/hooks.md +114 -0
  188. forge/templates/skills/impeccable/reference/init.md +131 -0
  189. forge/templates/skills/impeccable/reference/ios.md +51 -0
  190. forge/templates/skills/impeccable/reference/layout.md +84 -0
  191. forge/templates/skills/impeccable/reference/live-setup.md +104 -0
  192. forge/templates/skills/impeccable/reference/live.md +325 -0
  193. forge/templates/skills/impeccable/reference/mode-operate.md +21 -0
  194. forge/templates/skills/impeccable/reference/mode-persuade.md +19 -0
  195. forge/templates/skills/impeccable/reference/mode-read.md +21 -0
  196. forge/templates/skills/impeccable/reference/new-work.md +154 -0
  197. forge/templates/skills/impeccable/reference/onboard.md +234 -0
  198. forge/templates/skills/impeccable/reference/operate.md +61 -0
  199. forge/templates/skills/impeccable/reference/optimize.md +257 -0
  200. forge/templates/skills/impeccable/reference/overdrive.md +127 -0
  201. forge/templates/skills/impeccable/reference/polish.md +105 -0
  202. forge/templates/skills/impeccable/reference/quieter.md +99 -0
  203. forge/templates/skills/impeccable/reference/region-map.md +26 -0
  204. forge/templates/skills/impeccable/reference/routing.md +24 -0
  205. forge/templates/skills/impeccable/reference/shape.md +59 -0
  206. forge/templates/skills/impeccable/reference/typeset.md +90 -0
  207. forge/templates/skills/impeccable/reference/visualize.md +47 -0
  208. forge/templates/skills/impeccable/scripts/VERSION +1 -0
  209. forge/templates/skills/impeccable/scripts/command-metadata.json +98 -0
  210. forge/templates/skills/impeccable/scripts/data/font-index-failures.json +121 -0
  211. forge/templates/skills/impeccable/scripts/data/font-index.json +1 -0
  212. forge/templates/skills/impeccable/scripts/engine-checksums.txt +9 -0
  213. forge/templates/skills/impeccable/scripts/impeccable +249 -0
  214. forge/templates/skills/impeccable/scripts/impeccable.cmd +278 -0
  215. forge/templates/skills/impeccable/scripts/live-browser-dom.js +321 -0
  216. forge/templates/skills/impeccable/scripts/live-browser-ignores.js +247 -0
  217. forge/templates/skills/impeccable/scripts/live-browser-session.js +184 -0
  218. forge/templates/skills/impeccable/scripts/live-browser.js +13646 -0
  219. forge/templates/skills/impeccable/scripts/modern-screenshot.umd.js +15 -0
  220. forge/templates/skills/remote-approval/SKILL.md +40 -0
  221. forge/templates/skills/security-audit/AI-AND-LLM.md +83 -0
  222. forge/templates/skills/security-audit/ATTACK-CLASSES.md +130 -0
  223. forge/templates/skills/security-audit/CLIENT-SIDE.md +83 -0
  224. forge/templates/skills/security-audit/CLOUD-AND-DEPLOYMENT.md +86 -0
  225. forge/templates/skills/security-audit/DATA-ISOLATION-AND-LIFECYCLE.md +84 -0
  226. forge/templates/skills/security-audit/DESKTOP-MOBILE-AND-LOCAL-IPC.md +89 -0
  227. forge/templates/skills/security-audit/HUNTING.md +251 -0
  228. forge/templates/skills/security-audit/LICENSE +21 -0
  229. forge/templates/skills/security-audit/MEMORY-SAFETY-AND-BINARY.md +101 -0
  230. forge/templates/skills/security-audit/NOTICE.md +6 -0
  231. forge/templates/skills/security-audit/PROTOCOLS-RPC-AND-MESSAGING.md +81 -0
  232. forge/templates/skills/security-audit/RECONNAISSANCE.md +156 -0
  233. forge/templates/skills/security-audit/RESOURCE-EXHAUSTION-AND-AVAILABILITY.md +78 -0
  234. forge/templates/skills/security-audit/SKILL.md +192 -0
  235. forge/templates/skills/security-audit/SUPPLY-CHAIN-AND-RELEASE.md +73 -0
  236. forge/templates/skills/security-audit/VALIDATION-AND-REPORTING.md +186 -0
  237. forge/templates/skills/security-audit/WEB-PROTOCOL-AND-AUTH.md +105 -0
  238. forge/templates/skills/security-audit/report-schema.json +461 -0
  239. forge/templates/skills/security-audit/validate-coverage-ledger.cjs +873 -0
  240. forge/templates/skills/security-audit/validate-findings.cjs +774 -0
  241. forge/templates/skills/simplified-technical-english/LICENSE +28 -0
  242. forge/templates/skills/simplified-technical-english/NOTICE.md +33 -0
  243. forge/templates/skills/simplified-technical-english/SKILL.md +127 -0
  244. forge/templates/skills/simplified-technical-english/examples/before-after.md +86 -0
  245. forge/templates/skills/simplified-technical-english/references/substitutions.md +113 -0
  246. forge/templates/skills/simplified-technical-english/references/writing-rules.md +209 -0
  247. forge/templates/skills/simplified-technical-english/scripts/ste_check.py +301 -0
  248. forge/templates/skills/test-audit/NOTICE.md +25 -0
  249. forge/templates/skills/test-audit/SKILL.md +182 -0
  250. forge/templates/start.md +27 -0
  251. forge/templates/starter/.env.example +14 -0
  252. forge/templates/starter/.gitignore +7 -0
  253. forge/templates/starter/.npmrc +1 -0
  254. forge/templates/starter/Dockerfile +23 -0
  255. forge/templates/starter/README.md +121 -0
  256. forge/templates/starter/apps/api/package.json +15 -0
  257. forge/templates/starter/apps/api/prisma/migrations/20261022000000_initial/migration.sql +68 -0
  258. forge/templates/starter/apps/api/prisma/migrations/20261025000000_organisations/migration.sql +44 -0
  259. forge/templates/starter/apps/api/prisma/migrations/20261025000100_invites/migration.sql +18 -0
  260. forge/templates/starter/apps/api/prisma/migrations/20261025000200_history/migration.sql +13 -0
  261. forge/templates/starter/apps/api/prisma/migrations/20261025000300_soft_delete_only/migration.sql +10 -0
  262. forge/templates/starter/apps/api/prisma/migrations/20261026000000_extensions/migration.sql +3 -0
  263. forge/templates/starter/apps/api/prisma/migrations/20261026000100_ids_and_updated_at/migration.sql +31 -0
  264. forge/templates/starter/apps/api/prisma/migrations/20261026000150_module_schemas/migration.sql +19 -0
  265. forge/templates/starter/apps/api/prisma/migrations/20261026000200_columns/migration.sql +51 -0
  266. forge/templates/starter/apps/api/prisma/migrations/20261026000300_history_subjects/migration.sql +11 -0
  267. forge/templates/starter/apps/api/prisma/migrations/20261027000000_agents/migration.sql +12 -0
  268. forge/templates/starter/apps/api/prisma/migrations/20261027000100_mcp/migration.sql +20 -0
  269. forge/templates/starter/apps/api/prisma/migrations/20261028000000_via_agent/migration.sql +7 -0
  270. forge/templates/starter/apps/api/prisma/migrations/20261102000000_sign_in_attempts/migration.sql +13 -0
  271. forge/templates/starter/apps/api/prisma/migrations/20261104000000_notifications/migration.sql +23 -0
  272. forge/templates/starter/apps/api/prisma/migrations/migration_lock.toml +1 -0
  273. forge/templates/starter/apps/api/prisma/schema/auth.prisma +65 -0
  274. forge/templates/starter/apps/api/prisma/schema/base.prisma +9 -0
  275. forge/templates/starter/apps/api/prisma/schema/history.prisma +19 -0
  276. forge/templates/starter/apps/api/prisma/schema/mcp.prisma +18 -0
  277. forge/templates/starter/apps/api/prisma/schema/notifications.prisma +20 -0
  278. forge/templates/starter/apps/api/prisma/schema/organisations.prisma +66 -0
  279. forge/templates/starter/apps/api/prisma/schema/projects.prisma +23 -0
  280. forge/templates/starter/apps/api/project.json +35 -0
  281. forge/templates/starter/apps/api/src/app.module.ts +36 -0
  282. forge/templates/starter/apps/api/src/health/health.controller.ts +16 -0
  283. forge/templates/starter/apps/api/src/health/health.module.ts +5 -0
  284. forge/templates/starter/apps/api/src/main.ts +44 -0
  285. forge/templates/starter/apps/api/src/setup-company.ts +33 -0
  286. forge/templates/starter/apps/api/test/agents.e2e-spec.ts +99 -0
  287. forge/templates/starter/apps/api/test/api.e2e-spec.ts +250 -0
  288. forge/templates/starter/apps/api/test/auth.e2e-spec.ts +287 -0
  289. forge/templates/starter/apps/api/test/database.e2e-spec.ts +171 -0
  290. forge/templates/starter/apps/api/test/environment.e2e-spec.ts +56 -0
  291. forge/templates/starter/apps/api/test/error-reports.e2e-spec.ts +72 -0
  292. forge/templates/starter/apps/api/test/exports.e2e-spec.ts +85 -0
  293. forge/templates/starter/apps/api/test/helpers.ts +103 -0
  294. forge/templates/starter/apps/api/test/history.e2e-spec.ts +93 -0
  295. forge/templates/starter/apps/api/test/invites.e2e-spec.ts +262 -0
  296. forge/templates/starter/apps/api/test/mcp.e2e-spec.ts +269 -0
  297. forge/templates/starter/apps/api/test/notifications.e2e-spec.ts +117 -0
  298. forge/templates/starter/apps/api/test/one-company.e2e-spec.ts +154 -0
  299. forge/templates/starter/apps/api/test/organisations.e2e-spec.ts +210 -0
  300. forge/templates/starter/apps/api/test/projects.e2e-spec.ts +824 -0
  301. forge/templates/starter/apps/api/test/soft-delete.e2e-spec.ts +31 -0
  302. forge/templates/starter/apps/api/tsconfig.json +44 -0
  303. forge/templates/starter/apps/api/tsconfig.test.json +17 -0
  304. forge/templates/starter/apps/api/vitest.config.ts +13 -0
  305. forge/templates/starter/apps/web/e2e/motion.spec.ts +88 -0
  306. forge/templates/starter/apps/web/e2e/rules/accept-invite.spec.ts +59 -0
  307. forge/templates/starter/apps/web/e2e/rules/members.spec.ts +212 -0
  308. forge/templates/starter/apps/web/e2e/rules/reset-password.spec.ts +78 -0
  309. forge/templates/starter/apps/web/e2e/rules/sign-in.spec.ts +87 -0
  310. forge/templates/starter/apps/web/e2e/served-app.spec.ts +19 -0
  311. forge/templates/starter/apps/web/index.html +14 -0
  312. forge/templates/starter/apps/web/package.json +9 -0
  313. forge/templates/starter/apps/web/playwright.config.ts +21 -0
  314. forge/templates/starter/apps/web/project.json +36 -0
  315. forge/templates/starter/apps/web/src/index.css +166 -0
  316. forge/templates/starter/apps/web/src/main.tsx +14 -0
  317. forge/templates/starter/apps/web/src/shared-states.test.tsx +40 -0
  318. forge/templates/starter/apps/web/tsconfig.json +30 -0
  319. forge/templates/starter/apps/web/vite.config.ts +19 -0
  320. forge/templates/starter/apps/web/vitest.config.ts +23 -0
  321. forge/templates/starter/apps/web/vitest.setup.ts +5 -0
  322. forge/templates/starter/compose.test.yml +66 -0
  323. forge/templates/starter/eslint.config.mjs +56 -0
  324. forge/templates/starter/libs/auth/contracts/package.json +17 -0
  325. forge/templates/starter/libs/auth/contracts/project.json +15 -0
  326. forge/templates/starter/libs/auth/contracts/src/index.ts +56 -0
  327. forge/templates/starter/libs/auth/contracts/tsconfig.json +18 -0
  328. forge/templates/starter/libs/auth/server/package.json +19 -0
  329. forge/templates/starter/libs/auth/server/project.json +15 -0
  330. forge/templates/starter/libs/auth/server/src/agents.controller.ts +24 -0
  331. forge/templates/starter/libs/auth/server/src/auth.controller.ts +136 -0
  332. forge/templates/starter/libs/auth/server/src/auth.dto.ts +53 -0
  333. forge/templates/starter/libs/auth/server/src/auth.module.ts +18 -0
  334. forge/templates/starter/libs/auth/server/src/auth.service.ts +251 -0
  335. forge/templates/starter/libs/auth/server/src/index.ts +3 -0
  336. forge/templates/starter/libs/auth/server/src/invites.controller.ts +37 -0
  337. forge/templates/starter/libs/auth/server/src/members.controller.ts +47 -0
  338. forge/templates/starter/libs/auth/server/src/session.guard.ts +52 -0
  339. forge/templates/starter/libs/auth/server/tsconfig.json +29 -0
  340. forge/templates/starter/libs/core/server/package.json +17 -0
  341. forge/templates/starter/libs/core/server/project.json +19 -0
  342. forge/templates/starter/libs/core/server/src/common/account-principal.ts +8 -0
  343. forge/templates/starter/libs/core/server/src/common/admin-only.decorator.ts +18 -0
  344. forge/templates/starter/libs/core/server/src/common/all-exceptions.filter.ts +55 -0
  345. forge/templates/starter/libs/core/server/src/common/api-envelope.decorator.ts +28 -0
  346. forge/templates/starter/libs/core/server/src/common/api-response.dto.ts +26 -0
  347. forge/templates/starter/libs/core/server/src/common/api-zod.decorator.ts +21 -0
  348. forge/templates/starter/libs/core/server/src/common/authenticated-request.ts +7 -0
  349. forge/templates/starter/libs/core/server/src/common/common.module.ts +7 -0
  350. forge/templates/starter/libs/core/server/src/common/correlation.middleware.ts +12 -0
  351. forge/templates/starter/libs/core/server/src/common/csrf.guard.ts +35 -0
  352. forge/templates/starter/libs/core/server/src/common/csv.ts +14 -0
  353. forge/templates/starter/libs/core/server/src/common/current-account.decorator.ts +11 -0
  354. forge/templates/starter/libs/core/server/src/common/envelope.interceptor.ts +10 -0
  355. forge/templates/starter/libs/core/server/src/common/error-report.ts +43 -0
  356. forge/templates/starter/libs/core/server/src/common/json-logger.test.ts +95 -0
  357. forge/templates/starter/libs/core/server/src/common/json-logger.ts +57 -0
  358. forge/templates/starter/libs/core/server/src/common/permissions.ts +49 -0
  359. forge/templates/starter/libs/core/server/src/common/prompts.ts +42 -0
  360. forge/templates/starter/libs/core/server/src/common/public.decorator.ts +4 -0
  361. forge/templates/starter/libs/core/server/src/common/request-log.middleware.ts +19 -0
  362. forge/templates/starter/libs/core/server/src/common/resources.ts +88 -0
  363. forge/templates/starter/libs/core/server/src/common/retry-keys.ts +31 -0
  364. forge/templates/starter/libs/core/server/src/common/tools.test.ts +205 -0
  365. forge/templates/starter/libs/core/server/src/common/tools.ts +266 -0
  366. forge/templates/starter/libs/core/server/src/common/zod-validation.pipe.ts +22 -0
  367. forge/templates/starter/libs/core/server/src/config/environment.ts +95 -0
  368. forge/templates/starter/libs/core/server/src/index.ts +27 -0
  369. forge/templates/starter/libs/core/server/src/mail/mail.module.ts +19 -0
  370. forge/templates/starter/libs/core/server/src/mail/mail.provider.ts +22 -0
  371. forge/templates/starter/libs/core/server/src/prisma/prisma.module.ts +7 -0
  372. forge/templates/starter/libs/core/server/src/prisma/prisma.service.ts +19 -0
  373. forge/templates/starter/libs/core/server/tsconfig.json +23 -0
  374. forge/templates/starter/libs/core/web/package.json +16 -0
  375. forge/templates/starter/libs/core/web/project.json +15 -0
  376. forge/templates/starter/libs/core/web/src/api-client.ts +42 -0
  377. forge/templates/starter/libs/core/web/src/error-report.ts +12 -0
  378. forge/templates/starter/libs/core/web/src/form-errors.ts +18 -0
  379. forge/templates/starter/libs/core/web/src/index.ts +4 -0
  380. forge/templates/starter/libs/core/web/src/permissions.ts +9 -0
  381. forge/templates/starter/libs/core/web/src/query-client.ts +10 -0
  382. forge/templates/starter/libs/core/web/tsconfig.json +18 -0
  383. forge/templates/starter/libs/history/contracts/package.json +14 -0
  384. forge/templates/starter/libs/history/contracts/project.json +15 -0
  385. forge/templates/starter/libs/history/contracts/src/index.ts +2 -0
  386. forge/templates/starter/libs/history/contracts/src/service.ts +21 -0
  387. forge/templates/starter/libs/history/contracts/tsconfig.json +14 -0
  388. forge/templates/starter/libs/history/server/package.json +19 -0
  389. forge/templates/starter/libs/history/server/project.json +19 -0
  390. forge/templates/starter/libs/history/server/src/history.controller.ts +45 -0
  391. forge/templates/starter/libs/history/server/src/history.dto.ts +22 -0
  392. forge/templates/starter/libs/history/server/src/history.module.ts +12 -0
  393. forge/templates/starter/libs/history/server/src/history.service.test.ts +18 -0
  394. forge/templates/starter/libs/history/server/src/history.service.ts +42 -0
  395. forge/templates/starter/libs/history/server/src/index.ts +2 -0
  396. forge/templates/starter/libs/history/server/tsconfig.json +29 -0
  397. forge/templates/starter/libs/mcp/server/package.json +18 -0
  398. forge/templates/starter/libs/mcp/server/project.json +15 -0
  399. forge/templates/starter/libs/mcp/server/src/index.ts +1 -0
  400. forge/templates/starter/libs/mcp/server/src/mcp.controller.ts +102 -0
  401. forge/templates/starter/libs/mcp/server/src/mcp.module.ts +5 -0
  402. forge/templates/starter/libs/mcp/server/tsconfig.json +26 -0
  403. forge/templates/starter/libs/notifications/contracts/package.json +14 -0
  404. forge/templates/starter/libs/notifications/contracts/project.json +12 -0
  405. forge/templates/starter/libs/notifications/contracts/src/index.ts +1 -0
  406. forge/templates/starter/libs/notifications/contracts/src/service.ts +19 -0
  407. forge/templates/starter/libs/notifications/contracts/tsconfig.json +12 -0
  408. forge/templates/starter/libs/notifications/server/package.json +18 -0
  409. forge/templates/starter/libs/notifications/server/project.json +12 -0
  410. forge/templates/starter/libs/notifications/server/src/index.ts +1 -0
  411. forge/templates/starter/libs/notifications/server/src/notifications.controller.ts +21 -0
  412. forge/templates/starter/libs/notifications/server/src/notifications.dto.ts +28 -0
  413. forge/templates/starter/libs/notifications/server/src/notifications.module.ts +12 -0
  414. forge/templates/starter/libs/notifications/server/src/notifications.service.ts +36 -0
  415. forge/templates/starter/libs/notifications/server/tsconfig.json +18 -0
  416. forge/templates/starter/libs/organisations/contracts/package.json +14 -0
  417. forge/templates/starter/libs/organisations/contracts/project.json +15 -0
  418. forge/templates/starter/libs/organisations/contracts/src/index.ts +54 -0
  419. forge/templates/starter/libs/organisations/contracts/src/service.ts +29 -0
  420. forge/templates/starter/libs/organisations/contracts/tsconfig.json +14 -0
  421. forge/templates/starter/libs/organisations/server/package.json +20 -0
  422. forge/templates/starter/libs/organisations/server/project.json +15 -0
  423. forge/templates/starter/libs/organisations/server/src/index.ts +2 -0
  424. forge/templates/starter/libs/organisations/server/src/organisations.controller.ts +101 -0
  425. forge/templates/starter/libs/organisations/server/src/organisations.dto.ts +46 -0
  426. forge/templates/starter/libs/organisations/server/src/organisations.module.ts +14 -0
  427. forge/templates/starter/libs/organisations/server/src/organisations.service.ts +221 -0
  428. forge/templates/starter/libs/organisations/server/tsconfig.json +32 -0
  429. forge/templates/starter/libs/projects/contracts/package.json +14 -0
  430. forge/templates/starter/libs/projects/contracts/project.json +15 -0
  431. forge/templates/starter/libs/projects/contracts/src/index.ts +87 -0
  432. forge/templates/starter/libs/projects/contracts/tsconfig.json +14 -0
  433. forge/templates/starter/libs/projects/server/package.json +21 -0
  434. forge/templates/starter/libs/projects/server/project.json +15 -0
  435. forge/templates/starter/libs/projects/server/src/index.ts +2 -0
  436. forge/templates/starter/libs/projects/server/src/projects.controller.ts +165 -0
  437. forge/templates/starter/libs/projects/server/src/projects.dto.ts +77 -0
  438. forge/templates/starter/libs/projects/server/src/projects.module.ts +19 -0
  439. forge/templates/starter/libs/projects/server/src/projects.permissions.ts +7 -0
  440. forge/templates/starter/libs/projects/server/src/projects.service.ts +314 -0
  441. forge/templates/starter/libs/projects/server/src/projects.tools.ts +28 -0
  442. forge/templates/starter/libs/projects/server/tsconfig.json +29 -0
  443. forge/templates/starter/libs/shared/ui/components.json +21 -0
  444. forge/templates/starter/libs/shared/ui/package.json +27 -0
  445. forge/templates/starter/libs/shared/ui/project.json +15 -0
  446. forge/templates/starter/libs/shared/ui/src/components/states.tsx +73 -0
  447. forge/templates/starter/libs/shared/ui/src/components/theme-provider.tsx +39 -0
  448. forge/templates/starter/libs/shared/ui/src/components/ui/LICENSE +21 -0
  449. forge/templates/starter/libs/shared/ui/src/components/ui/alert-dialog.tsx +196 -0
  450. forge/templates/starter/libs/shared/ui/src/components/ui/alert.tsx +65 -0
  451. forge/templates/starter/libs/shared/ui/src/components/ui/avatar.tsx +108 -0
  452. forge/templates/starter/libs/shared/ui/src/components/ui/badge.tsx +47 -0
  453. forge/templates/starter/libs/shared/ui/src/components/ui/breadcrumb.tsx +108 -0
  454. forge/templates/starter/libs/shared/ui/src/components/ui/button.tsx +63 -0
  455. forge/templates/starter/libs/shared/ui/src/components/ui/card.tsx +91 -0
  456. forge/templates/starter/libs/shared/ui/src/components/ui/checkbox.tsx +29 -0
  457. forge/templates/starter/libs/shared/ui/src/components/ui/collapsible.tsx +33 -0
  458. forge/templates/starter/libs/shared/ui/src/components/ui/command.tsx +184 -0
  459. forge/templates/starter/libs/shared/ui/src/components/ui/dialog.tsx +158 -0
  460. forge/templates/starter/libs/shared/ui/src/components/ui/dropdown-menu.tsx +256 -0
  461. forge/templates/starter/libs/shared/ui/src/components/ui/empty.tsx +103 -0
  462. forge/templates/starter/libs/shared/ui/src/components/ui/form.tsx +167 -0
  463. forge/templates/starter/libs/shared/ui/src/components/ui/input.tsx +20 -0
  464. forge/templates/starter/libs/shared/ui/src/components/ui/label.tsx +23 -0
  465. forge/templates/starter/libs/shared/ui/src/components/ui/popover.tsx +88 -0
  466. forge/templates/starter/libs/shared/ui/src/components/ui/select.tsx +189 -0
  467. forge/templates/starter/libs/shared/ui/src/components/ui/separator.tsx +27 -0
  468. forge/templates/starter/libs/shared/ui/src/components/ui/sheet.tsx +142 -0
  469. forge/templates/starter/libs/shared/ui/src/components/ui/sidebar.tsx +726 -0
  470. forge/templates/starter/libs/shared/ui/src/components/ui/skeleton.tsx +13 -0
  471. forge/templates/starter/libs/shared/ui/src/components/ui/sonner.tsx +40 -0
  472. forge/templates/starter/libs/shared/ui/src/components/ui/switch.tsx +32 -0
  473. forge/templates/starter/libs/shared/ui/src/components/ui/table.tsx +115 -0
  474. forge/templates/starter/libs/shared/ui/src/components/ui/textarea.tsx +17 -0
  475. forge/templates/starter/libs/shared/ui/src/components/ui/tooltip.tsx +56 -0
  476. forge/templates/starter/libs/shared/ui/src/hooks/use-mobile.ts +19 -0
  477. forge/templates/starter/libs/shared/ui/src/lib/utils.ts +6 -0
  478. forge/templates/starter/libs/shared/ui/tsconfig.json +23 -0
  479. forge/templates/starter/libs/shared/util/package.json +14 -0
  480. forge/templates/starter/libs/shared/util/project.json +19 -0
  481. forge/templates/starter/libs/shared/util/src/csv-field.ts +6 -0
  482. forge/templates/starter/libs/shared/util/src/envelope.ts +9 -0
  483. forge/templates/starter/libs/shared/util/src/format.test.ts +33 -0
  484. forge/templates/starter/libs/shared/util/src/format.ts +43 -0
  485. forge/templates/starter/libs/shared/util/src/index.ts +12 -0
  486. forge/templates/starter/libs/shared/util/tsconfig.json +14 -0
  487. forge/templates/starter/nx.json +7 -0
  488. forge/templates/starter/package.json +97 -0
  489. forge/templates/starter/pnpm-lock.yaml +11587 -0
  490. forge/templates/starter/pnpm-workspace.yaml +4 -0
  491. forge/templates/starter/prisma.config.ts +13 -0
  492. forge/templates/starter/scripts/affected.mjs +27 -0
  493. forge/templates/starter/scripts/test-build.mjs +29 -0
  494. forge/templates/starter/scripts/test.mjs +107 -0
  495. forge/templates/starter/services.toml +7 -0
  496. forge/templates/starter/tsconfig.base.json +15 -0
  497. forge/templates/starter-python/.env.example +8 -0
  498. forge/templates/starter-python/.gitignore +13 -0
  499. forge/templates/starter-python/Dockerfile +30 -0
  500. forge/templates/starter-python/README.md +101 -0
  501. forge/templates/starter-python/apps/api/.python-version +1 -0
  502. forge/templates/starter-python/apps/api/alembic.ini +38 -0
  503. forge/templates/starter-python/apps/api/app/__init__.py +1 -0
  504. forge/templates/starter-python/apps/api/app/auth/__init__.py +27 -0
  505. forge/templates/starter-python/apps/api/app/auth/models.py +111 -0
  506. forge/templates/starter-python/apps/api/app/auth/routes.py +398 -0
  507. forge/templates/starter-python/apps/api/app/auth/schema.py +117 -0
  508. forge/templates/starter-python/apps/api/app/auth/service.py +453 -0
  509. forge/templates/starter-python/apps/api/app/core/__init__.py +89 -0
  510. forge/templates/starter-python/apps/api/app/core/admin.py +23 -0
  511. forge/templates/starter-python/apps/api/app/core/config.py +83 -0
  512. forge/templates/starter-python/apps/api/app/core/csv.py +40 -0
  513. forge/templates/starter-python/apps/api/app/core/database.py +21 -0
  514. forge/templates/starter-python/apps/api/app/core/envelope.py +40 -0
  515. forge/templates/starter-python/apps/api/app/core/error_report.py +85 -0
  516. forge/templates/starter-python/apps/api/app/core/errors.py +153 -0
  517. forge/templates/starter-python/apps/api/app/core/logging.py +66 -0
  518. forge/templates/starter-python/apps/api/app/core/mail.py +34 -0
  519. forge/templates/starter-python/apps/api/app/core/permissions.py +59 -0
  520. forge/templates/starter-python/apps/api/app/core/principal.py +12 -0
  521. forge/templates/starter-python/apps/api/app/core/prompts.py +96 -0
  522. forge/templates/starter-python/apps/api/app/core/resources.py +230 -0
  523. forge/templates/starter-python/apps/api/app/core/retry_keys.py +101 -0
  524. forge/templates/starter-python/apps/api/app/core/schema.py +13 -0
  525. forge/templates/starter-python/apps/api/app/core/security.py +197 -0
  526. forge/templates/starter-python/apps/api/app/core/tools.py +1117 -0
  527. forge/templates/starter-python/apps/api/app/history/__init__.py +5 -0
  528. forge/templates/starter-python/apps/api/app/history/models.py +48 -0
  529. forge/templates/starter-python/apps/api/app/history/routes.py +65 -0
  530. forge/templates/starter-python/apps/api/app/history/schema.py +29 -0
  531. forge/templates/starter-python/apps/api/app/history/service.py +77 -0
  532. forge/templates/starter-python/apps/api/app/main.py +115 -0
  533. forge/templates/starter-python/apps/api/app/mcp/__init__.py +3 -0
  534. forge/templates/starter-python/apps/api/app/mcp/server.py +192 -0
  535. forge/templates/starter-python/apps/api/app/notifications/__init__.py +5 -0
  536. forge/templates/starter-python/apps/api/app/notifications/models.py +62 -0
  537. forge/templates/starter-python/apps/api/app/notifications/routes.py +25 -0
  538. forge/templates/starter-python/apps/api/app/notifications/schema.py +39 -0
  539. forge/templates/starter-python/apps/api/app/notifications/service.py +70 -0
  540. forge/templates/starter-python/apps/api/app/openapi.py +17 -0
  541. forge/templates/starter-python/apps/api/app/organisations/__init__.py +10 -0
  542. forge/templates/starter-python/apps/api/app/organisations/models.py +128 -0
  543. forge/templates/starter-python/apps/api/app/organisations/routes.py +176 -0
  544. forge/templates/starter-python/apps/api/app/organisations/schema.py +76 -0
  545. forge/templates/starter-python/apps/api/app/organisations/service.py +403 -0
  546. forge/templates/starter-python/apps/api/app/projects/__init__.py +14 -0
  547. forge/templates/starter-python/apps/api/app/projects/models.py +67 -0
  548. forge/templates/starter-python/apps/api/app/projects/permissions.py +13 -0
  549. forge/templates/starter-python/apps/api/app/projects/routes.py +246 -0
  550. forge/templates/starter-python/apps/api/app/projects/schema.py +118 -0
  551. forge/templates/starter-python/apps/api/app/projects/service.py +359 -0
  552. forge/templates/starter-python/apps/api/app/projects/tools.py +28 -0
  553. forge/templates/starter-python/apps/api/app/setup_company.py +56 -0
  554. forge/templates/starter-python/apps/api/migrations/env.py +51 -0
  555. forge/templates/starter-python/apps/api/migrations/script.py.mako +25 -0
  556. forge/templates/starter-python/apps/api/migrations/versions/0001_initial.py +167 -0
  557. forge/templates/starter-python/apps/api/migrations/versions/0002_soft_delete_only.py +31 -0
  558. forge/templates/starter-python/apps/api/migrations/versions/0003_organisations.py +115 -0
  559. forge/templates/starter-python/apps/api/migrations/versions/0004_invites.py +58 -0
  560. forge/templates/starter-python/apps/api/migrations/versions/0005_history.py +51 -0
  561. forge/templates/starter-python/apps/api/migrations/versions/0006_extensions.py +22 -0
  562. forge/templates/starter-python/apps/api/migrations/versions/0007_ids_and_updated_at.py +52 -0
  563. forge/templates/starter-python/apps/api/migrations/versions/0008_module_schemas.py +42 -0
  564. forge/templates/starter-python/apps/api/migrations/versions/0009_columns.py +97 -0
  565. forge/templates/starter-python/apps/api/migrations/versions/0010_history_subjects.py +46 -0
  566. forge/templates/starter-python/apps/api/migrations/versions/0011_agents.py +44 -0
  567. forge/templates/starter-python/apps/api/migrations/versions/0012_mcp.py +71 -0
  568. forge/templates/starter-python/apps/api/migrations/versions/0013_via_agent.py +23 -0
  569. forge/templates/starter-python/apps/api/migrations/versions/20261103_sign_in_attempts.py +48 -0
  570. forge/templates/starter-python/apps/api/migrations/versions/20261105_notifications.py +84 -0
  571. forge/templates/starter-python/apps/api/pyproject.toml +86 -0
  572. forge/templates/starter-python/apps/api/tests/conftest.py +146 -0
  573. forge/templates/starter-python/apps/api/tests/test_agents.py +169 -0
  574. forge/templates/starter-python/apps/api/tests/test_api.py +319 -0
  575. forge/templates/starter-python/apps/api/tests/test_auth.py +428 -0
  576. forge/templates/starter-python/apps/api/tests/test_config.py +58 -0
  577. forge/templates/starter-python/apps/api/tests/test_database.py +204 -0
  578. forge/templates/starter-python/apps/api/tests/test_error_reports.py +119 -0
  579. forge/templates/starter-python/apps/api/tests/test_history.py +206 -0
  580. forge/templates/starter-python/apps/api/tests/test_invites.py +427 -0
  581. forge/templates/starter-python/apps/api/tests/test_logging.py +56 -0
  582. forge/templates/starter-python/apps/api/tests/test_mcp.py +556 -0
  583. forge/templates/starter-python/apps/api/tests/test_module_schemas.py +100 -0
  584. forge/templates/starter-python/apps/api/tests/test_notifications.py +182 -0
  585. forge/templates/starter-python/apps/api/tests/test_one_company.py +188 -0
  586. forge/templates/starter-python/apps/api/tests/test_organisations.py +231 -0
  587. forge/templates/starter-python/apps/api/tests/test_projects.py +874 -0
  588. forge/templates/starter-python/apps/api/tests/test_soft_delete.py +80 -0
  589. forge/templates/starter-python/apps/api/tests/test_tools.py +395 -0
  590. forge/templates/starter-python/apps/api/uv.lock +1277 -0
  591. forge/templates/starter-python/compose.test.yml +63 -0
  592. forge/templates/starter-python/eslint.config.mjs +49 -0
  593. forge/templates/starter-python/libs/auth/contracts/package.json +17 -0
  594. forge/templates/starter-python/libs/auth/contracts/src/index.ts +51 -0
  595. forge/templates/starter-python/libs/auth/contracts/tsconfig.json +16 -0
  596. forge/templates/starter-python/libs/history/contracts/package.json +17 -0
  597. forge/templates/starter-python/libs/history/contracts/src/index.ts +3 -0
  598. forge/templates/starter-python/libs/history/contracts/tsconfig.json +16 -0
  599. forge/templates/starter-python/libs/organisations/contracts/package.json +17 -0
  600. forge/templates/starter-python/libs/organisations/contracts/src/index.ts +30 -0
  601. forge/templates/starter-python/libs/organisations/contracts/tsconfig.json +16 -0
  602. forge/templates/starter-python/libs/projects/contracts/package.json +17 -0
  603. forge/templates/starter-python/libs/projects/contracts/src/index.ts +65 -0
  604. forge/templates/starter-python/libs/projects/contracts/tsconfig.json +16 -0
  605. forge/templates/starter-python/libs/shared/api-types/package.json +14 -0
  606. forge/templates/starter-python/libs/shared/api-types/tsconfig.json +14 -0
  607. forge/templates/starter-python/package.json +71 -0
  608. forge/templates/starter-python/pnpm-lock.yaml +7574 -0
  609. forge/templates/starter-python/pnpm-workspace.yaml +4 -0
  610. forge/templates/starter-python/scripts/affected.mjs +20 -0
  611. forge/templates/starter-python/scripts/test-browser.mjs +39 -0
  612. forge/templates/starter-python/scripts/test.mjs +86 -0
  613. forge/templates/starter-python/services.toml +7 -0
  614. forge/templates/story.md +89 -0
  615. forge/time_records.py +1022 -0
  616. forge/ui_checks.py +97 -0
  617. forge/upgrade.py +368 -0
  618. forge/worker.py +876 -0
  619. symphony_forge-1.2.44.dist-info/METADATA +7 -0
  620. symphony_forge-1.2.44.dist-info/RECORD +623 -0
  621. symphony_forge-1.2.44.dist-info/WHEEL +4 -0
  622. symphony_forge-1.2.44.dist-info/entry_points.txt +2 -0
  623. symphony_forge-1.2.44.dist-info/licenses/LICENSE +21 -0
forge/board.py ADDED
@@ -0,0 +1,1197 @@
1
+ """`forge board`: the facts behind the live board page (board_server.py) and `--json`: each story's
2
+ history and current state in plain English, how long each step took, which steps were slow, and the
3
+ three success numbers. `forge next` shows those numbers in one line once the check date is here.
4
+
5
+ It reads every copy of the state: in local worktrees, on Forge's branches on the remote, and on the
6
+ default branch. Steps are only ever added, so the copy with the most dated steps is the newest. gh
7
+ adds each pull request's title, summary line, merge date and when its checks passed; close stores
8
+ none of those. Without gh the board shows the state and its dates only.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import copy
13
+ import functools
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import statistics
19
+ import subprocess
20
+ import sys
21
+ from concurrent.futures import ThreadPoolExecutor
22
+ from datetime import datetime, timedelta, timezone
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from forge import __version__, approval, board_facts, board_graph, codex, machine, native, repo, review_skip, story, task
27
+
28
+ COMMANDS = [{
29
+ "words": "board", "run": "board", "changes_state": False,
30
+ "help": "Open the live board page on this computer",
31
+ "args": [(('--json',), {"action": "store_true", "help": "Print the machine view"}),
32
+ (('--out',), {"metavar": "PATH", "help": "write every item's facts here as JSON instead"})],
33
+ "position": 60,
34
+ "listing": "| `forge board` | Opens the live board page on this computer; stops after 30 minutes with no page open or Ctrl-C (`--out <path>` writes every item's facts as JSON instead) |",
35
+ }]
36
+
37
+ CHECK_DATE = "2026-11-15" # ponytail: the rebuild's check date, from the spec's success measure
38
+ PREFIXES = ("story/", "task/", "fix/", "forge/") # the branches Forge starts; forge/ is migrate's
39
+ STATE = re.compile(r"\.factory/(?:stories/(?P<key>[A-Z][A-Z0-9-]*)/(?:story|tasks/(?P<task>[A-Z0-9][A-Z0-9-]*))"
40
+ r"|fixes/(?P<fix>[a-z0-9][a-z0-9-]*))\.json")
41
+ # ponytail: a merged fix "fixed Forge" when it changed Forge's own files; widen once a miss shows up.
42
+ FORGE_FILES = ("forge.toml", ".claude/", ".codex/", ".github/workflows/forge.yml", "src/forge/")
43
+ STATUS = {"started": "Waiting to start", "working": "In progress", "reviewing": "Under review",
44
+ "fixing": "Needs fixes", "waiting for checks": "Checks running",
45
+ "ready": "Ready to merge", "hotspot": "Needs your decision"}
46
+
47
+ Item = dict[str, Any]
48
+
49
+
50
+ def board(args: Any) -> int:
51
+ from forge import known_issues
52
+
53
+ top = repo.root()
54
+ with repo.command_cache(snapshot=True):
55
+ repo.forge_dir(top)
56
+ repo.default_branch(top)
57
+ def local_history():
58
+ from forge import backfill, time_records
59
+ _event_history(top)
60
+ for pr in backfill.people(top):
61
+ time_records.view_body(pr.get("body") or "")
62
+ reads[1].result()
63
+ known_issues.inventory(top)
64
+ with ThreadPoolExecutor(max_workers=4) as pool:
65
+ if args.json:
66
+ reads = pool.submit(_machine_prs, top), pool.submit(board_facts.prs, top)
67
+ local = pool.submit(local_history)
68
+ if (args.json or args.out) and repo.run(
69
+ "git", "fetch", "-q", "--prune", "--tags", "origin", cwd=top).returncode:
70
+ print("Could not refresh work from GitHub; showing the local git records.", file=sys.stderr)
71
+ if args.json:
72
+ view = machine_board(top, reads=reads)
73
+ local.result()
74
+ print(json.dumps(view))
75
+ return 0
76
+ if not args.out:
77
+ from forge import board_server
78
+ return board_server.serve(top)
79
+ out = Path(args.out) # every item, finished ones included: what the live page's other pages read
80
+ out.parent.mkdir(parents=True, exist_ok=True)
81
+ out.write_bytes(json.dumps(machine_board(top, trim=False)).encode("utf-8")) # same bytes on Windows
82
+ print(f"Wrote the board to {out}")
83
+ return 0
84
+
85
+
86
+ def repo_root(top: Path) -> str:
87
+ """The main worktree identifies a repo across all of its worktrees."""
88
+ listing = repo.git("worktree", "list", "--porcelain", cwd=top)
89
+ return str(Path(listing.splitlines()[0].removeprefix("worktree ")).resolve())
90
+
91
+
92
+ def _machine_prs(top: Path) -> list[Item]:
93
+ return board_facts.machine_prs(top)
94
+
95
+
96
+ def _checks(pr: Item | None, required: list[str]) -> tuple[str, list[Item], list[Item]]:
97
+ if not pr:
98
+ return "unknown", [], []
99
+ try:
100
+ commit = pr["commits"]["nodes"][-1]["commit"]
101
+ if not pr.get("headRefOid") or commit.get("oid") != pr["headRefOid"]:
102
+ return "unknown", [], []
103
+ contexts = commit["statusCheckRollup"]["contexts"]
104
+ nodes = contexts["nodes"]
105
+ if not isinstance(nodes, list):
106
+ return "unknown", [], []
107
+ except (KeyError, TypeError, IndexError):
108
+ return "unknown", [], []
109
+ statuses, events, names, failures = [], [], [], []
110
+ workflows = set()
111
+ for check in nodes:
112
+ if not isinstance(check, dict):
113
+ continue
114
+ name = check.get("name") or check.get("context") or "Check"
115
+ suite = check.get("checkSuite") or {}
116
+ workflow = (suite.get("workflowRun") or {}).get("workflow") or {}
117
+ workflow_id = workflow.get("id")
118
+ if (workflow_id and suite.get("status") == "COMPLETED" and suite.get("conclusion")
119
+ and workflow_id not in workflows):
120
+ workflows.add(workflow_id)
121
+ result = {"SUCCESS": "passed", "FAILURE": "failed", "TIMED_OUT": "timed out",
122
+ "CANCELLED": "cancelled", "ACTION_REQUIRED": "needs action",
123
+ "STARTUP_FAILURE": "failed to start", "NEUTRAL": "neutral",
124
+ "SKIPPED": "skipped", "STALE": "stale"}.get(
125
+ suite["conclusion"], suite["conclusion"].lower().replace("_", " "))
126
+ events.append({"id": f"workflow:{workflow_id}:{pr['headRefOid']}",
127
+ "kind": "run_finished", "title": f"{workflow['name']} {result}",
128
+ "conclusion": suite["conclusion"]})
129
+ names.append(name)
130
+ value = (check.get("conclusion") if check.get("status") == "COMPLETED" else None) or check.get("state")
131
+ failed = (value in ("FAILURE", "ERROR", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "STALE")
132
+ or value in ("NEUTRAL", "SKIPPED") and
133
+ any(name == want or name.startswith(want + " (") for want in required))
134
+ statuses.append("fail" if failed else "pass" if value in ("SUCCESS", "NEUTRAL", "SKIPPED")
135
+ else "running" if value in ("PENDING", "EXPECTED") or check.get("status") in
136
+ ("QUEUED", "IN_PROGRESS", "WAITING", "PENDING", "REQUESTED") else "unknown")
137
+ if failed:
138
+ failures.append({"job": name, "cause": "timeout" if value == "TIMED_OUT" or
139
+ value == "CANCELLED" and check.get("timeout") is True else "failed"})
140
+ identity = (f"check-run:{check['databaseId']}:{check['completedAt']}"
141
+ if check.get("databaseId") is not None and check.get("completedAt")
142
+ else f"status:{check['id']}" if check.get("__typename") == "StatusContext" and check.get("id") else None)
143
+ if identity and not workflow:
144
+ events.append({"id": identity, "kind": "checks_failed", "title": f"{name} failed"})
145
+ missing = any(not any(n == want or n.startswith(want + " (") for n in names) for want in required)
146
+ status = ("fail" if "fail" in statuses else "running" if "running" in statuses else
147
+ "unknown" if not statuses or "unknown" in statuses or missing or
148
+ contexts.get("pageInfo", {}).get("hasNextPage") else "pass")
149
+ return status, events, failures
150
+
151
+
152
+ def _rollup(pr: Item) -> list[Item]:
153
+ try:
154
+ commit = pr["commits"]["nodes"][-1]["commit"]
155
+ if not pr.get("headRefOid") or commit.get("oid") != pr["headRefOid"]:
156
+ return []
157
+ nodes = commit["statusCheckRollup"]["contexts"]["nodes"]
158
+ return [{**n, "startedAt": n.get("createdAt")} if n.get("__typename") == "StatusContext" else n
159
+ for n in nodes if isinstance(n, dict)] if isinstance(nodes, list) else []
160
+ except (KeyError, TypeError, IndexError):
161
+ return []
162
+
163
+
164
+ def _event_history(top: Path) -> tuple[list[Item], dict[str, list[Item]]]:
165
+ def read():
166
+ from forge import event_log
167
+ recorded, by_item = event_log.read(top), {}
168
+ for event in recorded:
169
+ by_item.setdefault(event.get("item"), []).append(event)
170
+ return recorded, by_item
171
+ return repo.command_fact("board events", top, read)
172
+
173
+
174
+ def active_runs(top: Path, item: str, activity: list[Item] | None = None,
175
+ round_number: int | None = None) -> list[Item]:
176
+ if activity is None:
177
+ activity = _event_history(top)[1].get(item, [])
178
+ ended = {e.get("run_id") for e in activity if e.get("event") == "run end"}
179
+ runs = []
180
+ for event in activity:
181
+ if (event.get("event") != "run start" or event.get("id") in ended
182
+ or round_number is not None and event.get("round") is not None
183
+ and event["round"] != round_number):
184
+ continue
185
+ kind = event.get("kind")
186
+ if kind in ("work", "worker") or kind == "read" and event.get("family") == "codex":
187
+ if not native.worker_alive(top, item, kind, event.get("round")):
188
+ continue
189
+ runs.append(event)
190
+ return runs
191
+
192
+
193
+ @repo.command_cache(snapshot=True)
194
+ def machine_board(top: Path, history: Item | None = None, trim: bool = True, cache: Item | None = None,
195
+ reads: tuple[Any, Any] | None = None) -> Item:
196
+ """Stories and fixes, with tasks one level down. No invented run times or occurrence ids.
197
+ `trim` leaves out work finished more than seven days ago; the page keeps it. With the live page's
198
+ `cache`, only rows whose inputs changed are derived again, listed in `cache["rebuilt"]`."""
199
+ from forge import backfill, known_issues, nextstep, releases, time_records
200
+
201
+ repo.forge_dir(top)
202
+ repo.default_branch(top)
203
+ trees = story.worktrees(top)
204
+ configuration = functools.cache(lambda path: nextstep._report_config(path, {}))
205
+ # Fetch independent GitHub views while local Git supplies the state snapshot.
206
+ with ThreadPoolExecutor(max_workers=4) as pool:
207
+ checks_read, github_read = reads or (pool.submit(_machine_prs, top), pool.submit(board_facts.prs, top))
208
+ viewer_read = pool.submit(board_facts._cached, top, "viewer-login", lambda _: task.github_login(top), stale=True)
209
+ dates_read = (pool.submit(releases.dates, top) if any(
210
+ releases.VERSION.fullmatch(tag) for tag in repo.git("tag", "--list", cwd=top).splitlines()) else None)
211
+ authors_read = pool.submit(_starters, top)
212
+ history = history if history is not None else _machine_history(top)
213
+ prs, github = checks_read.result(), github_read.result()
214
+ viewer = viewer_read.result()
215
+ if dates_read is not None:
216
+ dates_read.result()
217
+ authors_read.result()
218
+ if not trim:
219
+ history = {**history, "expired": set()}
220
+ landed = history["landed"]
221
+ best: dict[str, tuple[Item, Path | str]] = {}
222
+ step_counts = history["step_counts"]
223
+ merged = set()
224
+ for rel, state, where in history["copies"]:
225
+ if where == landed:
226
+ merged.add(rel)
227
+ if (rel not in best or step_counts[id(state)] > step_counts[id(best[rel][0])] or
228
+ step_counts[id(state)] == step_counts[id(best[rel][0])] and where == trees.get(state.get("branch"))):
229
+ best[rel] = state, where
230
+ by_branch = {p.get("headRefName"): p for p in prs}
231
+ # Older open PRs keep their number, but deliberately have unknown checks.
232
+ people_prs = board_facts.prs(top, people=True)
233
+ past_people = backfill.people(top)
234
+ by_branch = {**{pr["headRefName"]: pr for pr in past_people}, **by_branch}
235
+ people_branches = {}
236
+ for pr in [*past_people, *(people_prs or {}).get("open", []), *board_facts.merged_prs(people_prs)]:
237
+ if isinstance(branch := pr.get("headRefName"), str):
238
+ previous = people_branches.get(branch, {})
239
+ people_branches[branch] = {**pr, **{
240
+ field: pr.get(field) or previous.get(field) for field in ("author", "mergedBy")}}
241
+ names = {("email", email): name for email, name in _display_names(top).items()}
242
+ for pr in sorted([*people_branches.values(), *past_people],
243
+ key=lambda pr: pr.get("mergedAt") or "", reverse=True):
244
+ for actor in (pr.get("author"), pr.get("mergedBy")):
245
+ if actor and actor.get("name"):
246
+ board_facts.person(actor, names=names)
247
+ actors = time_records.view_body(pr.get("body") or "")
248
+ for field in ("started_by", "approved_by"):
249
+ board_facts.person(actors, field=field, names=names)
250
+ for pr in (github or {}).get("open", []):
251
+ if isinstance(pr.get("headRefName"), str):
252
+ by_branch[pr["headRefName"]] = {**by_branch.get(pr["headRefName"], {}), **pr}
253
+ finished_prs = board_facts.merged_prs(github)
254
+ remembered = {branch for branch, pr in people_branches.items() if pr.get("author") or pr.get("mergedBy")}
255
+ merged_prs = {pr["headRefName"] for pr in finished_prs}
256
+ # The upgrade's six-week history is visible immediately, including older finished rows.
257
+ history = {**history, "expired": history["expired"] - {
258
+ rel for rel, (state, _) in best.items()
259
+ if state.get("branch") in remembered | merged_prs}}
260
+ by_branch.update({p["headRefName"]: p for p in finished_prs})
261
+ merged_details = {p["headRefName"]: p for p in finished_prs}
262
+ # Rows and counts must read the same published drop or restore, even with a stale worktree.
263
+ for rel, (state, where) in list(best.items()):
264
+ if fix := STATE.fullmatch(rel)["fix"]:
265
+ if rel not in merged and state.get("branch") not in merged_prs:
266
+ state = nextstep.at_ref(top, fix, state, by_branch.get(state.get("branch")))
267
+ best[rel] = state, where
268
+ dropped = {STATE.fullmatch(rel)["key"] for rel, (state, _) in best.items()
269
+ if rel.endswith("/story.json") and state.get("status") == "dropped"}
270
+ promoted = {state["from_fix"] for state, _ in best.values() if state.get("from_fix")}
271
+ best = {rel: pair for rel, pair in best.items()
272
+ if pair[0].get("status") != "dropped" and STATE.fullmatch(rel)["fix"] not in promoted}
273
+ readiness: dict[str, Item] = {}
274
+ person_waits: dict[str, list[Item]] = {} # each part's and fix's waits on a person, for Needs you
275
+ roadmap = {s["key"]: s for s in repo.roadmap(top) if s.get("status") != "superseded" and s["key"] not in dropped}
276
+ completed = {key: state for key, state in history["stories"].items() if state.get("status") == "done"}
277
+ completed.update({key: state for key, state in roadmap.items() if state.get("status") == "done"})
278
+ completed.update({STATE.fullmatch(rel)["key"]: state for rel, (state, _) in best.items()
279
+ if rel.endswith("/story.json") and state.get("status") == "done"})
280
+ recorded, by_item = _event_history(top)
281
+ story_event_dates: dict[str, list[Any]] = {}
282
+ for event in recorded:
283
+ key, separator, _ = str(event.get("item", "")).partition("/")
284
+ if separator:
285
+ story_event_dates.setdefault(key, []).append(event.get("at"))
286
+ timings = time_records.read(top, "timings")
287
+
288
+ refs = [line.split("\0") for line in repo.git(
289
+ "for-each-ref", "--format=%(refname:short)%00%(committerdate:iso-strict)%00%(objectname)"
290
+ "%00%(objecttype)%00%(taggerdate:iso-strict)%00%(refname)",
291
+ "refs/heads", "refs/remotes/origin", "refs/tags", cwd=top).splitlines()]
292
+ tag_refs = [(ref.removeprefix("refs/tags/"), kind, at) for _, _, _, kind, at, ref in refs
293
+ if ref.startswith("refs/tags/")]
294
+ refs = [(name, date, tip) for name, date, tip, _, _, ref in refs if not ref.startswith("refs/tags/")]
295
+ branch_dates = {name: date for name, date, _ in refs}
296
+ tips = {name: tip for name, _, tip in refs}
297
+ timing_dates: dict[str, list[str]] = {}
298
+ timings_by_item: dict[Any, list[Item]] = {}
299
+ for timing in timings:
300
+ timings_by_item.setdefault(timing.get("item"), []).append(timing)
301
+ start = _when(timing.get("start"))
302
+ if start:
303
+ end = start + timedelta(seconds=timing.get("seconds") or 0)
304
+ timing_dates.setdefault(timing.get("item"), []).append(end.isoformat())
305
+
306
+ owners = {}
307
+
308
+ @functools.cache
309
+ def story_read(key: str) -> tuple[str, Item]:
310
+ """A story's plan read and task rows: the same for the story and each of its parts."""
311
+ where = landed if key in completed else story.plan_ref(top, key, history) # finished: the landed plan
312
+ if where == f"story/{key}":
313
+ where = trees.get(where) or where
314
+ notes = _read(top, where, f"plans/{key}.read.md", history)
315
+ plan = story._plan(top, key, landed if key in completed else None, history)
316
+ owners[key] = task.owner(plan)
317
+ assignments = task.rows(task.sections(plan))
318
+ if not story._record(notes)[0]:
319
+ return "none", assignments
320
+ text = _read(top, where, f"plans/{key}.md", history)
321
+ digest = repo.blob_hash(text)
322
+ try:
323
+ story.gate(key, f"plans/{key}.md", notes, digest, text, top)
324
+ return "passed", assignments
325
+ except repo.Refused:
326
+ return "blocked", assignments
327
+
328
+ forge_files = repo.forge_dir(top)
329
+ people = "" if cache is None else repo.blob_hash(json.dumps(sorted(map(str, names.items())))) # in every row
330
+ files = [] if cache is None else [ # Forge's per-item records: locks, turn logs, approvals
331
+ (path.relative_to(forge_files).as_posix(), path.stat().st_mtime_ns)
332
+ for path in forge_files.rglob("*") if path.is_file()]
333
+ docs = {} if cache is None else {name: repo.blob_hash(text) for name, text in history.get("docs", {}).items()}
334
+ local = [] if cache is None else [entry for entry in cache.get("local", []) # records and plans on disk
335
+ if entry[1] not in ("forge.toml", "plans/roadmap.json")]
336
+ starters = {} if cache is None else _starters(top)
337
+
338
+ def row(item: str, kind: str, title: str, state: Item, where: Path | str) -> Item:
339
+ if cache is None:
340
+ return derive(item, kind, title, state, where)
341
+ # ponytail: a row's inputs are the facts that name its story or fix, a substring match that can
342
+ # over-include (SHOP-1 in SHOP-10) and only rebuilds more; a fact naming neither is not an input.
343
+ own = item.split("/")[0]
344
+ inputs = json.dumps([
345
+ # A story's next step reads the default branch, so a story row also rebuilds when it moves.
346
+ item, kind, title, state, str(where), tips.get(str(where)) if where != landed else None,
347
+ tips.get(landed) if kind == "story" else None, [entry for entry in local if own in entry[0] + entry[1]],
348
+ [(name, blob) for name, blob in docs.items() if own in name],
349
+ completed.get(own), starters.get(repo.state_path(item)), people,
350
+ [(branch, pr) for branch, pr in people_branches.items() if own in branch],
351
+ [(ref, tip) for ref, tip in tips.items() if own in ref],
352
+ [(branch, pr) for branch, pr in by_branch.items() if own in str(branch)],
353
+ sorted(rel for rel in merged if own in rel), [(rel, at) for rel, at in history["dates"].items() if own in rel],
354
+ [(rel, part) for rel, (part, _) in best.items() if own in rel],
355
+ [(name, e) for name, e in by_item.items() if own in str(name)],
356
+ [(name, t) for name, t in timings_by_item.items() if own in str(name)],
357
+ [f for f in files if own in f[0]]], sort_keys=True, default=str) # hashed below, kept small to save
358
+ kept, inputs = cache["rows"].get(item), repo.blob_hash(inputs)
359
+ if kept and kept[0] == inputs:
360
+ made, ready, waits, owner = copy.deepcopy(kept[1])
361
+ if owner is not None: # the story's owner, which its unstarted parts read after the rows
362
+ owners.setdefault(own, owner)
363
+ if made["idle_since"] and (now := _when(repo.now())) and _when(made["idle_since"]):
364
+ made["idle_seconds"] = max(0, (now - _when(made["idle_since"])).total_seconds())
365
+ made["stalled"] = made["idle_seconds"] > 86400
366
+ else:
367
+ made = derive(item, kind, title, state, where)
368
+ ready, waits = readiness.get(item), person_waits.get(item)
369
+ cache["rebuilt"].append(item)
370
+ running = made["worker"] or made["tests"] or made["activity"]["status"] == "running" # times move
371
+ kept = [made, ready, waits, owners.get(own)]
372
+ cache["rows"][item] = None if running else (inputs, copy.deepcopy(kept))
373
+ if ready is not None:
374
+ readiness[item] = ready
375
+ if waits is not None:
376
+ person_waits[item] = waits
377
+ return made
378
+
379
+ def derive(item: str, kind: str, title: str, state: Item, where: Path | str) -> Item:
380
+ if kind == "story" and item in completed:
381
+ state = {**state, **completed[item], "status": "done"}
382
+ elif kind == "task" and item.split("/")[0] in completed:
383
+ state = {**state, "status": "merged"}
384
+ if kind != "story" and repo.state_path(item) in merged:
385
+ state = {**state, "status": "merged"}
386
+ branch = state.get("branch") or (f"task/{item.replace('/', '-')}" if kind == "task"
387
+ else f"{kind}/{item}")
388
+ if kind != "story" and branch in merged_prs:
389
+ state = {**state, "status": "merged"}
390
+ tree = trees.get(branch)
391
+ cfg = configuration(tree or top)
392
+ pr = by_branch.get(branch)
393
+ state = nextstep.at_ref(top, item, state, pr) if kind != "story" else state
394
+ checks, events, failures = _checks(pr, cfg["checks"])
395
+ plan_text = ""
396
+ if state.get("status") == "done" or (state.get("status") == "merged" and not tree):
397
+ lines = [f"{title} is finished."]
398
+ elif not state and kind == "story":
399
+ lines = [f"{title} needs a story doc.", f'Next: forge story new {item} {json.dumps(title)}']
400
+ else:
401
+ try:
402
+ if kind == "story":
403
+ plan_text = _read(top, tree or where, f"plans/{item}.md", history)
404
+ if kind == "story" and item in history.get("story advice", {}):
405
+ lines, readiness[item] = history["story advice"][item]
406
+ else:
407
+ lines = (nextstep._item(item, title, state, top, tree, by_branch, {}) if kind != "story"
408
+ else nextstep._story(top, item, tree, plan_text,
409
+ title, trees, merged_prs, by_branch, {}, history,
410
+ readiness.setdefault(item, {}))[0])
411
+ except (repo.Refused, subprocess.CalledProcessError):
412
+ lines = [f"Couldn't check the next step for {title}; check the connection, then run forge next."]
413
+ review = state.get("review") or {}
414
+ dismissed = {d.get("finding") for d in review.get("dismissals", [])
415
+ if isinstance(d, dict)}
416
+ findings = [{"title": f.get("title") or "Untitled finding", "priority": f.get("priority")} for n, f in
417
+ enumerate(review.get("findings", []), 1)
418
+ if isinstance(f, dict) and n not in dismissed]
419
+ worker = None
420
+ finished = state.get("status") in ("done", "merged")
421
+ if not finished and native.lock_alive(codex._item_file(
422
+ top, item, ".lock", "Grill" if kind == "story" else "Build")) is not False:
423
+ family = state.get("worker")
424
+ role = "grill" if kind == "story" else "build" if kind == "task" else "lite"
425
+ if family == "codex" and kind != "story":
426
+ turns = codex._item_file(top, item, ".log", "Build")
427
+ for line in turns.read_text(encoding="utf-8").splitlines() if turns.is_file() else []:
428
+ try:
429
+ turn = json.loads(line)
430
+ if isinstance(turn, dict) and turn.get("kind") in ("Build", "Fix", "Lite"):
431
+ role = turn["kind"].lower()
432
+ except ValueError:
433
+ continue
434
+ try:
435
+ models = ({} if family not in ("codex", "claude") else
436
+ repo.models(cfg, role, family) if kind == "story" else
437
+ repo.worker_models(cfg, role, family))
438
+ if kind == "task":
439
+ key, tid = item.split("/")
440
+ spec = task.rows(task.sections(_read(top, where, f"plans/{key}.md"))).get(tid) or {}
441
+ if family in ("codex", "claude") and repo.user_facing(cfg, spec):
442
+ models = repo.design_models(cfg, family)
443
+ elif (family in ("codex", "claude") and kind == "fix"
444
+ and state.get("allow_large") == "Prototype before sign-off"
445
+ and repo.is_prototype(tree or top, cfg)):
446
+ models = repo.design_models(cfg, family)
447
+ model = models.get("model")
448
+ except repo.Refused:
449
+ model = None
450
+ worker = {"kind": "read" if kind == "story" else "build", "model": model,
451
+ "started_at": None}
452
+ activity = by_item.get(item, [])
453
+ active = [] if finished else active_runs(top, item, activity, state.get("round") if kind != "story" else None)
454
+ agents = [e for e in active if e.get("kind") in ("work", "worker", "read", "review")
455
+ and (kind == "story" or "round" not in state or e.get("round") == state["round"])]
456
+ if agents:
457
+ agent = agents[-1]
458
+ worker = {"kind": {"work": "build", "worker": "build"}.get(agent["kind"], agent["kind"]),
459
+ "tool": agent.get("family"), "model": agent.get("model"),
460
+ "effort": agent.get("effort"), "round": agent.get("round"),
461
+ "started_at": agent.get("at"),
462
+ "step": next((e.get("step") for e in reversed(activity)
463
+ if e.get("run_id") == agent["id"] and e.get("step")), None)}
464
+ for key in ("model", "effort"):
465
+ worker[key] = next((e[key] for e in reversed(activity)
466
+ if e.get("run_id") == agent["id"] and key in e), worker[key])
467
+ now = _when(repo.now())
468
+ elapsed = lambda at: max(0, (now - _when(at)).total_seconds()) if now and _when(at) else None
469
+ if worker:
470
+ worker["elapsed"] = elapsed(worker.get("started_at"))
471
+ dates = ([] if active or worker or finished else
472
+ [e.get("at") for e in activity] + [s.get("at") for s in _steps(state)]
473
+ + timing_dates.get(item, [])
474
+ + [branch_dates.get(branch), branch_dates.get("origin/" + branch)])
475
+ if kind == "story" and not (active or worker or finished):
476
+ dates.extend(story_event_dates.get(item, []))
477
+ prefix = f".factory/stories/{item}/tasks/"
478
+ dates.extend(s.get("at") for rel, (part, _) in best.items() if rel.startswith(prefix)
479
+ for s in _steps(part))
480
+ dates.extend(at for rel, at in history["dates"].items() if rel.startswith(prefix))
481
+ part_branches = {f"task/{item}-{tid.strip('` ')}" for tid in task.rows(task.sections(plan_text))}
482
+ part_branches.update(part.get("branch") or f"task/{item}-{STATE.fullmatch(rel)['task']}"
483
+ for rel, (part, _) in best.items() if rel.startswith(prefix))
484
+ dates.extend(merged_details.get(branch, {}).get("mergedAt") for branch in part_branches)
485
+ dates.extend(at for part, times in timing_dates.items() if str(part).startswith(item + "/")
486
+ for at in times)
487
+ dates.extend(branch_dates.get(ref) for branch in part_branches
488
+ for ref in (branch, "origin/" + branch))
489
+ idle_since = (max((at for at in dates if _when(at)), key=_when, default=None)
490
+ or history["dates"].get(repo.state_path(item))) if not active and not worker and not finished else None
491
+ test_runs = [e for e in active if e.get("kind") == "test"]
492
+ tests = None
493
+ if test_runs:
494
+ current = test_runs[-1]
495
+ tests = {"started_at": current.get("at"), "elapsed": elapsed(current.get("at"))}
496
+ tests.update(next(({k: e[k] for k in ("done", "total") if e.get(k) is not None}
497
+ for e in reversed(activity) if e.get("run_id") == current["id"]
498
+ and e.get("event") == "progress"), {}))
499
+ item_timings = timings_by_item.get(item, [])
500
+ round_number = (worker.get("round") if worker and worker.get("round") is not None else
501
+ state.get("round", (activity or item_timings or [{}])[-1].get("round")))
502
+ stages = []
503
+ for name, step, kinds in (("Build", "worker round", ("work", "worker")),
504
+ ("Tests", "test run", ("test",)), ("Review", "review", ("review",)),
505
+ ("CI", "CI wait", ("ci",)), ("Merge", "merge", ())):
506
+ records = [r for r in item_timings if round_number is not None
507
+ and r.get("round") == round_number and r.get("step") == step]
508
+ live = [e for e in active if e.get("round") == round_number and e.get("kind") in kinds]
509
+ outcome = records[-1].get("outcome") if records else None
510
+ status = {"completed": "pass", "clean": "pass", "passed": "pass",
511
+ "failed": "fail", "blocked": "fail"}.get(outcome, outcome)
512
+ end = (_when(records[-1].get("start")) if records else None)
513
+ if end is not None and records[-1].get("seconds") is not None:
514
+ end += timedelta(seconds=records[-1]["seconds"])
515
+ else:
516
+ end = None
517
+ stages.append({"name": name, "status": status,
518
+ "started_at": records[0].get("start") if records else None,
519
+ "ended_at": end.isoformat() if end else None,
520
+ "seconds": sum(r.get("seconds") or 0 for r in records)
521
+ if any(r.get("seconds") is not None for r in records) else None})
522
+ if live:
523
+ stages[-1].update(status="running", started_at=live[0].get("at"), ended_at=None)
524
+ stages[-1]["elapsed"] = elapsed(live[0].get("at"))
525
+ # The initial close has no worker turn yet (stored as zero); people count from one.
526
+ if round_number is not None:
527
+ round_number = max(1, round_number)
528
+ if worker and worker.get("round") is not None:
529
+ worker["round"] = max(1, worker["round"])
530
+ stage, receipt = (nextstep._item_readiness(item, state, top, checks, runs=active, pr=pr)
531
+ if kind != "story" and not finished else (state.get("status"), {}))
532
+ if kind == "story" and not finished:
533
+ stage = readiness.get(item, {}).get("stage", "planning")
534
+ if worker and not finished:
535
+ stage = ("planning" if kind == "story" else
536
+ "reviewing" if worker["kind"] == "review" else "working")
537
+ if kind != "story":
538
+ lines = nextstep._item(item, title, {**state, "status": stage}, top, tree, by_branch, {})
539
+ else:
540
+ lines = [f"A reader is reading {title}.", "Next: wait for the reader to finish"]
541
+ stage = stage or "unknown"
542
+ pending = (codex.record(top, item).get("question_id")
543
+ if any(e.get("event") == "worker question" for e in activity) else None)
544
+ latest_review = next((e for e in reversed(activity) if e.get("event") == "review result"), {})
545
+ for event in activity:
546
+ event_kind = event.get("event")
547
+ if event_kind == "run end":
548
+ if event.get("kind") == "ci":
549
+ continue
550
+ occurrence_kind, message = "run_finished", f"{event.get('kind', 'Run').capitalize()} finished"
551
+ elif event_kind == "worker question" and event.get("id") == pending:
552
+ occurrence_kind, message = "worker_question", event.get("question")
553
+ elif (event_kind == "review result" and event == latest_review
554
+ and (event.get("outcome") == "failed" or findings)):
555
+ occurrence_kind, message = "review_findings", "Review found problems" if findings else "Review failed"
556
+ else:
557
+ continue
558
+ events.append({"id": event["id"], "kind": occurrence_kind, "title": message})
559
+ if kind != "story" and stage == "ready" and (identity := review.get("id")):
560
+ events.append({"id": identity + ":" + receipt["commit"], "kind": "ready_to_merge",
561
+ "title": "Ready to merge"})
562
+ doc = (tree / "plans" / f"{item}.md" if kind == "story" and stage != "done" and tree
563
+ and approval.waiting_digest(item, tree) else None)
564
+ read_key = item.split("/")[0] if kind != "fix" else None
565
+ plan_read, assignments = story_read(read_key) if read_key else ("none", {})
566
+ ci = {"status": {"pass": "green", "fail": "red", "running": "running"}.get(checks, "none")}
567
+ if checks == "running":
568
+ starts = [c.get("startedAt") for c in _rollup(pr or {}) if _when(c.get("startedAt")) and board_facts.busy(c)]
569
+ ci["elapsed"] = elapsed(min(starts, key=_when)) if starts else None
570
+ if checks == "fail" and any(board_facts.busy(c) for c in _rollup(pr or {})):
571
+ ci["running"] = True # a failed job beside a running one: the checks are not settled
572
+ elif checks == "unknown" and any(e.get("kind") == "ci" for e in active):
573
+ ci = {"status": "running", "elapsed": elapsed(next(e["at"] for e in active if e.get("kind") == "ci"))}
574
+ status = ({"done": "Finished", "merged": "Finished", "planning": "Planning",
575
+ "waiting for approval": "Waiting for approval", "approved": "Approved",
576
+ "checks failed": "Checks failed"}.get(stage) or STATUS.get(stage, "Not started yet"))
577
+ finished_at = (merged_details.get(branch, {}).get("mergedAt") or state.get("finished")
578
+ or (history["dates"].get(repo.state_path(item)) if finished and kind != "story" else None))
579
+ if finished and _when(finished_at):
580
+ status += " on " + _day(_when(finished_at))
581
+ if worker:
582
+ status = {"build": "Worker", "read": "Plan read", "review": "Review"}.get(worker["kind"], "Worker") + " running"
583
+ if worker.get("elapsed") is not None:
584
+ status += " for " + time_records.plain(worker["elapsed"])
585
+ elif tests:
586
+ status = "Tests running"
587
+ if tests.get("elapsed") is not None:
588
+ status += " for " + time_records.plain(tests["elapsed"])
589
+ idle_seconds = elapsed(idle_since)
590
+ developer = board_facts.person(
591
+ (task.developer(assignments.get(item.split("/")[-1], {})) if kind == "task" else None)
592
+ or owners.get(read_key), names=names)
593
+ people_pr = people_branches.get(branch) or pr or {}
594
+ recorded_people = time_records.view_body(people_pr.get("body") or "")
595
+ author = people_pr.get("author") or {}
596
+ starter_name = None
597
+ if author.get("login") and not author.get("name"):
598
+ starter_name = (board_facts.person(recorded_people, field="started_by")["name"]
599
+ or _starters(top).get(repo.state_path(item)))
600
+ starter = board_facts.person(author, starter_name, names=names)
601
+ if not starter["name"]:
602
+ starter = board_facts.person(recorded_people, field="started_by", names=names)
603
+ if not starter["name"]:
604
+ starter = board_facts.person(name=_starters(top).get(repo.state_path(item)))
605
+ approver = board_facts.person(recorded_people, field="approved_by", names=names)
606
+ if not approver["name"] and read_key:
607
+ approver = board_facts.person(_approver(top, read_key), names=names)
608
+ return {"id": item, "kind": kind, "title": title, "stage": stage, "status": status,
609
+ "started_by": starter["name"], "started_by_login": starter["login"],
610
+ "approved_by": approver["name"], "approved_by_login": approver["login"],
611
+ "developer": developer["name"], "developer_login": developer["login"],
612
+ "owner": (task.developer(assignments.get(item.split("/")[-1], {})) if kind == "task" else None)
613
+ or owners.get(read_key),
614
+ "outcome": " ".join(str(state.get("outcome") or "").split()) or None if kind == "story" else None,
615
+ "took": [("Checks" if s["name"] == "CI" else s["name"]) + ": "
616
+ + time_records.plain(_stage_seconds(s)) for s in stages
617
+ if _stage_seconds(s) is not None],
618
+ "activity": {"status": "running", "action": active[-1].get("kind")} if active else
619
+ {"status": "running", "action": worker["kind"]} if worker else {"status": "idle"},
620
+ "idle_since": idle_since, "idle_seconds": idle_seconds,
621
+ "waits_on": lines[0] if not finished and not active and not worker and lines else None,
622
+ "needs_person": not finished and bool(person_waits.setdefault(item, nextstep.person_waits(
623
+ top, item, state, stage, pr, readiness.get(item, {}).get("blocker")))),
624
+ "stalled": bool(idle_seconds is not None and idle_seconds > 86400),
625
+ "gates": {"plan_read": {"status": plan_read},
626
+ "review": {"status": "running"} if any(e.get("kind") == "review" for e in active) else
627
+ {"status": "blocked", "count": len(findings)} if nextstep.review.blocking(review) else
628
+ {"status": "clean" if review else "none"}, "ci": ci},
629
+ "tests": tests,
630
+ "approval": {"doc": doc.resolve().as_posix()} if doc else None,
631
+ "worker": worker, "pr": {"number": (pr or {}).get("number"), "url": (pr or {}).get("url"),
632
+ "checks": checks, "failures": failures, "checked_at": (pr or {}).get("checks_fetched_at")},
633
+ "findings": {"count": len(findings), "titles": [f["title"] for f in findings], "items": findings,
634
+ "dismissed": len(dismissed & set(range(1, len(review.get("findings", [])) + 1)))}, "round": round_number,
635
+ "merged_by": board_facts.person(people_pr["mergedBy"], names=names) if people_pr.get("mergedBy") else None,
636
+ "merged_at": finished_at if finished else None,
637
+ **({k: v for k, v in time_records.combined(
638
+ top, item, state, (pr or {}).get("body") or "", events=activity, timings=item_timings,
639
+ ended_at=finished_at if finished else None).items()
640
+ if k not in ("events", "timings", "state", "ended_at", "seen", "known", "summary")}
641
+ if kind != "story" or time_records.view_body((pr or {}).get("body") or "") else {}),
642
+ "stages": stages, "occurrences": events, "next": board_facts.machine_next(lines),
643
+ "children": []}
644
+
645
+ items, children = {}, {}
646
+ for rel, (state, where) in best.items():
647
+ if rel in history["expired"]:
648
+ continue
649
+ match = STATE.fullmatch(rel)
650
+ if match["fix"]:
651
+ if state.get("kind") != "story-done":
652
+ name = match["fix"]
653
+ items[name] = row(name, "fix", state.get("why") or "A small fix", state, where)
654
+ elif match["task"]:
655
+ key, tid = match["key"], match["task"]
656
+ plan_where = trees.get(f"story/{key}") or best.get(repo.state_path(key), ({}, where))[1]
657
+ text = (_read(top, plan_where, f"plans/{key}.md", history)
658
+ if key in completed or story.plan_ref(top, key, history) == landed
659
+ else story._plan(top, key, history=history))
660
+ specs = task.rows(task.sections(text))
661
+ specs = {cell.strip("` "): spec for cell, spec in specs.items()}
662
+ title = (specs.get(tid) or {}).get("Name") or "A part with no name yet"
663
+ children.setdefault(key, []).append(row(f"{key}/{tid}", "task", title, state, where))
664
+ else:
665
+ key = match["key"]
666
+ completion = history["stories"].get(key, {})
667
+ if state.get("status") != "done" and completion.get("status") == "done":
668
+ state = completion
669
+ text = _read(top, trees.get(f"story/{key}", where), f"plans/{key}.md", history)
670
+ title = state.get("title") or next((s.removeprefix("# ") for s in text.splitlines()
671
+ if s.startswith("# ")), "A story with no title yet")
672
+ items[key] = row(key, "story", title, state, where)
673
+ for key, parts in children.items():
674
+ if key not in items:
675
+ items[key] = row(key, "story", next((s[2:] for s in _read(top, trees.get(f"story/{key}", landed), f"plans/{key}.md", history).splitlines() if s.startswith("# ")), "A story with missing state"), {}, landed)
676
+ items[key]["children"] = parts
677
+ running = next((part for part in parts if part["activity"]["status"] == "running"
678
+ or part["gates"]["ci"]["status"] == "running"), None)
679
+ if running and items[key]["stage"] != "done":
680
+ items[key].update(activity={"status": "running", "action": running["activity"].get("action", "ci")},
681
+ idle_since=None, idle_seconds=None, waits_on=None, stalled=False)
682
+ for key, state in roadmap.items():
683
+ if key not in items and repo.state_path(key) not in history["expired"]:
684
+ items[key] = row(key, "story", state.get("title") or "A story with no title yet",
685
+ completed.get(key, {}), landed)
686
+ for key, item in items.items():
687
+ if item["kind"] != "story" or item["stage"] == "done":
688
+ continue
689
+ for tid, spec in task.rows(task.sections(story._plan(top, key, history=history))).items():
690
+ if ((task.developer(spec) or owners.get(key)) and repo.state_path(f"{key}/{tid}") not in history["expired"]
691
+ and not any(child["id"] == f"{key}/{tid}" for child in item["children"])):
692
+ child = row(f"{key}/{tid}", "task", spec.get("Name") or tid, {}, landed)
693
+ child.update(stage="unstarted", next=board_facts.machine_next(["Next: forge next"]))
694
+ item["children"].append(child)
695
+ older_parts: dict[str, list[Item]] = {}
696
+ older = [(rel, state, match["key"], match["task"], state.get("branch") or f"task/{match['key']}-{match['task']}")
697
+ for rel, (state, _) in best.items() if rel in history["expired"]
698
+ and (match := STATE.fullmatch(rel))["task"] and match["key"] in items]
699
+ # An unfinished story's parts merged before the weekly searches still bring their records.
700
+ if needed := {branch for _, _, key, _, branch in older if branch not in by_branch and key not in completed}:
701
+ by_branch.update({branch: pr for branch, pr in board_facts.merged_before_weeks(top, needed).items()
702
+ if branch not in by_branch})
703
+ for rel, state, key, tid, branch in older:
704
+ if rel in merged or branch in merged_prs or key in completed:
705
+ state = {**state, "status": "merged"}
706
+ older_parts.setdefault(key, []).append(time_records.combined(
707
+ top, f"{key}/{tid}", state, by_branch.get(branch, {}).get("body") or "",
708
+ events=by_item.get(f"{key}/{tid}", []), timings=timings_by_item.get(f"{key}/{tid}", []),
709
+ ended_at=by_branch.get(branch, {}).get("mergedAt")))
710
+ notes_by_story = {key: _read(top, landed if key in completed else story.plan_ref(top, key, history),
711
+ f"plans/{key}.read.md", history)
712
+ for key, current in items.items() if current["kind"] == "story"}
713
+ past_notes = history["past notes"] # read with every plan read, in the same one git process
714
+ for key, notes in notes_by_story.items():
715
+ current = items[key]
716
+ current["read_rounds"] = _read_rounds(notes)
717
+ read_rounds, seen = [], set()
718
+ while notes:
719
+ record, _ = story._record(notes)
720
+ try:
721
+ seconds = float(record["seconds"])
722
+ except (KeyError, ValueError):
723
+ seconds = None
724
+ read_rounds.append({"read_at": record.get("read_at"), "seconds": seconds})
725
+ previous = record.get("notes_seen")
726
+ if not previous or previous in seen:
727
+ break
728
+ seen.add(previous)
729
+ notes = past_notes.get(previous, "")
730
+ started = _step(best.get(repo.state_path(key), ({}, landed))[0], "start")
731
+ # Union the story's own history with its parts so overlapping time is counted once.
732
+ own = [current] if current.get("intervals") else []
733
+ current.update(time_records.story([*own, *current["children"], *older_parts.get(key, [])], read_rounds,
734
+ unfinished=current["stage"] != "done",
735
+ started_at=started.isoformat() if started else None,
736
+ finished_at=completed.get(key, {}).get("finished")))
737
+ # Maps keep the whole plan, including dependencies too old for the active rows.
738
+ maps = []
739
+ active_parts = {p["id"]: p for parts in children.values() for p in parts if p["stage"] != "unstarted"}
740
+ for rel, (state, where) in best.items():
741
+ match = STATE.fullmatch(rel)
742
+ if not match["key"] or match["task"]:
743
+ continue
744
+ key = match["key"]
745
+ text = (_read(top, trees.get(f"story/{key}", where), f"plans/{key}.md", history)
746
+ if key in completed or story.plan_ref(top, key, history) == landed
747
+ else story._plan(top, key, history=history))
748
+ specs = task.rows(task.sections(text))
749
+ parts = []
750
+ for tid, spec in specs.items():
751
+ tid = tid.strip("` ")
752
+ item = f"{key}/{tid}"
753
+ waits = task.waits_for(item, task.cell_list(spec.get("After", "")))
754
+ current = active_parts.get(item, {})
755
+ task_state = nextstep._task(top, key, tid, trees, merged_prs, history)
756
+ waits = list(dict.fromkeys(waits + readiness.get(key, {}).get("waits", {}).get(tid, [])))
757
+ status = ("Merged" if key in completed or task_state.get("status") == "merged" else
758
+ "Running" if current.get("activity", {}).get("status") == "running"
759
+ or current.get("worker") or current.get("tests")
760
+ or current.get("gates", {}).get("ci", {}).get("status") == "running" else
761
+ "Waiting" if current else readiness.get(key, {}).get("parts", {}).get(tid, "Not started"))
762
+ parts.append({"id": item, "title": spec.get("Name") or "A part with no name yet",
763
+ "owner": task.developer(spec) or task.owner(text),
764
+ "status": readiness.get(key, {}).get("stacked", {}).get(tid, status), "waits_for": waits})
765
+ phase = ("done" if key in completed else
766
+ readiness.get(key, {}).get("stage", "planning"))
767
+ if items.get(key, {}).get("worker"):
768
+ phase = "planning"
769
+ if key in items and not items[key].get("worker") and phase in ("building", "ready to merge"):
770
+ finished_parts = sum(p["status"] == "Merged" for p in parts)
771
+ ready_parts = sum(active_parts.get(p["id"], {}).get("stage") == "ready" for p in parts)
772
+ items[key]["status"] = ("Ready to merge" if phase == "ready to merge" else
773
+ "Approved; no part has started yet" if not children.get(key) and not finished_parts else
774
+ f"In progress: {finished_parts} of {len(parts)} parts finished"
775
+ + (f", {ready_parts} ready to merge" if ready_parts else ""))
776
+ items[key]["stage"] = phase
777
+ maps.append({"id": key, "title": items.get(key, {}).get("title") or state.get("title")
778
+ or "A story with no title yet", "owner": task.owner(text),
779
+ "parts": parts, "stage": phase, "planned": bool(parts)})
780
+ mapped = {m["id"] for m in maps}
781
+ maps.extend({"id": s["key"], "title": s.get("title") or "A story with no title yet",
782
+ "owner": None,
783
+ "parts": [], "stage": "done" if s["key"] in completed else "needs a spec", "planned": False}
784
+ for s in roadmap.values() if s["key"] not in mapped)
785
+ order = list(roadmap) # roadmap order; stories off the roadmap keep theirs, after it
786
+ maps.sort(key=lambda entry: order.index(entry["id"]) if entry["id"] in roadmap else len(order))
787
+ part_titles = {part["id"]: part["title"] for entry in maps for part in entry["parts"]}
788
+ for parent in items.values():
789
+ for item in [parent, *parent["children"]]:
790
+ if item["waits_on"]:
791
+ item["waits_on"] = re.sub(r"(?<![\w/-])[A-Z][A-Z0-9-]*/[A-Z0-9][A-Z0-9-]*(?![\w/-])",
792
+ lambda match: part_titles.get(match[0], "A part with no name yet"), item["waits_on"])
793
+ for entry in maps:
794
+ if entry["stage"] == "needs a spec" and not items[entry["id"]].get("worker"):
795
+ items[entry["id"]].update(stage="needs a spec", status="Not started yet")
796
+ team = board_facts.team(top, history, items, maps, best, completed, github, readiness, person_waits, names)
797
+ fixes = [{"id": row["id"], "title": row["title"], "waits_for": [], "running": row["activity"]["status"] == "running"
798
+ or bool(row.get("worker")) or row["gates"]["ci"]["status"] == "running",
799
+ "started_on": next((on for on in [best.get(repo.state_path(row["id"]), ({}, None))[0].get("stacked_on")]
800
+ if "/" in str(on)), None)} # stacked on a story part, not on a fix
801
+ for row in items.values() if row["kind"] == "fix" and row["stage"] not in ("merged", "done")]
802
+ if fixes:
803
+ maps.insert(0, {"id": "fixes", "kind": "fixes", "title": "Fixes", "parts": fixes, "planned": True})
804
+ board_graph.place(maps)
805
+ event_lines = {"run start": "started", "run end": "finished", "review result": "Review "}
806
+ recent = [{"time": e.get("at"), "item": e.get("item"), "line":
807
+ " ".join((e.get("question") or "Worker asked a question").split()) if e.get("event") == "worker question" else
808
+ "Review " + review_skip.label(e) if e.get("event") == "review result" else
809
+ {"work": "Worker", "worker": "Worker", "ci": "Checks", "read": "Plan read",
810
+ "test": "Tests", "review": "Review"}.get(e.get("kind"), "Run") + " " + event_lines[e["event"]]}
811
+ for e in recorded if e.get("event") in (*event_lines, "worker question")][-20:]
812
+ time_records.save_body_validation(top)
813
+ return {"version": __version__, "repo_root": repo_root(top),
814
+ "daily_start_to_merge": time_records.daily_median(list(items.values()), viewer=viewer),
815
+ **releases.collect(top, history, maps, items, tag_refs),
816
+ "known_issues": known_issues.collect(top, {
817
+ "/".join(filter(None, (match["key"] or match["fix"], match["task"]))): (state, where)
818
+ for rel, state, where in (
819
+ [(rel, state, where) for rel, (state, where) in best.items() if rel not in merged]
820
+ + [(rel, state, where) for rel, state, where in history["copies"] if where == landed])
821
+ if (match := STATE.fullmatch(rel))}, landed),
822
+ "viewer": viewer, "signoff": nextstep.signoff(top, configuration(top)),
823
+ "items": list(items.values()),
824
+ "dependency_maps": maps, "team": team, "events": recent,
825
+ "lanes": machine.view(), "machine": machine.load()}
826
+
827
+
828
+ def numbers_line(top: Path, checks: list[str]) -> str:
829
+ """The three success numbers in one line, for `forge next`."""
830
+ stories, prs = _gather(top, checks)
831
+ return "How the factory is doing: " + "; ".join(_numbers(stories, prs)) + "."
832
+
833
+
834
+ # --- reading the state and GitHub ------------------------------------------------------------
835
+
836
+
837
+ def _gather(top: Path, checks: list[str] | None = None) -> tuple[list[Item], list[Item] | None]:
838
+ """Each story with its parts' start, green and touches, for the success numbers, and gh's pull
839
+ requests (None without a working gh)."""
840
+ landed = story.landed_ref(top)
841
+ best: dict[str, Item] = {}
842
+ for rel, state, _ in _copies(top, landed):
843
+ if rel not in best or len(_steps(state)) > len(_steps(best[rel])):
844
+ best[rel] = state
845
+ prs = _prs(top)
846
+ by_branch: dict[str, Item] = {}
847
+ for pr in prs or []: # newest first; a merged one wins
848
+ if pr.get("headRefName") not in by_branch or pr.get("state") == "MERGED":
849
+ by_branch[str(pr.get("headRefName"))] = pr
850
+ if checks is None:
851
+ checks = repo.config(top)["checks"] if (top / "forge.toml").is_file() else []
852
+ found: dict[str, Item] = {}
853
+ parts: dict[str, list[Item]] = {}
854
+ for rel, state in best.items():
855
+ match = STATE.fullmatch(rel)
856
+ if match["task"]:
857
+ pr = by_branch.get(state.get("branch") or f"task/{match['key']}-{match['task']}")
858
+ parts.setdefault(match["key"], []).append({"start": _step(state, "start"), "touches": state.get("touches", 0),
859
+ "green": _green_at(pr, checks)})
860
+ elif match["key"]:
861
+ found[match["key"]] = state
862
+ roadmap = {item["key"]: item for item in repo.roadmap(top) if item.get("status") != "superseded"}
863
+ stories = []
864
+ for key in [*roadmap, *sorted((set(found) | set(parts)) - set(roadmap))]:
865
+ state = found.get(key, {})
866
+ completed = story.completed(top, key, landed)
867
+ if state.get("status") != "done" and completed.get("status") == "done":
868
+ state = completed
869
+ if roadmap.get(key, {}).get("status") == "done":
870
+ state = {**state, **roadmap[key]}
871
+ mine = parts.get(key, [])
872
+ stories.append({"parts": mine, "approved": bool(_when((state.get("approval") or {}).get("at"))),
873
+ "touches": state.get("touches", 0) + sum(part["touches"] for part in mine)})
874
+ return stories, prs
875
+
876
+
877
+ def _blob_texts(top: Path, specs: list[str], *, follow_notes: bool = False) -> dict[str, str]:
878
+ """Read objects and their older notes through the command's shared Git reader."""
879
+ pending, seen, texts = list(dict.fromkeys(specs)), set(specs), {}
880
+ while pending:
881
+ found = repo.blob_texts(top, pending)
882
+ texts.update(found)
883
+ pending = []
884
+ if follow_notes:
885
+ for text in found.values():
886
+ previous = story._record(text)[0].get("notes_seen")
887
+ if not previous or previous in seen:
888
+ continue
889
+ seen.add(previous)
890
+ pending.append(previous)
891
+ return texts
892
+
893
+
894
+ def _machine_history(top: Path) -> Item:
895
+ """A fresh bulk read: omit old completions before any per-item command work."""
896
+ landed = story.landed_ref(top)
897
+ history: Item = {"landed": landed}
898
+ copies = _copies(top, landed, history)
899
+ log = repo.git("log", "--first-parent", "--diff-filter=A", "--no-renames",
900
+ "--format=%x00%cI%x00%B%x00", "--name-only", landed, "--",
901
+ ".factory/stories", ".factory/fixes", cwd=top).split("\0")[1:]
902
+ dates, messages = {}, {}
903
+ for at, message, paths in zip(log[::3], log[1::3], log[2::3]):
904
+ for rel in paths.splitlines():
905
+ if STATE.fullmatch(rel) and rel not in dates:
906
+ dates[rel], messages[rel] = _when(at).isoformat(), message
907
+ landed_states = {rel: state for rel, state, where in copies if where == landed}
908
+ states = {STATE.fullmatch(rel)["key"]: state for rel, state in landed_states.items()
909
+ if STATE.fullmatch(rel)["key"] and not STATE.fullmatch(rel)["task"]}
910
+ history.update(copies=copies, stories=states, dates=dates, messages=messages, states=landed_states)
911
+ for key in states:
912
+ states[key] = story.completed(top, key, landed, history)
913
+ cutoff = (_when(repo.now()) or datetime.now(timezone.utc)) - timedelta(days=7)
914
+ expired = {rel for rel, at in dates.items() if not rel.endswith("/story.json")
915
+ and _when(at) is not None and _when(at) < cutoff}
916
+ best: dict[str, Item] = {}
917
+ step_counts = {}
918
+ for rel, state, _ in copies:
919
+ identity = id(state)
920
+ if identity not in step_counts:
921
+ step_counts[identity] = len(_steps(state))
922
+ if rel not in best or step_counts[identity] > step_counts[id(best[rel])]:
923
+ best[rel] = state
924
+ for rel, state in best.items():
925
+ match = STATE.fullmatch(rel)
926
+ if match["key"] and not match["task"] and states.get(match["key"], {}).get("status") == "done":
927
+ state = states[match["key"]]
928
+ if state.get("status") == "done" and (at := _when(state.get("finished"))) and at < cutoff:
929
+ expired.add(rel)
930
+ for rel in best:
931
+ match = STATE.fullmatch(rel)
932
+ if match["task"] and repo.state_path(match["key"]) in expired:
933
+ expired.add(rel)
934
+ return {**history, "expired": expired, "step_counts": step_counts}
935
+
936
+
937
+ def _copies(top: Path, landed: str, history: Item | None = None) -> list[tuple[str, Item, Path | str]]:
938
+ """Every copy of every state file as (path, state, where): local worktrees first (the freshest,
939
+ so they win a tie), then Forge's branches on the remote, then the default branch."""
940
+ found: list[tuple[str, Item, Path | str]] = []
941
+ trees = story.worktrees(top)
942
+ parsed: dict[str, Item] = {} # most copies match; a shared state is never changed in place
943
+ landed_ref = f"refs/{'remotes' if landed.startswith('origin/') else 'heads'}/{landed}"
944
+ listing = repo.git("for-each-ref", "--format=%(refname) %(tree) %(objectname)",
945
+ *(f"refs/remotes/origin/{prefix}" for prefix in PREFIXES),
946
+ *(("refs/heads/story/", "refs/heads/task/") if history is not None else ()),
947
+ *(f"refs/heads/{branch}" for branch in trees if branch.startswith(PREFIXES)), landed_ref, cwd=top)
948
+ refs = {line.split()[0]: line.split()[1] for line in listing.splitlines()}
949
+ if history is not None:
950
+ history["tips"] = {line.split()[0]: line.split()[2] for line in listing.splitlines()}
951
+ refs[landed] = refs.pop(landed_ref)
952
+ empty = repo.run("git", "hash-object", "-t", "tree", "--stdin", cwd=top)
953
+ empty.check_returncode()
954
+ # Apply each branch's differences to the default snapshot; retained branches share most blobs.
955
+ snapshots: dict[str, dict[str, str]] = {tree: {} for tree in refs.values()}
956
+ base_tree = refs[landed]
957
+ # Git requires LF pairs; text-mode stdin adds CR on Windows and Git silently lists nothing.
958
+ done = subprocess.run([shutil.which("git") or "git", "diff-tree", "--stdin", "-r", "--raw",
959
+ "-z", "--no-abbrev", "--no-renames", "--", ".factory/stories",
960
+ ".factory/fixes", "plans", "forge.toml"], cwd=top,
961
+ input=(f"{empty.stdout.strip()} {base_tree}\n" + "".join(
962
+ f"{base_tree} {tree}\n" for tree in snapshots if tree != base_tree)).encode("utf-8"),
963
+ capture_output=True, check=True, env={**os.environ, "FORGE_WORKER": "1"})
964
+ fields = iter(done.stdout.decode("utf-8", errors="replace").split("\0"))
965
+ for field in fields:
966
+ for line in field.splitlines():
967
+ if line.startswith(":"):
968
+ rel = next(fields)
969
+ if (STATE.fullmatch(rel) or rel == "forge.toml"
970
+ or re.fullmatch(r"plans/[A-Z0-9][A-Z0-9-]*(\.read)?\.md", rel)):
971
+ blob = line.split()[3]
972
+ if blob == "0" * len(blob):
973
+ snapshots[tree].pop(rel, None)
974
+ else:
975
+ snapshots[tree][rel] = blob
976
+ elif line:
977
+ tree = line.split()[1]
978
+ if tree != base_tree:
979
+ snapshots[tree] = dict(snapshots[base_tree])
980
+ texts = _blob_texts(top, list(dict.fromkeys(blob for files in snapshots.values() for blob in files.values())))
981
+ blobs = {blob: repo.without_size_stop(story.json_of(text)) for blob, text in texts.items()}
982
+ state_files = {tree: {rel: blob for rel, blob in sorted(files.items()) if STATE.fullmatch(rel)}
983
+ for tree, files in snapshots.items()}
984
+ # Bulk Git supplies clean state; changed and untracked state still needs fresh disk reads.
985
+ def changed_files(path: Path) -> set[str]:
986
+ return set(repo.git("diff", "HEAD", "--name-only", "--no-renames", "-z",
987
+ "--", ".factory", cwd=path).split("\0"))
988
+
989
+ work = [(branch, path) for branch, path in trees.items() if branch.startswith(PREFIXES)]
990
+ with ThreadPoolExecutor(max_workers=4) as pool:
991
+ changes = dict(zip((path for _, path in work), pool.map(changed_files, (path for _, path in work))))
992
+ for branch, path in work:
993
+ saved = state_files.get(refs.get(f"refs/heads/{branch}"), {})
994
+ changed = changes[path]
995
+ paths = (f"{prefix}/{name}"
996
+ for kind in ("stories", "fixes")
997
+ for folder, _, names in os.walk(path / ".factory" / kind)
998
+ for prefix in (os.path.relpath(folder, path).replace(os.sep, "/"),)
999
+ for name in names if name.endswith(".json"))
1000
+ for rel in sorted(paths):
1001
+ if STATE.fullmatch(rel):
1002
+ if rel in saved and rel not in changed:
1003
+ state = blobs[saved[rel]]
1004
+ else:
1005
+ text = (path / rel).read_text(encoding="utf-8")
1006
+ if text not in parsed:
1007
+ parsed[text] = repo.without_size_stop(story.json_of(text))
1008
+ state = parsed[text]
1009
+ found.append((rel, state, path))
1010
+ seen_states = set()
1011
+ for ref, tree in refs.items():
1012
+ if ref == landed or ref.startswith("refs/remotes/"):
1013
+ for rel, blob in state_files[tree].items():
1014
+ if ref == landed or (rel, blob) not in seen_states:
1015
+ seen_states.add((rel, blob))
1016
+ found.append((rel, blobs[blob], ref))
1017
+ if history is not None:
1018
+ history["worktrees"] = trees
1019
+ history["ref_states"] = {ref: {rel: blobs[blob] for rel, blob in state_files[tree].items()}
1020
+ for ref, tree in refs.items()}
1021
+ history["docs"] = {f"{alias}:{rel}": texts[blob] for ref, tree in refs.items()
1022
+ for alias in (ref, ref.removeprefix("refs/heads/").removeprefix("refs/remotes/"))
1023
+ for rel, blob in snapshots[tree].items() if rel not in state_files[tree]}
1024
+ # The doc each plan read saw, for "changed since the read": one git process for all of them.
1025
+ seen = list(dict.fromkeys(h for text in dict.fromkeys(history["docs"].values())
1026
+ for h in map(story._record(text)[0].get, # pyright: ignore[reportPrivateUsage]
1027
+ ("read_hash", "notes_seen")) if h))
1028
+ history["past notes"] = _blob_texts(top, seen, follow_notes=True)
1029
+ for blob, text in history["past notes"].items():
1030
+ repo.command_fact(("read blob", blob), top, lambda text=text: text)
1031
+ return found
1032
+
1033
+
1034
+ def _prs(top: Path) -> list[Item] | None:
1035
+ """Every pull request gh can see, newest first, or None without a working gh."""
1036
+ github = board_facts.prs(top)
1037
+ if github is None:
1038
+ return None
1039
+ prs = list({(pr.get("number"), pr.get("headRefName")): pr
1040
+ for pr in [*github["open"], *board_facts.merged_prs(github)]}.values())
1041
+ by_branch = {pr["headRefName"]: pr for pr in board_facts.details(top)
1042
+ if isinstance(pr.get("headRefName"), str)}
1043
+ opened = {p["headRefName"]: p for p in _machine_prs(top)}
1044
+ return [{**pr, **by_branch.get(pr.get("headRefName"), {}),
1045
+ **({"statusCheckRollup": _rollup({**opened.get(pr.get("headRefName"), {}), **pr})}
1046
+ if pr.get("state") == "OPEN" else {})} for pr in prs]
1047
+
1048
+
1049
+ def _read(top: Path, where: Path | str, rel: str, history: Item | None = None) -> str:
1050
+ if isinstance(where, Path):
1051
+ return (where / rel).read_text(encoding="utf-8") if (where / rel).is_file() else ""
1052
+ if history is not None:
1053
+ return history["docs"].get(f"{where}:{rel}", "")
1054
+ return story.show(top, where, rel) or ""
1055
+
1056
+
1057
+ # --- a story, a part and the numbers ------------------------------------------------------------
1058
+
1059
+
1060
+ def _numbers(stories: list[Item], prs: list[Item] | None) -> list[str]:
1061
+ """The three success numbers, as plain phrases: task cycle time, human touches per story, and
1062
+ the share of the last 25 finished changes that fixed Forge itself."""
1063
+ cycles = [part["green"] - part["start"] for s in stories for part in s["parts"]
1064
+ if part["start"] and part["green"]]
1065
+ touches = [s["touches"] for s in stories if s["approved"]]
1066
+ merged = sorted((pr for pr in prs or [] if pr.get("mergedAt")), key=lambda pr: str(pr["mergedAt"]),
1067
+ reverse=True)[:25]
1068
+ forge = [pr for pr in merged if str(pr.get("headRefName")).startswith(("fix/", "forge/"))
1069
+ and any(str(f.get("path")).startswith(FORGE_FILES) for f in pr.get("files") or [])]
1070
+ return [
1071
+ (f"a part usually takes {_took(statistics.median(cycles))} from its start to ready" if cycles
1072
+ else "the usual time from a part's start to ready isn't measured yet") + " (target: under 2 hours)",
1073
+ (f"a story usually needs a person {_times(statistics.median(touches))}" if touches
1074
+ else "how often a story needs a person isn't measured yet") + " (target: 3 times or fewer)",
1075
+ (f"{len(forge)} of the last {len(merged)} finished changes fixed Forge itself" if merged
1076
+ else "the share of finished changes that fixed Forge itself isn't measured yet")
1077
+ + " (target: under 10%)",
1078
+ ]
1079
+
1080
+
1081
+ def _green_at(pr: Item | None, names: list[str]) -> datetime | None:
1082
+ """When the last named check passed on the pull request's head; None unless every one passed."""
1083
+ seen = [(str(c.get("name") or c.get("context")), c.get("conclusion") or c.get("state"),
1084
+ _when(c.get("completedAt") or c.get("startedAt")))
1085
+ for c in (pr or {}).get("statusCheckRollup") or [] if isinstance(c, dict)]
1086
+ times: list[datetime] = []
1087
+ for want in names: # a matrix job reports as "tests (ubuntu-latest)"; every one must pass
1088
+ mine = [(ok, at) for name, ok, at in seen if name == want or name.startswith(want + " (")]
1089
+ if not mine or any(ok != "SUCCESS" for ok, _ in mine):
1090
+ return None
1091
+ times += [at for _, at in mine if at]
1092
+ return max(times, default=None)
1093
+
1094
+
1095
+ def _display_names(top: Path) -> dict[str, str]:
1096
+ def read() -> dict[str, str]:
1097
+ names = {}
1098
+ for author in repo.git("log", "--all", "--date-order", "--format=%aN%x00%aE", cwd=top).splitlines():
1099
+ name, _, email = author.partition("\0")
1100
+ names.setdefault(email.casefold(), name)
1101
+ return names
1102
+ return repo.command_fact("display_names", top, read)
1103
+
1104
+
1105
+ def _starters(top: Path) -> dict[str, str]:
1106
+ def read() -> dict[str, str]:
1107
+ names = _display_names(top)
1108
+ log = repo.git(
1109
+ "log", "--all", "--reverse", "--diff-filter=A", "--no-renames", "--grep=^Start ",
1110
+ "--format=%x00%aN%x00%aE%x00", "--name-only", "--", ".factory/stories", ".factory/fixes",
1111
+ cwd=top).split("\0")[1:]
1112
+ found = {}
1113
+ for name, email, paths in zip(log[::3], log[1::3], log[2::3]):
1114
+ for rel in paths.splitlines():
1115
+ if rel.endswith(".json"):
1116
+ found.setdefault(rel, names.get(email.casefold(), name))
1117
+ return found
1118
+ return repo.command_fact("board starter authors", top, read)
1119
+
1120
+
1121
+ def _approver(top: Path, key: str) -> Item | None:
1122
+ """The approval commit's own author, independent of the plan's assignee."""
1123
+ def read():
1124
+ log = repo.git("log", "--all", "--format=%x00%aN%x00%aE%x00", "-F",
1125
+ "--grep=Approve the plan: ", "--name-only", "--", ".factory/stories", cwd=top).split("\0")[1:]
1126
+ found = {}
1127
+ for name, email, paths in zip(log[::3], log[1::3], log[2::3]):
1128
+ for rel in paths.splitlines():
1129
+ found.setdefault(rel, {"name": name, "email": email})
1130
+ return found
1131
+ return repo.command_fact("board approval authors", top, read).get(repo.state_path(key))
1132
+
1133
+
1134
+ def _read_rounds(notes: str) -> list[Item]:
1135
+ """Each round of a plan's cold read, from its notes: the round number, each finding's first
1136
+ line with its disposition (cut, defer or keep, and keep's reason), and the date of the latest
1137
+ round only, which is the one the notes' frontmatter records."""
1138
+ record, body = story._record(notes) # pyright: ignore[reportPrivateUsage]
1139
+ rounds = []
1140
+ for number, text in re.findall(r"^## Round (\d+)[ \t]*\n(.*?)(?=^## Round \d|\Z)", body, re.M | re.S):
1141
+ findings = []
1142
+ for finding in story._findings(text).values(): # pyright: ignore[reportPrivateUsage]
1143
+ said = re.search(r"^\s*Disposition:\s*(cut|defer|keep)\b[\s:\-]*(?:because\s+)?(.*)$", finding, re.M | re.I)
1144
+ findings.append({"title": finding.split("\n", 1)[0].split(". ", 1)[1].strip(),
1145
+ "disposition": said[1].lower() if said else None,
1146
+ "reason": (said[2].strip() or None) if said else None})
1147
+ rounds.append({"round": int(number), "findings": findings,
1148
+ "read_at": record.get("read_at") if number == record.get("round") else None})
1149
+ return rounds
1150
+
1151
+
1152
+ # --- plain English ---------------------------------------------------------------------------
1153
+
1154
+
1155
+ def _steps(state: Item) -> list[Item]:
1156
+ steps = state.get("steps")
1157
+ return [step for step in steps if isinstance(step, dict)] if isinstance(steps, list) else []
1158
+
1159
+
1160
+ def _step(state: Item, name: str) -> datetime | None:
1161
+ """When the first step of this name happened."""
1162
+ return next((_when(step.get("at")) for step in _steps(state) if step.get("step") == name), None)
1163
+
1164
+
1165
+ def _when(text: Any) -> datetime | None:
1166
+ return _parsed_time(str(text))
1167
+
1168
+
1169
+ @functools.lru_cache(maxsize=8192)
1170
+ def _parsed_time(text: str) -> datetime | None:
1171
+ try:
1172
+ return datetime.fromisoformat(text).astimezone(timezone.utc)
1173
+ except ValueError:
1174
+ return None
1175
+
1176
+
1177
+ def _took(delta: timedelta) -> str:
1178
+ from forge.time_records import plain
1179
+ return plain(delta.total_seconds())
1180
+
1181
+
1182
+
1183
+
1184
+ def _times(n: float) -> str:
1185
+ return {1: "once", 2: "twice"}.get(n, f"{n:g} times")
1186
+
1187
+
1188
+ def _stage_seconds(stage: Item) -> float | None:
1189
+ """A stage's recorded seconds, with a running stage's elapsed time added."""
1190
+ seconds = stage.get("seconds")
1191
+ if stage.get("status") == "running" and stage.get("elapsed") is not None:
1192
+ seconds = (seconds or 0) + stage["elapsed"]
1193
+ return seconds
1194
+
1195
+
1196
+ def _day(when: datetime | None) -> str:
1197
+ return f"{when.day} {when:%B %Y}" if when else "a date that wasn't recorded"