even-keel 0.2.4 → 0.3.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (477) hide show
  1. package/.claude-plugin/marketplace.json +16 -4
  2. package/.env.example +2 -2
  3. package/CHANGELOG.md +23 -0
  4. package/README.md +10 -8
  5. package/dist/src/account/aws.js +76 -0
  6. package/dist/src/account/azure.js +36 -0
  7. package/dist/src/account/cloud-errors.js +72 -0
  8. package/dist/src/account/cloud.js +335 -0
  9. package/dist/src/account/credit.js +49 -7
  10. package/dist/src/account/gcloud.js +71 -0
  11. package/dist/src/account/header-levels.js +3 -2
  12. package/dist/src/account/homes.js +49 -5
  13. package/dist/src/account/keycheck.js +57 -4
  14. package/dist/src/account/management.js +41 -0
  15. package/dist/src/account/model.js +41 -18
  16. package/dist/src/account/network.js +8 -3
  17. package/dist/src/account/service-defaults.js +12 -3
  18. package/dist/src/account/settingsGuard.js +92 -0
  19. package/dist/src/account/settingsGuardStrip.js +36 -0
  20. package/dist/src/account/settingsHook.js +15 -0
  21. package/dist/src/account/settingsLayer.js +190 -0
  22. package/dist/src/account/settingsUninstall.js +7 -0
  23. package/dist/src/account/share.js +23 -6
  24. package/dist/src/account/spend.js +155 -0
  25. package/dist/src/account/watcher.js +189 -24
  26. package/dist/src/agent/adapters.js +13 -2
  27. package/dist/src/agent/env.js +22 -7
  28. package/dist/src/agent/model-slots.js +32 -0
  29. package/dist/src/agent/process.js +32 -6
  30. package/dist/src/agent/projectRules.js +3 -2
  31. package/dist/src/agent/providers.js +18 -1
  32. package/dist/src/agent/scripted.js +319 -0
  33. package/dist/src/agent/windows.js +35 -3
  34. package/dist/src/badge/action.js +41 -0
  35. package/dist/src/badge/check.js +60 -0
  36. package/dist/src/badge/collect.js +174 -0
  37. package/dist/src/badge/dates.js +29 -0
  38. package/dist/src/badge/drawing.js +3 -0
  39. package/dist/src/badge/fonts.generated.js +11 -0
  40. package/dist/src/badge/model.js +9 -0
  41. package/dist/src/badge/privacy.js +151 -0
  42. package/dist/src/badge/push.js +117 -0
  43. package/dist/src/badge/render.js +490 -0
  44. package/dist/src/badge/settings.js +43 -0
  45. package/dist/src/badge/stats.js +31 -0
  46. package/dist/src/badge/status.js +57 -0
  47. package/dist/src/badge/text.js +52 -0
  48. package/dist/src/badge/theme.js +54 -0
  49. package/dist/src/badge/translate.js +162 -0
  50. package/dist/src/builtin/adapter.js +40 -0
  51. package/dist/src/builtin/control.js +179 -0
  52. package/dist/src/builtin/editor.js +117 -0
  53. package/dist/src/builtin/export-store.js +67 -0
  54. package/dist/src/builtin/export.js +202 -0
  55. package/dist/src/builtin/exporting.js +25 -0
  56. package/dist/src/builtin/files.js +155 -0
  57. package/dist/src/builtin/links.js +25 -0
  58. package/dist/src/builtin/model.js +59 -0
  59. package/dist/src/builtin/routes.js +108 -0
  60. package/dist/src/builtin/source.js +240 -0
  61. package/dist/src/builtin/store.js +520 -0
  62. package/dist/src/builtin/switch.js +77 -0
  63. package/dist/src/chain/answers.js +27 -0
  64. package/dist/src/chain/archive.js +0 -1
  65. package/dist/src/chain/dispatcher.js +105 -12
  66. package/dist/src/chain/fence.js +30 -0
  67. package/dist/src/chain/handover.js +27 -9
  68. package/dist/src/chain/launches.js +4 -4
  69. package/dist/src/chain/limitNotice.js +1 -1
  70. package/dist/src/chain/lists.js +42 -6
  71. package/dist/src/chain/log.js +3 -1
  72. package/dist/src/chain/maincheck.js +116 -10
  73. package/dist/src/chain/mainci.js +26 -7
  74. package/dist/src/chain/mainfix.js +12 -1
  75. package/dist/src/chain/milestone-sequence.js +40 -0
  76. package/dist/src/chain/milestones.js +3 -2
  77. package/dist/src/chain/order.js +20 -5
  78. package/dist/src/chain/overage.js +7 -2
  79. package/dist/src/chain/places.js +1 -1
  80. package/dist/src/chain/prompts.js +64 -6
  81. package/dist/src/chain/relay.js +35 -14
  82. package/dist/src/chain/reviews.js +8 -4
  83. package/dist/src/chain/rules.js +40 -11
  84. package/dist/src/chain/snapshots.js +2 -0
  85. package/dist/src/chain/start.js +21 -1
  86. package/dist/src/chain/store.js +16 -6
  87. package/dist/src/chain/unchanged.js +68 -5
  88. package/dist/src/ci/adapters.js +3 -1
  89. package/dist/src/ci/forgejo-profile.js +3 -24
  90. package/dist/src/ci/forgejo.js +2 -1
  91. package/dist/src/ci/github.js +10 -2
  92. package/dist/src/ci/gitlab.js +10 -3
  93. package/dist/src/ci/http.js +4 -0
  94. package/dist/src/ci/model.js +79 -6
  95. package/dist/src/ci/report.js +6 -3
  96. package/dist/src/ci/shared.js +9 -0
  97. package/dist/src/ci/verdict.js +18 -7
  98. package/dist/src/ci/watcher.js +95 -23
  99. package/dist/src/ci/wiring.js +15 -0
  100. package/dist/src/claude/adapter.js +34 -8
  101. package/dist/src/claude/cli.js +32 -8
  102. package/dist/src/claude/instructions.js +42 -7
  103. package/dist/src/claude/oauth.js +67 -0
  104. package/dist/src/claude/sdk/host.js +9 -4
  105. package/dist/src/claude/tree.js +45 -14
  106. package/dist/src/cli-check/run.js +3 -3
  107. package/dist/src/cli-check/support.js +4 -4
  108. package/dist/src/cli.js +54 -17
  109. package/dist/src/codex/adapter.js +2 -0
  110. package/dist/src/codex/cli.js +34 -18
  111. package/dist/src/codex/protection.js +17 -11
  112. package/dist/src/codex/rollout.js +9 -2
  113. package/dist/src/codex/turns.js +6 -3
  114. package/dist/src/codex/window.js +14 -0
  115. package/dist/src/config-form.js +63 -7
  116. package/dist/src/config-store.js +29 -7
  117. package/dist/src/config.js +45 -15
  118. package/dist/src/copilot/adapter.js +2 -0
  119. package/dist/src/copilot/cli.js +8 -11
  120. package/dist/src/copilot/home.js +1 -1
  121. package/dist/src/copilot/transcript.js +1 -2
  122. package/dist/src/demo/agent.js +97 -0
  123. package/dist/src/demo/model.js +6 -0
  124. package/dist/src/demo/scenario.js +139 -0
  125. package/dist/src/demo/service.js +161 -0
  126. package/dist/src/diagnostics/stop.js +16 -0
  127. package/dist/src/env-file.js +4 -0
  128. package/dist/src/error-reason.js +10 -0
  129. package/dist/src/event-log/log.js +97 -0
  130. package/dist/src/event-log/model.js +1 -0
  131. package/dist/src/event-log/page-events.js +71 -0
  132. package/dist/src/event-log/watch.js +236 -0
  133. package/dist/src/events.js +57 -1
  134. package/dist/src/forgejo/adapter.js +49 -0
  135. package/dist/src/forgejo/api.js +95 -0
  136. package/dist/src/forgejo/editor.js +196 -0
  137. package/dist/src/forgejo/model.js +90 -0
  138. package/dist/src/forgejo/profile.js +24 -0
  139. package/dist/src/forgejo/source.js +292 -0
  140. package/dist/src/forgejo/trust.js +45 -0
  141. package/dist/src/git/branches.js +88 -0
  142. package/dist/src/git/clone-progress.js +168 -0
  143. package/dist/src/git/remote-run.js +162 -0
  144. package/dist/src/git/run.js +6 -2
  145. package/dist/src/git/setup.js +4 -5
  146. package/dist/src/git/slot.js +9 -7
  147. package/dist/src/git/worktree.js +13 -10
  148. package/dist/src/github/adapter.js +1 -0
  149. package/dist/src/github/editor.js +214 -0
  150. package/dist/src/github/edits.js +31 -0
  151. package/dist/src/github/model.js +10 -4
  152. package/dist/src/github/source.js +66 -15
  153. package/dist/src/gitlab/adapter.js +1 -0
  154. package/dist/src/gitlab/api.js +4 -2
  155. package/dist/src/gitlab/editor.js +248 -0
  156. package/dist/src/gitlab/model.js +43 -4
  157. package/dist/src/gitlab/source.js +113 -22
  158. package/dist/src/guard.js +26 -10
  159. package/dist/src/hotkeys.js +51 -0
  160. package/dist/src/huly/adapter.js +1 -0
  161. package/dist/src/huly/collab.js +15 -0
  162. package/dist/src/huly/editor.js +241 -0
  163. package/dist/src/huly/marks.js +48 -0
  164. package/dist/src/huly/model.js +22 -5
  165. package/dist/src/huly/source.js +111 -48
  166. package/dist/src/intake/github.js +10 -0
  167. package/dist/src/intake/intake.js +41 -1
  168. package/dist/src/intake/model.js +8 -3
  169. package/dist/src/jira/adapter.js +1 -0
  170. package/dist/src/jira/api.js +28 -7
  171. package/dist/src/jira/editor.js +243 -0
  172. package/dist/src/jira/model.js +19 -5
  173. package/dist/src/jira/source.js +41 -9
  174. package/dist/src/jobs/model.js +1 -0
  175. package/dist/src/jobs/runner.js +236 -0
  176. package/dist/src/limits/chatgpt.js +11 -0
  177. package/dist/src/limits/copilot.js +51 -18
  178. package/dist/src/limits/model.js +62 -8
  179. package/dist/src/limits/overage-session.js +2 -2
  180. package/dist/src/limits/overage.js +8 -5
  181. package/dist/src/limits/reset.js +7 -0
  182. package/dist/src/limits/usage.js +60 -5
  183. package/dist/src/linear/adapter.js +1 -0
  184. package/dist/src/linear/editor.js +220 -0
  185. package/dist/src/linear/estimate.js +32 -0
  186. package/dist/src/linear/model.js +24 -3
  187. package/dist/src/linear/source.js +74 -21
  188. package/dist/src/main.js +53 -23
  189. package/dist/src/notice/en-advice.js +28 -0
  190. package/dist/src/notice/en-review.js +29 -0
  191. package/dist/src/notice/en-startup.js +21 -0
  192. package/dist/src/notice/en-values.js +47 -0
  193. package/dist/src/notice/en.js +265 -96
  194. package/dist/src/notice/kinds.js +26 -0
  195. package/dist/src/notice/notice.js +49 -6
  196. package/dist/src/npm-access.js +58 -0
  197. package/dist/src/opencode/adapter.js +4 -2
  198. package/dist/src/opencode/cli.js +34 -25
  199. package/dist/src/opencode/go.js +51 -0
  200. package/dist/src/opencode/home.js +41 -8
  201. package/dist/src/opencode/transcript.js +5 -5
  202. package/dist/src/opencode/usage.js +10 -4
  203. package/dist/src/opencode/window.js +54 -0
  204. package/dist/src/packages/check.js +11 -5
  205. package/dist/src/packages/gateway.js +76 -6
  206. package/dist/src/packages/launch.js +6 -3
  207. package/dist/src/packages/model.js +61 -2
  208. package/dist/src/packages/npm.js +55 -6
  209. package/dist/src/packages/plugins.js +23 -2
  210. package/dist/src/packages/service.js +104 -17
  211. package/dist/src/packages/settings.js +13 -0
  212. package/dist/src/packages/store.js +1 -1
  213. package/dist/src/paths.js +32 -0
  214. package/dist/src/profiles/control.js +1 -0
  215. package/dist/src/profiles/model.js +2 -2
  216. package/dist/src/profiles/oauth-error.js +1 -9
  217. package/dist/src/profiles/oauth-response.js +2 -0
  218. package/dist/src/profiles/service.js +46 -4
  219. package/dist/src/profiles/store.js +10 -5
  220. package/dist/src/projects/add.js +25 -2
  221. package/dist/src/projects/branch-control.js +86 -0
  222. package/dist/src/projects/branch-move.js +39 -0
  223. package/dist/src/projects/branch.js +13 -0
  224. package/dist/src/projects/check.js +80 -36
  225. package/dist/src/projects/creation.js +166 -0
  226. package/dist/src/projects/git-found.js +62 -0
  227. package/dist/src/projects/git-mode.js +116 -0
  228. package/dist/src/projects/own-folder.js +8 -0
  229. package/dist/src/projects/place.js +235 -0
  230. package/dist/src/projects/remote-branches.js +24 -0
  231. package/dist/src/projects/target-read.js +95 -0
  232. package/dist/src/projects/target.js +56 -0
  233. package/dist/src/review/events.js +1 -1
  234. package/dist/src/review/note.js +58 -0
  235. package/dist/src/review/open.js +3 -3
  236. package/dist/src/review/wiring.js +25 -3
  237. package/dist/src/secrets/catalog.js +4 -1
  238. package/dist/src/server-control.js +1 -0
  239. package/dist/src/server-guard.js +4 -0
  240. package/dist/src/server-request.js +88 -10
  241. package/dist/src/server-response.js +143 -0
  242. package/dist/src/server-security.js +16 -0
  243. package/dist/src/server.js +105 -117
  244. package/dist/src/service/account-packages.js +116 -0
  245. package/dist/src/service/accounts.js +109 -81
  246. package/dist/src/service/badge-private.js +62 -0
  247. package/dist/src/service/badge.js +203 -0
  248. package/dist/src/service/chain-prompts.js +87 -0
  249. package/dist/src/service/chain.js +120 -190
  250. package/dist/src/service/cleanup.js +114 -0
  251. package/dist/src/service/cli-check.js +1 -1
  252. package/dist/src/service/closing.js +57 -0
  253. package/dist/src/service/demo.js +46 -0
  254. package/dist/src/service/hosting.js +239 -18
  255. package/dist/src/service/install-check.js +78 -0
  256. package/dist/src/service/lifecycle.js +4 -7
  257. package/dist/src/service/stats.js +3 -3
  258. package/dist/src/service/trackers.js +27 -1
  259. package/dist/src/service/vocabulary.js +17 -0
  260. package/dist/src/service.js +215 -19
  261. package/dist/src/sessions/agents.js +10 -2
  262. package/dist/src/sessions/approvals.js +1 -1
  263. package/dist/src/sessions/ask.js +32 -6
  264. package/dist/src/sessions/boot.js +7 -0
  265. package/dist/src/sessions/chat.js +16 -4
  266. package/dist/src/sessions/commandPrompt.js +13 -6
  267. package/dist/src/sessions/history.js +2 -0
  268. package/dist/src/sessions/keepwarm.js +1 -1
  269. package/dist/src/sessions/launch.js +21 -25
  270. package/dist/src/sessions/lingering.js +30 -7
  271. package/dist/src/sessions/mail.js +7 -6
  272. package/dist/src/sessions/mailRelay.js +2 -2
  273. package/dist/src/sessions/mailbox.js +1 -1
  274. package/dist/src/sessions/monitor.js +47 -3
  275. package/dist/src/sessions/note.js +44 -19
  276. package/dist/src/sessions/permission.js +32 -10
  277. package/dist/src/sessions/protection.js +38 -14
  278. package/dist/src/sessions/rare.js +130 -0
  279. package/dist/src/sessions/runs-store.js +20 -0
  280. package/dist/src/sessions/runs.js +140 -0
  281. package/dist/src/sessions/tail.js +4 -0
  282. package/dist/src/sessions/transcript.js +64 -8
  283. package/dist/src/settings/defaults.js +1 -0
  284. package/dist/src/settings/registry.js +86 -24
  285. package/dist/src/settings/store.js +14 -5
  286. package/dist/src/setup.js +5 -0
  287. package/dist/src/shown-work.js +22 -0
  288. package/dist/src/state/settings.js +1 -0
  289. package/dist/src/stats/base-sql.js +7 -1
  290. package/dist/src/stats/checkpoint.js +8 -5
  291. package/dist/src/stats/model.js +1 -1
  292. package/dist/src/stats/reader.js +50 -25
  293. package/dist/src/stats/rules-reader.js +6 -2
  294. package/dist/src/stats/steps-reader.js +5 -0
  295. package/dist/src/stats/tally-schema.js +1 -1
  296. package/dist/src/storage/backup-model.js +3 -0
  297. package/dist/src/storage/backup-schedule.js +197 -0
  298. package/dist/src/storage/backup-worker.js +9 -0
  299. package/dist/src/storage/backup.js +141 -0
  300. package/dist/src/storage/browser-hotkeys.js +25 -0
  301. package/dist/src/storage/context-windows.js +39 -0
  302. package/dist/src/storage/copy.js +44 -13
  303. package/dist/src/storage/database.js +343 -4
  304. package/dist/src/storage/left-folders.js +16 -0
  305. package/dist/src/storage/migrations.js +98 -1
  306. package/dist/src/storage/owner.js +12 -7
  307. package/dist/src/storage/schema.js +1 -1
  308. package/dist/src/storage/startup.js +25 -0
  309. package/dist/src/storage/state-files.js +1 -1
  310. package/dist/src/storage/vacuum.js +29 -0
  311. package/dist/src/taskmcp/args.js +146 -0
  312. package/dist/src/taskmcp/calls.js +741 -0
  313. package/dist/src/taskmcp/downloads.js +87 -0
  314. package/dist/src/taskmcp/files.js +58 -0
  315. package/dist/src/taskmcp/retries.js +57 -0
  316. package/dist/src/taskmcp/server.js +81 -0
  317. package/dist/src/taskmcp/tools.js +128 -0
  318. package/dist/src/taskmcp/vocabulary.js +75 -0
  319. package/dist/src/tools/panel.js +41 -8
  320. package/dist/src/tools/sessionSettings.js +2 -1
  321. package/dist/src/tools/settings.js +16 -3
  322. package/dist/src/tracker/adapters.js +3 -1
  323. package/dist/src/tracker/card.js +16 -12
  324. package/dist/src/tracker/close.js +57 -0
  325. package/dist/src/tracker/closer.js +18 -15
  326. package/dist/src/tracker/closes.js +6 -0
  327. package/dist/src/tracker/control.js +32 -13
  328. package/dist/src/tracker/diagnostics.js +5 -2
  329. package/dist/src/tracker/editor.js +108 -0
  330. package/dist/src/tracker/export-target.js +30 -0
  331. package/dist/src/tracker/export.js +168 -0
  332. package/dist/src/tracker/health.js +5 -0
  333. package/dist/src/tracker/link.js +127 -24
  334. package/dist/src/tracker/markers.js +7 -0
  335. package/dist/src/tracker/model.js +0 -12
  336. package/dist/src/tracker/parents.js +8 -0
  337. package/dist/src/tracker/questions.js +24 -3
  338. package/dist/src/tracker/readers.js +19 -3
  339. package/dist/src/tracker/source.js +5 -0
  340. package/dist/src/tracker/start.js +61 -6
  341. package/dist/src/tracker/templates.js +102 -0
  342. package/dist/src/tracker/trackers.js +20 -10
  343. package/dist/src/updates/runner.js +1 -1
  344. package/dist/src/updates/settle.js +11 -3
  345. package/dist/src/updates/updater.js +4 -4
  346. package/dist/tally/src/builtin-tasks.js +45 -0
  347. package/dist/tally/src/catalogue.js +70 -0
  348. package/dist/tally/src/classify.js +1 -0
  349. package/dist/tally/src/collect.js +33 -10
  350. package/dist/tally/src/copilot.js +1 -0
  351. package/dist/tally/src/db-classify.js +46 -0
  352. package/dist/tally/src/db.js +66 -60
  353. package/dist/tally/src/migrations/10-rework-label.sql +73 -0
  354. package/dist/tally/src/migrations/11-catalogue-prices.sql +53 -0
  355. package/dist/tally/src/migrations/12-key-spends.sql +30 -0
  356. package/dist/tally/src/migrations/13-normal-spans.sql +110 -0
  357. package/dist/tally/src/migrations/14-model-families.sql +25 -0
  358. package/dist/tally/src/migrations/15-task-moves.sql +32 -0
  359. package/dist/tally/src/migrations.js +1 -1
  360. package/dist/tally/src/opencode.js +1 -0
  361. package/dist/tally/src/parse.js +3 -0
  362. package/dist/tally/src/rollout.js +2 -1
  363. package/dist/tally/src/rule-hook-size.js +2 -1
  364. package/dist/tally/src/rule-hook.js +3 -0
  365. package/dist/tally/src/task-moves.js +32 -0
  366. package/dist/web/assets/BadgeDialog-Dx2EERWr.js +1 -0
  367. package/dist/web/assets/BadgeDialog-W0giN4k2.css +1 -0
  368. package/dist/web/assets/DescriptionEditor-BL_6314d.js +216 -0
  369. package/dist/web/assets/ProjectPackages-D-Hqs0sG.js +1 -0
  370. package/dist/web/assets/Select-B5xZpiCG.js +1 -0
  371. package/dist/web/assets/Select-CYemy5Na.css +1 -0
  372. package/dist/web/assets/TaskCard-B9EJ_Qa2.js +2 -0
  373. package/dist/web/assets/TaskCard-BV2lQojC.css +1 -0
  374. package/dist/web/assets/TranscriptWindow-BN6jSpev.css +1 -0
  375. package/dist/web/assets/TranscriptWindow-E8DxggYC.js +4 -0
  376. package/dist/web/assets/accountParts-c2gPSGKK.js +3 -0
  377. package/dist/web/assets/accountParts-tFRVownp.css +1 -0
  378. package/dist/web/assets/blocks-B03KxlgQ.js +12 -0
  379. package/dist/web/assets/blocks-Dx3DACiG.css +1 -0
  380. package/dist/web/assets/cardDrafts-Cb5dNpJ3.js +12 -0
  381. package/dist/web/assets/cardDrafts-izWnctoh.css +1 -0
  382. package/dist/web/assets/cardSide-63fNWHHv.css +1 -0
  383. package/dist/web/assets/cardSide-CIGvmTwG.js +2 -0
  384. package/dist/web/assets/description-C-o9LBbp.css +1 -0
  385. package/dist/web/assets/feedLine-Buzox_AA.js +1 -0
  386. package/dist/web/assets/feedLine-CBjZXWwX.css +1 -0
  387. package/dist/web/assets/hooks-DdmIE6gF.js +1 -0
  388. package/dist/web/assets/index-CkYiatZt.css +1 -0
  389. package/dist/web/assets/index-DELgEMlH.js +25 -0
  390. package/dist/web/assets/lib-B8qNeB0X.css +1 -0
  391. package/dist/web/assets/lib-C1i2rKJZ.js +18 -0
  392. package/dist/web/assets/overview-B7iEgjQD.css +1 -0
  393. package/dist/web/assets/overview-D9PUjFeR.js +7 -0
  394. package/dist/web/assets/packageGroups-B34vA6-0.js +1 -0
  395. package/dist/web/assets/packages-Dld4uH9X.css +1 -0
  396. package/dist/web/assets/react-dom-vGPErQYp.js +1 -0
  397. package/dist/web/assets/rules-BVB-I2tg.js +1 -0
  398. package/dist/web/assets/rules-Bgil4ZBp.css +1 -0
  399. package/dist/web/assets/secret-CmK85pY6.js +1 -0
  400. package/dist/web/assets/secret-DldsC74x.css +1 -0
  401. package/dist/web/assets/useFileDrop-eZtIxL1H.js +1 -0
  402. package/dist/web/assets/useHeightGlide-BmtdsmN0.css +1 -0
  403. package/dist/web/assets/useHeightGlide-DQvvOoIL.js +3 -0
  404. package/dist/web/assets/useRowFocus-CwOoEmzD.js +1 -0
  405. package/dist/web/index.html +30 -9
  406. package/dist/web/theme.js +6 -0
  407. package/even-keel.config.example.json +5 -4
  408. package/package.json +21 -5
  409. package/plugins/agent-bridge/.claude-plugin/plugin.json +16 -0
  410. package/plugins/{checkpoint → agent-bridge}/README.md +20 -6
  411. package/plugins/agent-bridge/hooks/addressban.mjs +64 -0
  412. package/plugins/{checkpoint → agent-bridge}/hooks/checkpoint-mark.mjs +4 -3
  413. package/plugins/{checkpoint → agent-bridge}/hooks/evenkeel.mjs +28 -11
  414. package/plugins/agent-bridge/hooks/git-ban.mjs +31 -0
  415. package/plugins/agent-bridge/hooks/gitban.mjs +83 -0
  416. package/plugins/agent-bridge/hooks/handoff.mjs +20 -0
  417. package/plugins/{checkpoint → agent-bridge}/hooks/hooks.json +10 -0
  418. package/plugins/{checkpoint → agent-bridge}/hooks/mailbox.mjs +6 -3
  419. package/plugins/{checkpoint → agent-bridge}/hooks/nudges.mjs +11 -7
  420. package/plugins/{checkpoint/opencode/checkpoint.mjs → agent-bridge/opencode/agent-bridge.mjs} +15 -9
  421. package/plugins/forgejo/.claude-plugin/plugin.json +7 -0
  422. package/plugins/forgejo/.mcp.json +13 -0
  423. package/plugins/forgejo/README.md +23 -0
  424. package/plugins/forgejo/skills/task/SKILL.md +55 -0
  425. package/plugins/github/.claude-plugin/plugin.json +1 -1
  426. package/plugins/github/README.md +1 -1
  427. package/plugins/github/skills/task/SKILL.md +2 -2
  428. package/plugins/gitlab/.claude-plugin/plugin.json +1 -1
  429. package/plugins/gitlab/skills/task/SKILL.md +2 -2
  430. package/plugins/huly/.claude-plugin/plugin.json +1 -1
  431. package/plugins/huly/skills/task/SKILL.md +4 -4
  432. package/plugins/jira/.claude-plugin/plugin.json +1 -1
  433. package/plugins/jira/skills/task/SKILL.md +3 -3
  434. package/plugins/linear/.claude-plugin/plugin.json +1 -1
  435. package/plugins/linear/README.md +1 -1
  436. package/plugins/linear/skills/task/SKILL.md +3 -3
  437. package/plugins/tally/.claude-plugin/plugin.json +1 -1
  438. package/plugins/tally/skills/session-audit/SKILL.md +5 -5
  439. package/plugins/tasks/.claude-plugin/plugin.json +9 -0
  440. package/plugins/tasks/.mcp.json +8 -0
  441. package/plugins/tasks/README.md +42 -0
  442. package/plugins/tasks/hooks/calibration-context.mjs +45 -0
  443. package/plugins/tasks/hooks/calibration.mjs +92 -0
  444. package/plugins/tasks/hooks/check-service.mjs +15 -0
  445. package/plugins/tasks/hooks/hooks.json +28 -0
  446. package/plugins/tasks/hooks/service-check.mjs +34 -0
  447. package/plugins/tasks/hooks/show-calibration.mjs +19 -0
  448. package/plugins/tasks/opencode/tasks.mjs +28 -0
  449. package/plugins/tasks/skills/split/SKILL.md +29 -0
  450. package/plugins/tasks/skills/task/SKILL.md +61 -0
  451. package/service/EvenKeelTray.cs +4 -20
  452. package/service/install.sh +25 -2
  453. package/service/uninstall.ps1 +16 -0
  454. package/service/uninstall.sh +10 -0
  455. package/tally/tally.config.json +2 -0
  456. package/dist/web/assets/Loader-CRe-GCoI.js +0 -31
  457. package/dist/web/assets/Loader-DJJTBsaF.css +0 -1
  458. package/dist/web/assets/TaskCard-Br2QIllc.css +0 -1
  459. package/dist/web/assets/TaskCard-C2xeaHWD.js +0 -2
  460. package/dist/web/assets/TranscriptWindow-B9zsSmIg.css +0 -1
  461. package/dist/web/assets/TranscriptWindow-COL_WTrF.js +0 -4
  462. package/dist/web/assets/feedLine-D0lnFyBZ.js +0 -1
  463. package/dist/web/assets/index-DQje9Nfo.js +0 -25
  464. package/dist/web/assets/index-mDBlgk2Y.css +0 -1
  465. package/dist/web/assets/media-BlW-XXN0.js +0 -1
  466. package/dist/web/assets/media-DR8nAbPy.css +0 -1
  467. package/dist/web/assets/useModels-1oIk0mDX.css +0 -1
  468. package/dist/web/assets/useModels-DRW63oka.js +0 -15
  469. package/plugins/checkpoint/.claude-plugin/plugin.json +0 -9
  470. package/plugins/checkpoint/hooks/handoff.mjs +0 -9
  471. /package/plugins/{checkpoint → agent-bridge}/hooks/context-checkpoint.mjs +0 -0
  472. /package/plugins/{checkpoint → agent-bridge}/hooks/merge-check.mjs +0 -0
  473. /package/plugins/{checkpoint → agent-bridge}/hooks/merges.mjs +0 -0
  474. /package/plugins/{checkpoint → agent-bridge}/hooks/permission.mjs +0 -0
  475. /package/plugins/{checkpoint → agent-bridge}/hooks/schema-hint.mjs +0 -0
  476. /package/plugins/{checkpoint → agent-bridge}/hooks/standard-gate.mjs +0 -0
  477. /package/plugins/{checkpoint → agent-bridge}/hooks/standards.mjs +0 -0
@@ -1,10 +1,10 @@
1
1
  import pg from 'pg';
2
- import { BASE, familyOf } from './base-sql.js';
2
+ import { BASE, excludingProjects, familyOf } from './base-sql.js';
3
3
  import { mapCalibration } from './calibration.js';
4
4
  import { checkpointThreshold } from './checkpoint.js';
5
5
  import { folderGroups, repoTail } from './model.js';
6
6
  import { readCompare, readRuleDiff, readRules } from './rules-reader.js';
7
- import { readSteps, readTaskSteps } from './steps-reader.js';
7
+ import { readSteps, readTaskActive, readTaskSteps } from './steps-reader.js';
8
8
  import { TALLY_SCHEMA_VERSION, tallyVersion } from './tally-schema.js';
9
9
  const CACHE_MS = 60_000;
10
10
  const TOP_STUCK = 20;
@@ -23,12 +23,13 @@ left join firsts f on f.day = l.day and f.project = l.project
23
23
  group by l.day, l.project
24
24
  order by l.day, l.project`;
25
25
  const ACCOUNTS = `select distinct account from messages order by account`;
26
- // $1 time zone: the spend since local midnight and over the last 30 days, per account folder key.
26
+ // $1 time zone: the spend since local midnight and over the last 30 days, per account folder key; a session's real
27
+ // spend on its key where Even Keel read one (BTN-860), the estimate by price otherwise.
27
28
  const SPEND = `
28
29
  select account,
29
- coalesce(sum(cost) filter (where at >= (now() at time zone $1::text)::date::timestamp at time zone $1::text), 0) as day,
30
- coalesce(sum(cost), 0) as month
31
- from message_costs
30
+ coalesce(sum(paid) filter (where at >= (now() at time zone $1::text)::date::timestamp at time zone $1::text), 0) as day,
31
+ coalesce(sum(paid), 0) as month
32
+ from message_paid
32
33
  where at >= now() - interval '30 days'
33
34
  group by account`;
34
35
  // $1 time zone: the tokens since local midnight and over the last 30 days, per account folder key.
@@ -76,7 +77,9 @@ select r.cur, coalesce(sum(r.cost), 0) as cost, count(*) as messages, count(dist
76
77
  count(distinct r.task) as tasks, count(*) filter (where r.cost is null) as unpriced, sum(sv.share) as limit_share,
77
78
  coalesce(sum(r.cost) filter (where exists (
78
79
  select 1 from spans sp
80
+ left join span_reasons sr on sr.span_id = sp.id
79
81
  where sp.session_id = r.session_id and sp.agent_id = r.agent_id and r.at between sp.from_at and sp.to_at
82
+ and sr.reason is distinct from 'normal'
80
83
  )), 0) as stuck_cost
81
84
  from ranged r
82
85
  left join seven sv on sv.message_id = r.message_id
@@ -107,7 +110,7 @@ const TASKS = `${PERIOD}, cur as (
107
110
  from stuck_spans sp
108
111
  join (select distinct session_id, task from cur) t on t.session_id = sp.session_id
109
112
  cross join bounds
110
- where sp.to_at >= bounds.lo and sp.from_at < bounds.hi
113
+ where sp.to_at >= bounds.lo and sp.from_at < bounds.hi and sp.reason is distinct from 'normal'
111
114
  group by t.task
112
115
  ), compacted as (
113
116
  select t.task,
@@ -118,8 +121,12 @@ const TASKS = `${PERIOD}, cur as (
118
121
  cross join bounds
119
122
  where k.agent_id is null and k.at >= bounds.lo and k.at < bounds.hi
120
123
  group by t.task
124
+ ), paid as (
125
+ -- The real spend on the key where Even Keel read one (BTN-860): only those sessions, so the view prices no other.
126
+ select p.message_id, p.paid from message_paid p where p.session_id in (select session_id from key_spends where not shared)
121
127
  )
122
- select c.task, min(c.project) as project, t.title, t.status, t.url, coalesce(sum(c.cost), 0) as cost, sum(sv.share) as limit_share,
128
+ select c.task, min(c.project) as project, t.title, t.status, t.url, coalesce(sum(coalesce(pd.paid, c.cost)), 0) as cost,
129
+ case when count(pd.message_id) > 0 then coalesce(sum(c.cost), 0) end as price_estimate, sum(sv.share) as limit_share,
123
130
  count(distinct c.session_id) as sessions,
124
131
  count(distinct c.session_id) filter (where c.launch_reason = 'relay') as relays,
125
132
  count(distinct c.session_id) filter (where c.launch_reason = 'checkpoint') as checkpoints,
@@ -127,11 +134,13 @@ select c.task, min(c.project) as project, t.title, t.status, t.url, coalesce(sum
127
134
  coalesce(max(st.spans), 0) as spans,
128
135
  coalesce(max(cp.compacts_auto), 0) as compacts_auto,
129
136
  coalesce(max(cp.compacts_manual), 0) as compacts_manual,
130
- coalesce('Переделка' = any(t.labels), false) as rework,
137
+ -- Rework is the built-in tracker's label (BTN-767).
138
+ coalesce(t.labels && array['Переделка', 'Rework'], false) as rework,
131
139
  t.estimate_h, tt.active_s, tt.wait_s, tt.total_s, t.done, t.component,
132
140
  mode() within group (order by ${familyOf('c.model')}) as model
133
141
  from cur c
134
142
  left join seven sv on sv.message_id = c.message_id
143
+ left join paid pd on pd.message_id = c.message_id
135
144
  left join tasks t on t.task = c.task
136
145
  left join task_times tt on tt.task = c.task
137
146
  left join stuck st on st.task = c.task
@@ -159,9 +168,12 @@ order by p.to_at desc
159
168
  limit ${TOP_STUCK}`;
160
169
  const TASK_SESSIONS = `
161
170
  select c.session_id, coalesce(s.custom_title, s.ai_title) as title, s.launch_reason, mode() within group (order by c.model) as model,
162
- min(c.at) as first_at, max(c.at) as last_at, coalesce(sum(c.cost), 0) as cost, mode() within group (order by c.account) as account
163
- from message_costs c
171
+ min(c.at) as first_at, max(c.at) as last_at, coalesce(sum(c.paid), 0) as cost,
172
+ case when max(k.session_id) is not null then coalesce(sum(c.cost), 0) end as price_estimate,
173
+ mode() within group (order by c.account) as account
174
+ from message_paid c
164
175
  left join sessions s on s.session_id = c.session_id
176
+ left join key_spends k on k.session_id = c.session_id and not k.shared
165
177
  where c.task = $1::text
166
178
  group by c.session_id, s.custom_title, s.ai_title, s.launch_reason
167
179
  order by first_at`;
@@ -191,7 +203,7 @@ with own as (
191
203
  join session_tasks st on st.session_id = s.session_id
192
204
  where split_part(st.task, '-', 1) = any($1::text[])
193
205
  ), reqs as (
194
- select c.session_id, c.message_id, c.cost, c.model,
206
+ select c.session_id, c.message_id, c.cost, c.model, c.price_model,
195
207
  c.input + c.cache_write_5m + c.cache_write_1h + c.cache_read as ctx,
196
208
  row_number() over (partition by c.session_id order by c.at, c.message_id) as n
197
209
  from message_costs c
@@ -199,8 +211,8 @@ with own as (
199
211
  where c.agent_id is null and c.entrypoint is distinct from 'tally-classify'
200
212
  ), marks as (
201
213
  select r.session_id,
202
- min(r.n) filter (where t.brief not like '%.temp/handoff.md') as edit_n,
203
- min(r.n) filter (where t.brief like '%.temp/handoff.md') as note_n
214
+ min(r.n) filter (where t.brief not like '%.temp/handoff%.md') as edit_n,
215
+ min(r.n) filter (where t.brief like '%.temp/handoff%.md') as note_n
204
216
  from tool_calls t
205
217
  join reqs r on r.message_id = t.message_id
206
218
  where t.name in ('Edit', 'Write', 'MultiEdit', 'NotebookEdit')
@@ -211,7 +223,8 @@ with own as (
211
223
  max(r.ctx) filter (where r.n = 15) as ctx15,
212
224
  sum(r.cost) filter (where r.n < m.edit_n) as recovery,
213
225
  sum(r.cost) filter (where r.n >= m.note_n) as note,
214
- (array_agg(r.model order by r.n))[1] as model
226
+ (array_agg(r.model order by r.n))[1] as model,
227
+ (array_agg(r.price_model order by r.n))[1] as price_model
215
228
  from own o
216
229
  join reqs r on r.session_id = o.session_id
217
230
  left join marks m on m.session_id = o.session_id
@@ -223,13 +236,16 @@ with own as (
223
236
  percentile_cont(0.5) within group (order by ctx15) filter (where handed) as base,
224
237
  percentile_cont(0.5) within group (order by recovery) filter (where handed) as recovery,
225
238
  percentile_cont(0.5) within group (order by note) as note,
226
- mode() within group (order by model) filter (where handed) as model
239
+ mode() within group (order by model) filter (where handed) as model,
240
+ mode() within group (order by price_model) filter (where handed) as price_model
227
241
  from per
228
242
  group by key
229
243
  )
244
+ -- The config's longest prefix of the model, else the catalogue row the model was priced by (BTN-859).
230
245
  select t.key, t.handoffs, t.sessions, t.base, t.recovery, t.note, (
231
246
  select p.cache_read from model_prices p
232
- where starts_with(t.model, p.model) order by length(p.model) desc limit 1
247
+ where (p.source = 'config' and starts_with(t.model, p.model)) or (p.source = 'catalogue' and p.model = t.price_model)
248
+ order by p.source = 'config' desc, length(p.model) desc limit 1
233
249
  ) as cache_read
234
250
  from total t`;
235
251
  const number = (value) => Number(value ?? 0);
@@ -306,6 +322,7 @@ export function mapPeriod(query, rows, at) {
306
322
  status: text(row.status),
307
323
  url: text(row.url),
308
324
  cost: number(row.cost),
325
+ priceEstimate: maybe(row.price_estimate),
309
326
  limit: maybe(row.limit_share),
310
327
  sessions: number(row.sessions),
311
328
  relays: number(row.relays),
@@ -338,6 +355,7 @@ export function mapTask(task, sessions, spans, steps = [], compactions = []) {
338
355
  firstAt: iso(row.first_at),
339
356
  lastAt: iso(row.last_at),
340
357
  cost: number(row.cost),
358
+ priceEstimate: maybe(row.price_estimate),
341
359
  account: text(row.account),
342
360
  })),
343
361
  spans: spans.map(stuck),
@@ -358,6 +376,7 @@ export class StatsReader {
358
376
  projects;
359
377
  statsConfig;
360
378
  pinnedOf;
379
+ testProjects;
361
380
  // A string is why the stats are off (`TALLY_DISABLED`, `TALLY_UNCHOSEN` or the missing variables); the local database
362
381
  // comes as a promise that settles once it is open.
363
382
  pool;
@@ -365,10 +384,11 @@ export class StatsReader {
365
384
  folders = null;
366
385
  constructor(settings, projects, statsConfig,
367
386
  /** The project's pinned checkpoint threshold, its own over the shared one; `null` — calibrated. */
368
- pinnedOf = () => statsConfig().checkpointTokens) {
387
+ pinnedOf = () => statsConfig().checkpointTokens, testProjects = () => []) {
369
388
  this.projects = projects;
370
389
  this.statsConfig = statsConfig;
371
390
  this.pinnedOf = pinnedOf;
391
+ this.testProjects = testProjects;
372
392
  this.setReader(settings);
373
393
  }
374
394
  /** The database moved (`TALLY_*` or the mode changed): the old pool ends, the answers read from it go. */
@@ -394,17 +414,17 @@ export class StatsReader {
394
414
  return Object.keys(projects).map((key) => repoTail(projects[key]));
395
415
  }
396
416
  history(filter) {
397
- return this.cached(`history|${filter.scope}|${filter.account}|${filter.tz}`, async (pool) => {
417
+ return this.cached(`history|${JSON.stringify(filter)}`, async (pool) => {
398
418
  const [rows, accounts, limits] = await Promise.all([
399
419
  this.query(pool, HISTORY, filter),
400
420
  pool.query(ACCOUNTS).then((result) => result.rows),
401
421
  pool.query(COVERAGE, [filter.tz, filter.account]).then((result) => result.rows),
402
422
  ]);
403
- return mapHistory(rows, accounts, limits, this.keys, new Date());
423
+ return mapHistory(rows, accounts, limits, this.keys.filter(key => filter.includeTests || !this.testProjects().includes(key)), new Date());
404
424
  });
405
425
  }
406
426
  period(query) {
407
- const key = `period|${query.scope}|${query.account}|${query.tz}|${query.from}|${query.to}|${query.projects?.join(',') ?? '*'}`;
427
+ const key = `period|${JSON.stringify(query)}`;
408
428
  return this.cached(key, async (pool) => {
409
429
  const extra = [query.from, query.to, query.projects];
410
430
  const plain = (sql, params) => pool.query(sql, params).then((result) => result.rows);
@@ -426,6 +446,9 @@ export class StatsReader {
426
446
  return mapTask(task, sessions, spans, steps, compactions);
427
447
  });
428
448
  }
449
+ activeTime(task) {
450
+ return this.cached(`active|${task}`, (pool) => readTaskActive(this.db(pool), task));
451
+ }
429
452
  /** Any project key Tally has seen, not only the tracked ones: the huly plugin runs in projects outside the chain. */
430
453
  calibration(project, task) {
431
454
  return this.cached(`calibration|${project}|${task ?? ''}`, async (pool) => {
@@ -490,12 +513,12 @@ export class StatsReader {
490
513
  });
491
514
  }
492
515
  steps(query) {
493
- const key = `steps|${query.scope}|${query.account}|${query.tz}|${query.from}|${query.to}|${query.projects?.join(',') ?? '*'}`;
516
+ const key = `steps|${JSON.stringify(query)}`;
494
517
  return this.cached(key, (pool) => readSteps(this.db(pool), query));
495
518
  }
496
519
  rules(query) {
497
520
  const settings = this.statsConfig().compare;
498
- return this.cached(rulesKey(query, settings), (pool) => readRules(this.db(pool), query, settings));
521
+ return this.cached(rulesKey(query, settings), (pool) => readRules(this.db(pool), query, settings, query.includeTests ? [] : this.testProjects()));
499
522
  }
500
523
  ruleDiff(ids) {
501
524
  return this.cached(`diff|${ids.join(',')}`, (pool) => readRuleDiff(this.db(pool), ids));
@@ -520,12 +543,13 @@ export class StatsReader {
520
543
  }
521
544
  async query(pool, sql, filter, extra = []) {
522
545
  const { dirs, labels } = await this.groups(pool);
523
- const result = await pool.query(sql, [this.keys, this.dirs, filter.tz, filter.scope, filter.account, dirs, labels, ...extra]);
546
+ const params = [this.keys, this.dirs, filter.tz, filter.scope, filter.account, dirs, labels, ...extra];
547
+ const result = await pool.query(excludingProjects(sql, params.length + 1), [...params, filter.includeTests ? [] : this.testProjects()]);
524
548
  return result.rows;
525
549
  }
526
550
  groups(pool) {
527
551
  const { moves, otherBelow } = this.statsConfig();
528
- const key = JSON.stringify([moves, otherBelow]);
552
+ const key = JSON.stringify([this.projects(), moves, otherBelow]);
529
553
  if (this.folders !== null && this.folders.key === key && Date.now() - this.folders.at < CACHE_MS)
530
554
  return this.folders.groups;
531
555
  const tracked = this.keys.map((each, index) => ({ key: each, dir: this.dirs[index] }));
@@ -539,6 +563,7 @@ export class StatsReader {
539
563
  return groups;
540
564
  }
541
565
  async cached(key, read) {
566
+ key = `${JSON.stringify([this.projects(), this.statsConfig(), this.testProjects()])}|${key}`;
542
567
  const now = Date.now();
543
568
  for (const [each, entry] of this.cache)
544
569
  if (now - entry.at >= CACHE_MS)
@@ -57,7 +57,9 @@ const SIDE_SESSIONS = `${SIDED}
57
57
  select x.side, count(distinct x.session_id) as sessions, coalesce(sum(p.cost), 0) as cost,
58
58
  coalesce(sum(p.cost) filter (where exists (
59
59
  select 1 from spans sp
60
+ left join span_reasons sr on sr.span_id = sp.id
60
61
  where sp.session_id = p.session_id and sp.agent_id = p.agent_id and p.at between sp.from_at and sp.to_at
62
+ and sr.reason is distinct from 'normal'
61
63
  )), 0) as stuck_cost
62
64
  from sided x
63
65
  join picked p on p.session_id = x.session_id
@@ -155,7 +157,7 @@ const importOf = (row) => ({
155
157
  task: row.task === null ? null : String(row.task),
156
158
  source: String(row.source),
157
159
  });
158
- export async function readRules(db, query, settings) {
160
+ export async function readRules(db, query, settings, excluded = []) {
159
161
  const [changeRows, editRows, importRows, starts, places] = await Promise.all([
160
162
  db.plain(CHANGES, []),
161
163
  db.plain(EDITS, []),
@@ -182,7 +184,9 @@ export async function readRules(db, query, settings) {
182
184
  const ids = [...new Set(edits.map((each) => each.sessionId))];
183
185
  const info = ids.length === 0 ? [] : await db.plain(SESSION_INFO, [ids]);
184
186
  const sessions = new Map(info.map((row) => [String(row.session_id), { task: row.task === null ? null : String(row.task), title: row.title === null ? null : String(row.title) }]));
185
- const filtered = filterSets(withImports(ruleSets(changes, edits, sessions), importRows.map(importOf), places), query);
187
+ const filtered = filterSets(withImports(ruleSets(changes, edits, sessions), importRows.map(importOf), places), query)
188
+ .map(set => ({ ...set, files: set.files.filter(file => file.project === null || !excluded.includes(file.project)) }))
189
+ .filter(set => set.files.length > 0);
186
190
  const hashes = netHashes(filtered, changes);
187
191
  const texts = hashes.length === 0 ? [] : await db.plain(TEXTS, [hashes]);
188
192
  const sets = withNetLines(filtered, changes, new Map(texts.map((row) => [String(row.hash), String(row.content)])));
@@ -102,6 +102,11 @@ export async function readSteps(db, query) {
102
102
  unknown: mapUnknown(unknownRows),
103
103
  };
104
104
  }
105
+ /** The agent's active seconds on the task, as the Time column of `/stats`; `null` — Tally has no session of it. */
106
+ export async function readTaskActive(db, task) {
107
+ const [row] = await db.plain(TASK_ACTIVE, [[task]]);
108
+ return row === undefined ? null : Number(row.active_s);
109
+ }
105
110
  export async function readTaskSteps(db, task) {
106
111
  const time = (await readTimes(db, [task])).get(task);
107
112
  return time === undefined ? [] : taskSteps(time);
@@ -1,6 +1,6 @@
1
1
  // The schema version of the Tally database (BTN-133). The collector migrates up to it
2
2
  // (tally/src/migrations.ts, one step per version); the page refuses a database newer than this.
3
- export const TALLY_SCHEMA_VERSION = 9;
3
+ export const TALLY_SCHEMA_VERSION = 15;
4
4
  /** The collector's exit code when this code cannot migrate the database (newer, or rights missing): the service stops collecting until a restart. */
5
5
  export const HALTED = 2;
6
6
  /** 0 — no version recorded: an empty database or one created before versions. */
@@ -0,0 +1,3 @@
1
+ export const DEFAULT_BACKUP_KEEP = 14;
2
+ export const MAX_BACKUP_KEEP = 365;
3
+ export const DEFAULT_BACKUP = { dir: null, keep: DEFAULT_BACKUP_KEEP };
@@ -0,0 +1,197 @@
1
+ import { mkdirSync, rmSync } from 'node:fs';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { Worker } from 'node:worker_threads';
4
+ import { fail, notice } from '../notice/notice.js';
5
+ import { BackupError, backupDirOf, lastChecked, makeCopy, ownName, rotate } from './backup.js';
6
+ import { DEFAULT_BACKUP_KEEP, MAX_BACKUP_KEEP } from './backup-model.js';
7
+ import { rowsTextOf } from './copy.js';
8
+ import { databaseVersion } from './database.js';
9
+ import { databaseDirOf, filesDirOf } from './owner.js';
10
+ // The service's daily copy of the state database (BTN-1083): the rows are read here, the copy is written and checked
11
+ // on its own thread. `docs/storage.md`, "Backup, export, rollback".
12
+ const MINUTE = 60_000;
13
+ export const BACKUP_FIRST_LOOK_MS = 5 * MINUTE;
14
+ export const BACKUP_LOOK_EVERY_MS = 10 * MINUTE;
15
+ /** A copy is made when the newest checked one is older than this. */
16
+ export const BACKUP_EVERY_MS = 24 * 60 * MINUTE;
17
+ /** A failed copy is tried again after this. */
18
+ export const BACKUP_RETRY_MS = 60 * MINUTE;
19
+ export class Backups {
20
+ options;
21
+ timer = null;
22
+ running = null;
23
+ failure = null;
24
+ failedAt = 0;
25
+ last = null;
26
+ abort = new AbortController();
27
+ constructor(options) {
28
+ this.options = options;
29
+ }
30
+ start() {
31
+ this.timer = setTimeout(() => this.tick(), BACKUP_FIRST_LOOK_MS);
32
+ this.timer.unref();
33
+ }
34
+ async stop() {
35
+ if (this.timer !== null)
36
+ clearTimeout(this.timer);
37
+ this.timer = null;
38
+ this.abort.abort();
39
+ await this.running;
40
+ }
41
+ /** The copy made before the schema steps at the start failed: shown until a copy succeeds, the first look tries one. */
42
+ failedAtStart(failure) {
43
+ this.failure = failure;
44
+ }
45
+ view() {
46
+ const { dir } = this.options.settings();
47
+ return { dir, at: this.lastAt(dir), running: this.running !== null, failure: this.failure };
48
+ }
49
+ /** Makes a copy when the newest checked one is older than a day, unless a failed one waits for its retry. */
50
+ async look() {
51
+ if (this.running !== null || this.abort.signal.aborted)
52
+ return;
53
+ const now = this.now().getTime();
54
+ const { dir } = this.options.settings();
55
+ this.last = null;
56
+ const at = this.lastAt(dir);
57
+ if (at !== null && now - Date.parse(at) < BACKUP_EVERY_MS)
58
+ return;
59
+ if (this.failedAt > 0 && now - this.failedAt < BACKUP_RETRY_MS)
60
+ return;
61
+ this.begin();
62
+ await this.running;
63
+ }
64
+ /** Starts a copy and returns at once; refused while one runs. */
65
+ copyNow() {
66
+ if (this.running !== null)
67
+ throw fail('storage.backupRunning', {});
68
+ this.begin();
69
+ }
70
+ /** The copy under way, if any, ended. */
71
+ async idle() {
72
+ await this.running;
73
+ }
74
+ tick() {
75
+ void this.look().finally(() => {
76
+ if (this.abort.signal.aborted)
77
+ return;
78
+ this.timer = setTimeout(() => this.tick(), BACKUP_LOOK_EVERY_MS);
79
+ this.timer.unref();
80
+ });
81
+ }
82
+ begin() {
83
+ this.running = this.copy().finally(() => {
84
+ this.running = null;
85
+ this.last = null;
86
+ this.options.changed();
87
+ });
88
+ this.options.changed();
89
+ }
90
+ async copy() {
91
+ const { db, files, run, log } = this.options;
92
+ const { dir, keep } = this.options.settings();
93
+ let target = null;
94
+ try {
95
+ mkdirSync(dir, { recursive: true });
96
+ const from = performance.now();
97
+ const rows = await rowsTextOf(db);
98
+ const version = await databaseVersion(db);
99
+ log(`storage: the backup read the database in ${Math.round(performance.now() - from)} ms`);
100
+ target = join(dir, ownName(this.now(), version));
101
+ const check = await run({ rows, version, dir: target, files }, this.abort.signal);
102
+ const gone = rotate(dir, keep);
103
+ log(`storage: the backup ${target} is checked: ${Object.keys(check.tables).length} tables, ${check.files} files${gone.length > 0 ? `; removed ${gone.join(', ')}` : ''}`);
104
+ this.failure = null;
105
+ this.failedAt = 0;
106
+ }
107
+ catch (error) {
108
+ if (target !== null)
109
+ rmSync(target, { recursive: true, force: true });
110
+ if (this.abort.signal.aborted)
111
+ return;
112
+ const stage = error instanceof BackupError ? error.stage : 'copy';
113
+ log(`storage: the backup into ${target ?? dir} failed at the ${stage}: ${error instanceof Error ? error.message : String(error)}`);
114
+ this.failure = notice(stage === 'check' ? 'storage.backupCheckFailed' : 'storage.backupFailed', {});
115
+ this.failedAt = this.now().getTime();
116
+ }
117
+ }
118
+ lastAt(dir) {
119
+ if (this.last?.dir !== dir)
120
+ this.last = { dir, at: lastChecked(dir)?.check?.at ?? null };
121
+ return this.last.at;
122
+ }
123
+ now() {
124
+ return this.options.now?.() ?? new Date();
125
+ }
126
+ }
127
+ let startFailure = null;
128
+ /** The failure of the copy made before the schema steps, once: the service's `Backups` shows it. */
129
+ export function takeStartFailure() {
130
+ const failure = startFailure;
131
+ startFailure = null;
132
+ return failure;
133
+ }
134
+ /**
135
+ * The copy made at the start before an existing database takes new schema steps, on its old schema: in this thread,
136
+ * the service does not run yet. The settings are read from their rows as they are; a failure does not stop the start.
137
+ */
138
+ export function copyBeforeSteps(stateDir, log) {
139
+ return async (db, from) => {
140
+ const { dir, keep } = await storedSettings(db, stateDir);
141
+ const target = join(dir, ownName(new Date(), from));
142
+ try {
143
+ mkdirSync(dir, { recursive: true });
144
+ const check = await makeCopy({ rows: await rowsTextOf(db), version: from, dir: target, files: filesDirOf(databaseDirOf(stateDir)) });
145
+ const gone = rotate(dir, keep);
146
+ log(`storage: the copy before the schema steps from ${from} is checked in ${target}: ${check.files} files${gone.length > 0 ? `; removed ${gone.join(', ')}` : ''}`);
147
+ }
148
+ catch (error) {
149
+ rmSync(target, { recursive: true, force: true });
150
+ const stage = error instanceof BackupError ? error.stage : 'copy';
151
+ log(`storage: the copy before the schema steps from ${from} into ${target} failed at the ${stage}, the start goes on: ${error instanceof Error ? error.message : String(error)}`);
152
+ startFailure = notice(stage === 'check' ? 'storage.backupCheckFailed' : 'storage.backupFailed', {});
153
+ }
154
+ };
155
+ }
156
+ async function storedSettings(db, stateDir) {
157
+ const values = new Map();
158
+ try {
159
+ const { rows } = await db.query("select key, value from setting_values where key in ('backup.dir', 'backup.keep') and project_id is null and qualifier = ''");
160
+ for (const { key, value } of rows)
161
+ values.set(key, JSON.parse(value));
162
+ }
163
+ catch {
164
+ // A schema from before the settings' rows, or a value that does not parse: the defaults.
165
+ }
166
+ const dir = values.get('backup.dir');
167
+ const keep = values.get('backup.keep');
168
+ return {
169
+ dir: backupDirOf(stateDir, typeof dir === 'string' && isAbsolute(dir) ? dir : null),
170
+ keep: Number.isInteger(keep) && keep >= 1 && keep <= MAX_BACKUP_KEEP ? keep : DEFAULT_BACKUP_KEEP,
171
+ };
172
+ }
173
+ // The sources under tsx, the compiled `dist/src/storage/` from the build.
174
+ const workerFile = new URL(`./backup-worker${import.meta.url.endsWith('.ts') ? '.ts' : '.js'}`, import.meta.url);
175
+ /** `Backups`' `run` of the service: the copy on its own thread, terminated on abort. */
176
+ export function copyOnThread(job, signal) {
177
+ return new Promise((resolve, reject) => {
178
+ const thread = new Worker(workerFile, { workerData: job });
179
+ let answer = null;
180
+ const onAbort = () => void thread.terminate();
181
+ signal.addEventListener('abort', onAbort, { once: true });
182
+ thread.on('message', (message) => {
183
+ answer = message;
184
+ void thread.terminate();
185
+ });
186
+ thread.on('error', (error) => {
187
+ answer ??= { stage: 'copy', error: error.stack ?? error.message };
188
+ });
189
+ thread.on('exit', () => {
190
+ signal.removeEventListener('abort', onAbort);
191
+ if (answer !== null && 'check' in answer)
192
+ resolve(answer.check);
193
+ else
194
+ reject(new BackupError(answer?.stage ?? 'copy', answer?.error ?? 'the thread ended without an answer'));
195
+ });
196
+ });
197
+ }
@@ -0,0 +1,9 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { BackupError, makeCopy } from './backup.js';
3
+ // One automatic copy on its own thread (BTN-1083): writing a database, opening it back and hashing the attachments
4
+ // would stall the service's event loop.
5
+ const answer = await makeCopy(workerData).then((check) => ({ check }), (error) => ({
6
+ stage: error instanceof BackupError ? error.stage : 'copy',
7
+ error: error instanceof Error ? error.message : String(error),
8
+ }));
9
+ parentPort.postMessage(answer);
@@ -0,0 +1,141 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream, cpSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { PGlite } from '@electric-sql/pglite';
7
+ import { tablesOf, writeRows } from './copy.js';
8
+ import { databaseVersion, SQLITE_VERSIONS, STEPS } from './database.js';
9
+ import { dataDirOf, filesDirOf } from './owner.js';
10
+ // The automatic copies of the state database (BTN-1083): each written, opened back in a temporary folder and checked
11
+ // before it counts. `docs/storage.md`, "Backup, export, rollback".
12
+ /** The folder of the automatic copies when the setting `backup.dir` names none: `backups/` next to the database's folder. */
13
+ export const backupDirOf = (stateDir, setting) => setting ?? join(stateDir, 'backups');
14
+ export const CHECK_FILE = 'check.json';
15
+ const OWN_NAME = /^even-keel-auto-\d{8}-\d{6}-v\d+$/;
16
+ /** The name of an automatic copy: only folders of this pattern are ever rotated, never a copy made by hand. */
17
+ export function ownName(at, version) {
18
+ const iso = at.toISOString();
19
+ return `even-keel-auto-${iso.slice(0, 10).replaceAll('-', '')}-${iso.slice(11, 19).replaceAll(':', '')}-v${version}`;
20
+ }
21
+ /** A failed copy: `copy` — writing it, `check` — it was written but did not open back whole. */
22
+ export class BackupError extends Error {
23
+ stage;
24
+ constructor(stage, message) {
25
+ super(message);
26
+ this.stage = stage;
27
+ }
28
+ }
29
+ /** Writes the copy, checks it and marks it checked; the copy's folder goes on any failure. */
30
+ export async function makeCopy(job) {
31
+ if (existsSync(job.dir))
32
+ throw new BackupError('copy', `${job.dir} exists`);
33
+ let tables;
34
+ try {
35
+ const rows = JSON.parse(job.rows);
36
+ tables = Object.fromEntries(Object.entries(rows).map(([table, list]) => [table, list.length]));
37
+ await writeRows(rows, job.dir, job.files, STEPS.slice(0, job.version - SQLITE_VERSIONS));
38
+ }
39
+ catch (error) {
40
+ rmSync(job.dir, { recursive: true, force: true });
41
+ throw new BackupError('copy', messageOf(error));
42
+ }
43
+ try {
44
+ const check = await checkCopy(job.dir, job.version, tables, job.temp);
45
+ writeFileSync(join(job.dir, CHECK_FILE), `${JSON.stringify(check, null, 2)}\n`);
46
+ return check;
47
+ }
48
+ catch (error) {
49
+ rmSync(job.dir, { recursive: true, force: true });
50
+ throw new BackupError('check', messageOf(error));
51
+ }
52
+ }
53
+ /**
54
+ * A trial restore: the copy is copied whole into a temporary folder and opened there as the service would open it.
55
+ * Its schema must be `version`, its tables those of `tables` with as many rows, and each `builtin_files` record must
56
+ * find its file with the same sha256. The temporary folder goes either way.
57
+ */
58
+ export async function checkCopy(dir, version, tables, temp) {
59
+ const trial = temp ?? mkdtempSync(join(tmpdir(), 'even-keel-check-'));
60
+ try {
61
+ cpSync(dir, trial, { recursive: true });
62
+ const db = await PGlite.create({ dataDir: dataDirOf(trial) });
63
+ try {
64
+ const found = await databaseVersion(db);
65
+ if (found !== version)
66
+ throw new Error(`the copy is at schema ${found}, not ${version}`);
67
+ const counted = {};
68
+ for (const name of await tablesOf(db)) {
69
+ const { rows } = await db.query(`select count(*)::int as count from "${name}"`);
70
+ counted[name] = rows[0].count;
71
+ }
72
+ const differ = [...new Set([...Object.keys(tables), ...Object.keys(counted)])].filter((name) => tables[name] !== counted[name]);
73
+ if (differ.length > 0) {
74
+ throw new Error(`rows differ: ${differ.map((name) => `${name} has ${counted[name] ?? 'no table'} of ${tables[name] ?? 'none'}`).join(', ')}`);
75
+ }
76
+ const files = Object.hasOwn(counted, 'builtin_files') ? await checkFiles(db, filesDirOf(trial)) : 0;
77
+ return { at: new Date().toISOString(), version, tables: counted, files };
78
+ }
79
+ finally {
80
+ await db.close();
81
+ }
82
+ }
83
+ finally {
84
+ rmSync(trial, { recursive: true, force: true });
85
+ }
86
+ }
87
+ async function checkFiles(db, dir) {
88
+ const { rows } = await db.query('select distinct sha256 from builtin_files order by sha256');
89
+ const bad = [];
90
+ for (const { sha256 } of rows) {
91
+ const path = join(dir, sha256);
92
+ if (!existsSync(path))
93
+ bad.push(`${sha256} is missing`);
94
+ else if ((await hashOf(path)) !== sha256)
95
+ bad.push(`${sha256} has other bytes`);
96
+ }
97
+ if (bad.length > 0)
98
+ throw new Error(`attachments: ${bad.join(', ')}`);
99
+ return rows.length;
100
+ }
101
+ async function hashOf(path) {
102
+ const hash = createHash('sha256');
103
+ await pipeline(createReadStream(path), hash);
104
+ return hash.digest('hex');
105
+ }
106
+ /** The automatic copies of the folder, oldest first; folders of other names are no copies of ours. */
107
+ export function ownCopies(dir) {
108
+ if (!existsSync(dir))
109
+ return [];
110
+ return readdirSync(dir, { withFileTypes: true })
111
+ .filter((entry) => entry.isDirectory() && OWN_NAME.test(entry.name))
112
+ .map((entry) => ({ name: entry.name, path: join(dir, entry.name), check: checkOf(join(dir, entry.name)) }))
113
+ .sort((a, b) => a.name.localeCompare(b.name));
114
+ }
115
+ function checkOf(path) {
116
+ try {
117
+ const parsed = JSON.parse(readFileSync(join(path, CHECK_FILE), 'utf8'));
118
+ return typeof parsed.at === 'string' && typeof parsed.version === 'number' ? parsed : null;
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ }
124
+ /** The newest checked copy of the folder; `null` — none. */
125
+ export const lastChecked = (dir) => ownCopies(dir).findLast((copy) => copy.check !== null) ?? null;
126
+ /**
127
+ * Keeps the newest `keep` checked copies: older checked ones go, and so do unchecked ones older than the newest checked
128
+ * (a copy a crash cut short). Without a checked copy nothing goes. Returns the names removed.
129
+ */
130
+ export function rotate(dir, keep) {
131
+ const copies = ownCopies(dir);
132
+ const checked = copies.filter((copy) => copy.check !== null);
133
+ const newest = checked.at(-1);
134
+ if (newest === undefined)
135
+ return [];
136
+ const gone = [...checked.slice(0, Math.max(0, checked.length - keep)), ...copies.filter((copy) => copy.check === null && copy.name < newest.name)];
137
+ for (const copy of gone)
138
+ rmSync(copy.path, { recursive: true, force: true });
139
+ return gone.map((copy) => copy.name).sort();
140
+ }
141
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));