rvlib-shipkit 2.31.0 → 2.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (384) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/package.json +1 -1
  3. package/src/advisors/acts.ts +16 -15
  4. package/src/advisors/advice.ts +56 -102
  5. package/src/advisors/advisor-view.ts +98 -73
  6. package/src/advisors/app-graph.ts +1 -1
  7. package/src/advisors/app.ts +3 -11
  8. package/src/advisors/cf-api.ts +1 -1
  9. package/src/advisors/dir-bucket.ts +4 -3
  10. package/src/advisors/edge/api.ts +26 -198
  11. package/src/advisors/edge/bucket.ts +2 -2
  12. package/src/advisors/edge/handler.ts +13 -155
  13. package/src/advisors/edge/here.ts +5 -5
  14. package/src/advisors/edge/pages.ts +12 -9
  15. package/src/advisors/edge/shell.ts +6 -5
  16. package/src/advisors/edge/sign-in.ts +101 -36
  17. package/src/advisors/edge/status.ts +19 -6
  18. package/src/advisors/edge/types.ts +36 -60
  19. package/src/advisors/expose.ts +29 -29
  20. package/src/advisors/here.ts +12 -12
  21. package/src/advisors/invite-send.ts +79 -35
  22. package/src/advisors/invite.ts +31 -8
  23. package/src/advisors/job.ts +24 -16
  24. package/src/advisors/login.ts +40 -15
  25. package/src/advisors/owner-store.ts +46 -22
  26. package/src/advisors/photos.ts +3 -3
  27. package/src/advisors/project.ts +25 -23
  28. package/src/advisors/reach.ts +89 -0
  29. package/src/advisors/rights.ts +1 -1
  30. package/src/advisors/routes.ts +55 -74
  31. package/src/advisors/scan.ts +0 -4
  32. package/src/advisors/setup-run.ts +14 -14
  33. package/src/advisors/share-trace.ts +3 -3
  34. package/src/advisors/{door-probe.ts → sign-in-probe.ts} +7 -6
  35. package/src/advisors/speaks.ts +29 -0
  36. package/src/advisors/sync.ts +92 -182
  37. package/src/advisors/tunnel.ts +6 -5
  38. package/src/advisors/users-listen.ts +92 -0
  39. package/src/advisors/users-router.ts +257 -85
  40. package/src/advisors/users-store.ts +81 -0
  41. package/src/agent-time/blocked-scan.ts +181 -0
  42. package/src/agent-time/registry.ts +12 -5
  43. package/src/agent-time/store.ts +9 -109
  44. package/src/asks/ask-bar-fold.ts +2 -1
  45. package/src/asks/ask-close.ts +2 -1
  46. package/src/asks/ask-doc.ts +2 -1
  47. package/src/asks/ask-migrate.ts +3 -2
  48. package/src/asks/ask-steps-fold.ts +2 -1
  49. package/src/asks/ask-store.ts +4 -3
  50. package/src/check.ts +3 -43
  51. package/src/checks/SK001-package-json-shape.check.ts +4 -55
  52. package/src/checks/SK004-gitignore-policy.check.ts +24 -69
  53. package/src/checks/SK013-one-way-in-policy.check.ts +3 -7
  54. package/src/checks/SK017-vscode-hub-task.check.ts +4 -4
  55. package/src/checks/SK019-tests-run-in-units.check.ts +3 -14
  56. package/src/checks/SK020-self-spawning-check.check.ts +5 -7
  57. package/src/checks/SK035-public-clean.check.ts +1 -1
  58. package/src/checks/SK039-vscode-watch-generated.check.ts +1 -1
  59. package/src/checks/SK042-post-kinds.check.ts +5 -14
  60. package/src/checks/SK054-agent-allow-list.check.ts +5 -74
  61. package/src/checks/SK055-retired-config-keys.check.ts +45 -0
  62. package/src/cli/cmd_Advisors.ts +11 -45
  63. package/src/cli/cmd_Asks.ts +3 -10
  64. package/src/cli/cmd_Backup.ts +25 -127
  65. package/src/cli/cmd_BackupTargets.ts +1 -1
  66. package/src/cli/cmd_Checks.ts +0 -14
  67. package/src/cli/cmd_Db.ts +3 -82
  68. package/src/cli/cmd_Home.ts +4 -32
  69. package/src/cli/cmd_Hq.ts +0 -17
  70. package/src/cli/cmd_Releases.ts +57 -4
  71. package/src/cli/cmd_Review.ts +333 -354
  72. package/src/cli/cmd_SocialDrafts.ts +6 -13
  73. package/src/cli/cmd_ThreadSyncNeeds.ts +6 -2
  74. package/src/cli/cmd_Time.ts +1 -1
  75. package/src/cli/cmd_Trailer.ts +1 -1
  76. package/src/cli/inbox-hook-run.ts +5 -23
  77. package/src/cli/registry-heads.ts +5 -55
  78. package/src/cli/registry.ts +1 -5
  79. package/src/cli/review-here.ts +1 -1
  80. package/src/cli.ts +2 -2
  81. package/src/collections/collection-types.ts +1 -1
  82. package/src/collections/review.ts +5 -4
  83. package/src/core/agent-allow-policy.ts +32 -2
  84. package/src/core/agent-env.ts +8 -0
  85. package/src/core/allow-rows.ts +74 -0
  86. package/src/core/check-file-names.ts +19 -106
  87. package/src/core/footprint.ts +17 -13
  88. package/src/core/identities-root.ts +1 -4
  89. package/src/core/layout.ts +1 -2
  90. package/src/core/machine-db.ts +33 -208
  91. package/src/core/machine-layout.ts +14 -127
  92. package/src/core/mask-source.ts +60 -0
  93. package/src/core/memory-watch.ts +17 -14
  94. package/src/core/motherhome.ts +8 -35
  95. package/src/core/one-way-in-policy.ts +0 -3
  96. package/src/core/repo-walk.ts +0 -9
  97. package/src/core/retention.ts +1 -9
  98. package/src/core/retired-checks.ts +2 -0
  99. package/src/core/tmux-policy.ts +1 -1
  100. package/src/core/tree-watch.ts +2 -2
  101. package/src/core/when.ts +7 -45
  102. package/src/gate/discover-checks.ts +42 -32
  103. package/src/gate/gate-checks.ts +21 -131
  104. package/src/gate/pre-commit-discovery.ts +16 -25
  105. package/src/gate/run-check.ts +0 -4
  106. package/src/gate/run-fix.ts +5 -17
  107. package/src/gate/run-fixers.ts +6 -42
  108. package/src/home/app-sign.ts +2 -2
  109. package/src/home/backup-status.ts +52 -92
  110. package/src/home/backup-verdict.ts +2 -2
  111. package/src/home/daemon-jobs.ts +51 -95
  112. package/src/home/database-words.ts +1 -2
  113. package/src/home/databases.ts +9 -25
  114. package/src/home/home-launchd.ts +0 -6
  115. package/src/home/home-paths.ts +8 -4
  116. package/src/home/home-routes.ts +3 -10
  117. package/src/home/home-state.ts +2 -14
  118. package/src/home/inbox-shape.ts +14 -15
  119. package/src/home/inbox.ts +1 -1
  120. package/src/home/machine-repair.ts +102 -103
  121. package/src/home/resume.ts +1 -15
  122. package/src/home/run-daemon.ts +4 -11
  123. package/src/home/space-page.ts +3 -2
  124. package/src/home/supervise.ts +3 -7
  125. package/src/hooks/hook-config.ts +6 -7
  126. package/src/hooks/leak-guard.ts +1 -1
  127. package/src/hooks/run-hooks.ts +0 -5
  128. package/src/hq/daemon-db.ts +8 -8
  129. package/src/hq/door.ts +3 -16
  130. package/src/hq/hq-db.ts +4 -3
  131. package/src/hq/hq-local.ts +1 -2
  132. package/src/hq/hq-store.ts +0 -15
  133. package/src/hq/item-direct.ts +8 -10
  134. package/src/hq/item-fill.ts +37 -0
  135. package/src/hq/kinds/item-gone.ts +7 -10
  136. package/src/hq/kinds/item-msg.ts +12 -18
  137. package/src/hq/kinds/item.ts +13 -19
  138. package/src/hq/kinds/report.ts +3 -4
  139. package/src/hq/owner-switch.ts +3 -3
  140. package/src/hq/report.ts +5 -9
  141. package/src/hq/switch.ts +2 -11
  142. package/src/hq/thread-sync.ts +5 -17
  143. package/src/hq/{shapes-words.ts → threads-words.ts} +2 -12
  144. package/src/http/owner-word.ts +1 -1
  145. package/src/identities/machine.ts +16 -0
  146. package/src/init-repo.ts +0 -1
  147. package/src/ledger/check-stats.ts +6 -5
  148. package/src/ledger/db.ts +2 -4
  149. package/src/ledger/record-kept.ts +117 -48
  150. package/src/ledger/run-log.ts +21 -2
  151. package/src/ledger/slow-tests.ts +96 -0
  152. package/src/ledger/store.ts +3 -86
  153. package/src/ledger/suite-log.ts +8 -2
  154. package/src/media-store/backup/facts.ts +3 -37
  155. package/src/media-store/backup/keys.ts +1 -8
  156. package/src/media-store/backup/manifest.ts +6 -67
  157. package/src/media-store/backup/restore.ts +4 -13
  158. package/src/media-store/backup/retention.ts +13 -1
  159. package/src/media-store/backup/run.ts +6 -267
  160. package/src/media-store/backup/snapshot.ts +2 -38
  161. package/src/media-store/backup/sources.ts +3 -113
  162. package/src/media-store/backup/target-send.ts +5 -29
  163. package/src/media-store/db.ts +8 -7
  164. package/src/media-store/forget-one.ts +1 -1
  165. package/src/media-store/forget.ts +1 -80
  166. package/src/orchestrator/guards.ts +0 -1
  167. package/src/orchestrator/presence.ts +2 -2
  168. package/src/orchestrator/routes.ts +1 -1
  169. package/src/orchestrator/started.ts +0 -9
  170. package/src/orchestrator/talk-key.ts +3 -4
  171. package/src/orchestrator/unheard.ts +1 -1
  172. package/src/recordings/edit.ts +3 -3
  173. package/src/recordings/marks-draw.ts +17 -6
  174. package/src/recordings/marks.ts +120 -9
  175. package/src/reflections/reflections-queue.ts +3 -10
  176. package/src/release/notes.ts +1 -1
  177. package/src/release/public-clean.ts +66 -6
  178. package/src/release/run-bump.ts +11 -0
  179. package/src/release/run-release.ts +4 -0
  180. package/src/releases/from-thread.ts +3 -3
  181. package/src/releases/model.ts +186 -36
  182. package/src/releases/store.ts +13 -3
  183. package/src/releases/validate.ts +83 -0
  184. package/src/repo-config.ts +29 -64
  185. package/src/review/answer-kinds.ts +61 -4
  186. package/src/review/blocked-guard.ts +11 -0
  187. package/src/review/blocked-object.ts +298 -0
  188. package/src/review/cells.ts +116 -229
  189. package/src/review/close.ts +39 -1
  190. package/src/review/doc-save.ts +3 -2
  191. package/src/review/draft-item.ts +1 -1
  192. package/src/review/events.ts +3 -7
  193. package/src/review/expect.ts +23 -39
  194. package/src/review/format.ts +79 -46
  195. package/src/review/glyphs.ts +1 -0
  196. package/src/review/hand-over.ts +3 -3
  197. package/src/review/heard.ts +1 -1
  198. package/src/review/holds-sync.ts +2 -1
  199. package/src/review/inbox-hook.ts +2 -2
  200. package/src/review/inbox-read.ts +39 -33
  201. package/src/review/instruction-guards.ts +12 -0
  202. package/src/review/instructions.ts +0 -1
  203. package/src/review/item-db.ts +13 -43
  204. package/src/review/item-hq.ts +2 -2
  205. package/src/review/item-rows.ts +3 -14
  206. package/src/review/kind-catalog.ts +3 -1
  207. package/src/review/kinds.ts +18 -8
  208. package/src/review/live-view.ts +3 -0
  209. package/src/review/media-kind.ts +1 -1
  210. package/src/review/mentions.ts +1 -2
  211. package/src/review/model.ts +158 -114
  212. package/src/review/move.ts +149 -0
  213. package/src/review/need-threads.ts +3 -2
  214. package/src/review/object-card.ts +11 -0
  215. package/src/review/object-read.ts +6 -1
  216. package/src/review/one-block.ts +1 -1
  217. package/src/review/owner-read.ts +1 -1
  218. package/src/review/phone-push.ts +10 -9
  219. package/src/review/previews.ts +32 -4
  220. package/src/review/push.ts +2 -2
  221. package/src/review/recap.ts +129 -0
  222. package/src/review/referring.ts +6 -3
  223. package/src/review/reflection-object.ts +4 -3
  224. package/src/review/routes.ts +49 -19
  225. package/src/review/secret-route.ts +3 -2
  226. package/src/review/settle.ts +0 -6
  227. package/src/review/snooze.ts +5 -3
  228. package/src/review/speaker.ts +68 -0
  229. package/src/review/start-title.ts +19 -0
  230. package/src/review/store.ts +86 -59
  231. package/src/review/{wakes.ts → thread-events.ts} +92 -7
  232. package/src/review/thread-md.ts +35 -14
  233. package/src/review/thread-state.ts +798 -0
  234. package/src/review/threads.ts +29 -347
  235. package/src/review/traces.ts +104 -7
  236. package/src/review/trailer-item.ts +1 -1
  237. package/src/review/unit.ts +7 -9
  238. package/src/review/verdict-items.ts +12 -10
  239. package/src/review/view-layout.ts +25 -1
  240. package/src/review/watch-feed.ts +1 -2
  241. package/src/review/working-guards.ts +2 -3
  242. package/src/rules/untrack-generated.ts +1 -15
  243. package/src/secrets/lapse.ts +2 -1
  244. package/src/serve/hub-app/advisor-app.tsx +4 -4
  245. package/src/serve/hub-app/advisor-face.tsx +9 -3
  246. package/src/serve/hub-app/advisor-host.ts +27 -27
  247. package/src/serve/hub-app/advisors-model.ts +17 -8
  248. package/src/serve/hub-app/advisors-rights.tsx +1 -1
  249. package/src/serve/hub-app/advisors-st.ts +15 -14
  250. package/src/serve/hub-app/advisors-view.tsx +13 -11
  251. package/src/serve/hub-app/app-bridge.ts +23 -3
  252. package/src/serve/hub-app/asks-page.tsx +1 -1
  253. package/src/serve/hub-app/auto-text.tsx +71 -16
  254. package/src/serve/hub-app/check-view.tsx +0 -8
  255. package/src/serve/hub-app/controls.css +14 -3
  256. package/src/serve/hub-app/database-view.tsx +1 -2
  257. package/src/serve/hub-app/git-view.tsx +3 -1
  258. package/src/serve/hub-app/hub.css +12 -5
  259. package/src/serve/hub-app/icons.tsx +1 -1
  260. package/src/serve/hub-app/inbox-view.tsx +1 -2
  261. package/src/serve/hub-app/live-sources.ts +2 -2
  262. package/src/serve/hub-app/main-panel.tsx +2 -1
  263. package/src/serve/hub-app/panel-repo.ts +0 -9
  264. package/src/serve/hub-app/pic.tsx +29 -12
  265. package/src/serve/hub-app/polled.ts +16 -2
  266. package/src/serve/hub-app/recordings-st.ts +23 -2
  267. package/src/serve/hub-app/recordings-view.tsx +68 -10
  268. package/src/serve/hub-app/ref-pill.ts +1 -1
  269. package/src/serve/hub-app/repo-st.ts +1 -2
  270. package/src/serve/hub-app/review/advisor-add.tsx +1 -1
  271. package/src/serve/hub-app/review/advisor-invite.tsx +1 -1
  272. package/src/serve/hub-app/review/draft-body.tsx +2 -2
  273. package/src/serve/hub-app/review/heard-line.tsx +1 -1
  274. package/src/serve/hub-app/review/instructions-view.tsx +1 -8
  275. package/src/serve/hub-app/review/kind-states.tsx +14 -9
  276. package/src/serve/hub-app/review/kit.tsx +4 -11
  277. package/src/serve/hub-app/review/lane-bar.tsx +3 -3
  278. package/src/serve/hub-app/review/lightbox.tsx +15 -11
  279. package/src/serve/hub-app/review/line-window.ts +4 -1
  280. package/src/serve/hub-app/review/live-bar-st.ts +2 -2
  281. package/src/serve/hub-app/review/live-view.tsx +57 -1
  282. package/src/serve/hub-app/review/object-panel.tsx +20 -8
  283. package/src/serve/hub-app/review/question-views.tsx +181 -54
  284. package/src/serve/hub-app/review/recap-bar.tsx +40 -0
  285. package/src/serve/hub-app/review/request-cell.tsx +48 -0
  286. package/src/serve/hub-app/review/review-cells.tsx +154 -96
  287. package/src/serve/hub-app/review/review-host.ts +2 -2
  288. package/src/serve/hub-app/review/review-kit.ts +17 -11
  289. package/src/serve/hub-app/review/review-list.tsx +23 -31
  290. package/src/serve/hub-app/review/review-st.ts +30 -40
  291. package/src/serve/hub-app/review/review-thread.tsx +139 -85
  292. package/src/serve/hub-app/review/review-views.tsx +124 -68
  293. package/src/serve/hub-app/review/share-lines.tsx +4 -4
  294. package/src/serve/hub-app/review/start-st.ts +2 -5
  295. package/src/serve/hub-app/review/superseded-runs.ts +4 -3
  296. package/src/serve/hub-app/review/thread-close.tsx +10 -7
  297. package/src/serve/hub-app/review/thread-st.ts +372 -201
  298. package/src/serve/hub-app/review/tone-bar.tsx +126 -0
  299. package/src/serve/hub-app/review/tones.ts +35 -0
  300. package/src/serve/hub-app/review/trailer-body.tsx +2 -2
  301. package/src/serve/hub-app/review/trailer-st.ts +3 -2
  302. package/src/serve/hub-app/review/trailer-voices-st.ts +3 -2
  303. package/src/serve/hub-app/review.css +180 -106
  304. package/src/serve/hub-app/search-view.tsx +1 -1
  305. package/src/serve/hub-app/social/social-model.ts +0 -4
  306. package/src/serve/hub-app/source-acts.ts +2 -1
  307. package/src/serve/hub-app/stores/stores-page.tsx +2 -2
  308. package/src/serve/hub-app/terminal-sources.tsx +2 -1
  309. package/src/serve/hub-app/thread-row.tsx +3 -4
  310. package/src/serve/hub-app/tree-build.ts +0 -4
  311. package/src/serve/hub-app/urls-view.tsx +2 -1
  312. package/src/serve/hub-app/view-layout.css +13 -3
  313. package/src/serve/hub-app/wikis-view.tsx +5 -2
  314. package/src/serve/hub-runtime.ts +7 -37
  315. package/src/serve/project-gutter-route.ts +6 -2
  316. package/src/serve/read-thread.ts +20 -2
  317. package/src/serve/read-worker.ts +9 -1
  318. package/src/serve/record-pages.ts +46 -0
  319. package/src/serve/serve-hub.ts +2 -2
  320. package/src/serve/terminal-host.ts +1 -1
  321. package/src/serve/terminal-route.ts +1 -3
  322. package/src/serve/tracked-watch.ts +1 -3
  323. package/src/setup-house.ts +2 -2
  324. package/src/shipkit-files.ts +1 -1
  325. package/src/shipkit.ts +1 -6
  326. package/src/shot/film-box.ts +0 -20
  327. package/src/social/drafts.ts +1 -1
  328. package/src/social/kinds.ts +6 -29
  329. package/src/social/load.ts +2 -2
  330. package/src/social/post-object.ts +3 -2
  331. package/src/social/release-stage.ts +1 -1
  332. package/src/social/stage.ts +2 -2
  333. package/src/stores/model.ts +4 -0
  334. package/src/stores/routes.ts +11 -3
  335. package/src/suite/judge-suites.ts +58 -0
  336. package/src/suite/red-alone.ts +54 -18
  337. package/src/suite/runner-shapes.ts +2 -2
  338. package/src/suite/suite-cli.ts +67 -14
  339. package/src/suite/test-units.ts +2 -1
  340. package/src/urls/fill.ts +1 -1
  341. package/src/urls/places.ts +1 -2
  342. package/src/vault/vault-config.ts +2 -2
  343. package/src/vault/vault-init.ts +1 -5
  344. package/src/wiki/graph-page.ts +14 -2
  345. package/src/advisors/copy-truth.ts +0 -49
  346. package/src/advisors/door-child.ts +0 -112
  347. package/src/advisors/door-serve.ts +0 -52
  348. package/src/advisors/door.ts +0 -118
  349. package/src/checks/SK016-legacy-check-shapes.check.ts +0 -189
  350. package/src/checks/SK029-explicit-check-files.check.ts +0 -112
  351. package/src/checks/SK048-one-local-file.check.ts +0 -36
  352. package/src/core/config-rewrite.ts +0 -111
  353. package/src/core/daemon-port.ts +0 -10
  354. package/src/core/legacy-shapes.ts +0 -263
  355. package/src/core/migrate-layout.ts +0 -638
  356. package/src/core/port-check-cli.ts +0 -52
  357. package/src/core/port-check-file.ts +0 -295
  358. package/src/core/port-check-files.ts +0 -31
  359. package/src/gate/discover-legacy-checks.ts +0 -26
  360. package/src/home/home-move.ts +0 -527
  361. package/src/home/machine-fold.ts +0 -810
  362. package/src/hq/item-shapes.ts +0 -54
  363. package/src/hq/kinds/items-read.ts +0 -4
  364. package/src/media-store/backup/daemon.ts +0 -220
  365. package/src/media-store/backup/kept.ts +0 -241
  366. package/src/media-store/backup/prune.ts +0 -359
  367. package/src/media-store/backup/secret.ts +0 -88
  368. package/src/media-store/backup/ssh-space.ts +0 -202
  369. package/src/media-store/backup/watch.ts +0 -117
  370. package/src/review/band.ts +0 -182
  371. package/src/review/folders.ts +0 -216
  372. package/src/review/hook-ask.ts +0 -58
  373. package/src/review/role.ts +0 -48
  374. package/src/review/thread-fold.ts +0 -64
  375. package/src/review/wait.ts +0 -91
  376. package/src/rules/rule.ts +0 -43
  377. package/src/serve/hook-thread.ts +0 -37
  378. package/src/serve/hook-work.ts +0 -92
  379. package/src/serve/hook-worker.ts +0 -57
  380. package/src/serve/hub-app/review/dock.tsx +0 -147
  381. package/src/serve/hub-app/review/faces.tsx +0 -18
  382. package/src/serve/hub-app/review/item-verdict.tsx +0 -112
  383. package/src/serve/hub-app/review/review-board.tsx +0 -48
  384. /package/src/{scaffold → core}/jsonc-spans.ts +0 -0
@@ -0,0 +1,798 @@
1
+ // a thread's state, the one model (wiki tools/shipkit/threads-how-it-fits.md, The model): `threadState` gives its turn,
2
+ // what waits on the owner, what the agents owe, whether it is closed, its holder, working line, promise and set aside;
3
+ // `bandOf` gives the band from that state and the parties, the one reader of the registry. Every surface reads them (the
4
+ // hub's list, rows and dock, the inbox hook, `sk thread`, the phone, the advisors' page, the guards on a thread's state);
5
+ // its table is tests/thread-state.test.ts, every verb against every state. Pure and browser safe
6
+ // the one constraint a reader breaks first: whose turn, closed or owed is read off ThreadState, never decided again
7
+ // from the head's item state (model.ts stateOf) or from the messages
8
+ import { kindOfAsk, askOpen } from './answer-kinds.ts'
9
+ import type { MessageType } from './glyphs.ts'
10
+ import { heldOpen, holdMoveOf, holdsOf, type Hold } from './holds.ts'
11
+ import { laneAskOf, laneAskOwed, type LaneAsk } from './lane-ask.ts'
12
+ import {
13
+ asksNoVerdict,
14
+ byMachine,
15
+ handedOver,
16
+ inWork,
17
+ isClosedAskState,
18
+ isOpening,
19
+ itemWithdrawOf,
20
+ moveOf,
21
+ NO_SPEC,
22
+ partyOf,
23
+ proposeOpen,
24
+ reworkOf,
25
+ stateOf,
26
+ subjectKey,
27
+ updatesOf,
28
+ verdictOf,
29
+ leftUnansweredOf,
30
+ withdrawnOf,
31
+ openBrokenOf,
32
+ toAcknowledge,
33
+ WORKING_FRESH_MS,
34
+ type AskState,
35
+ type Message,
36
+ type ReviewItem,
37
+ type ReviewStatus,
38
+ type ShownStatus,
39
+ type Spec,
40
+ type Subject,
41
+ } from './model.ts'
42
+ import type { Holder, Parties } from './parties.ts'
43
+ import { replacersOf } from './supersede.ts'
44
+ import { AFTER_MOVE, asksWork, messageMove, openingOf, wakeOf, wakingUnread, type Move } from './thread-events.ts'
45
+ import { askFactsOf, askItemOf, answererOf, holderOf, membersOf, newest, oldest, supersederOf, threadsOf, threadTitle, type Thread } from './threads.ts'
46
+ import { cursorOf, workingsOf, type Cursor } from './traces.ts'
47
+ import { openVerdictAsks } from './verdict-items.ts'
48
+ import { recapStateOf, type RecapRef, type RecapState } from './recap.ts'
49
+ import { slugWords } from '../core/slug.ts'
50
+
51
+ /** who acts now on a thread: the owner's turn, the owner's turn set aside, an agent's move (whether one works it now is the band's),
52
+ * nothing owed */
53
+ export type Turn = 'yours' | 'aside' | 'agents' | 'done'
54
+
55
+ /** how the thread stands closed: by the owner's act (the owner's OK or archive, the owner's close, the owner's own save), by an agent or the machine
56
+ * (`sk thread close`, a withdraw, a machine `fixed`), or by its ask (done, declined, cancelled, merged) */
57
+ export interface Closed {
58
+ at: string
59
+ by: 'owner' | 'agent' | 'ask'
60
+ who: string
61
+ why: string
62
+ }
63
+
64
+ /** one thing that waits on the owner, in the dock's order: its verb, what a row draws for it, the cell a click jumps to */
65
+ export interface OwnerWaiting {
66
+ wait: OwnerWait
67
+ on: WaitsOn
68
+ /** the cell: `<item>/<message>` for a message, the item id for a version or the ask */
69
+ id: string
70
+ what: 'question' | 'change' | 'words' | 'steps' | 'ask' | 'version' | 'note' | 'hold'
71
+ /** the ask's title on `ask` and `steps`, the hold's address on `hold` */
72
+ title?: string
73
+ /** the version's number on `version` */
74
+ n?: number
75
+ /** a field inside a step of an ask's instructions: it waits as its step does, never on a line of its own */
76
+ step?: true
77
+ }
78
+
79
+ /** the work a tone that gives the version back owes its agent */
80
+ export type OwedWork = 'fix' | 'redo' | 'rethink' | 'decide'
81
+ export const OWED_OF: Partial<Record<ReviewStatus, OwedWork>> = { 'approved-with-fix': 'fix', rework: 'redo', 'wrong-direction': 'rethink', 'your-call': 'decide' }
82
+ export const isOwedWork = (k: string): k is OwedWork => k === 'fix' || k === 'redo' || k === 'rethink' || k === 'decide'
83
+
84
+ /** why the agents owe the thread a move, each with its time; an agent's close owes nothing of what came before it */
85
+ export type Owed =
86
+ /** the owner's newest word that asks work with no agent act since: unseen (`read` null), or read by an agent */
87
+ | { kind: 'word'; id: string; at: string; word: Message; read: { who: string; at: string } | null }
88
+ /** the owner's note, or a player's, open */
89
+ | { kind: 'note'; id: string; at: string }
90
+ /** the owner's tone that gives the version back, the work not done (OWED_OF): « ok with a fix » a fix, « rework » a redo,
91
+ * « wrong direction » a rethink with a question before building, « your call » the agent's own decision */
92
+ | { kind: OwedWork; id: string; at: string; seen: boolean }
93
+ /** the owner's OK with words or rectangles an agent has not read */
94
+ | { kind: 'approval-note'; id: string; at: string }
95
+ /** a lane reworking it on its claim */
96
+ | { kind: 'rework'; lane: string; at: string; until: number }
97
+ /** a version in work, or an opening whose newest update says « broken » or « better » */
98
+ | { kind: 'in-work'; id: string; at: string; broken: Message | null }
99
+ /** an agent's promise of the next version */
100
+ | { kind: 'promise'; at: string; next: NextVersion }
101
+ /** the owner's request for a lane */
102
+ | { kind: 'lane-ask'; at: string; ask: LaneAsk }
103
+ /** an attached object of an agent's move holds it open */
104
+ | { kind: 'hold'; at: string; address: string }
105
+
106
+ /** a thread's state: everything a surface shows or a guard decides of it */
107
+ export interface ThreadState {
108
+ turn: Turn
109
+ closed: Closed | null
110
+ /** the head's shown status */
111
+ status: ShownStatus
112
+ /** the head version waits for the owner's verdict now */
113
+ headWaits: boolean
114
+ /** what waits on the owner, in the dock's order: on the owner's turn, and as a quiet mark on the agents' move */
115
+ waitsOwner: OwnerWaiting[]
116
+ /** the badge: the first waiting verb on the owner's turn (`answer` when none explains it), else `agents` or `done` */
117
+ wait: Wait
118
+ /** what waits on the owner first, the icon a row draws */
119
+ waitsOn?: WaitsOn
120
+ /** on the agents' move after the owner's last word, the verb of what still waits on the owner */
121
+ owed?: OwnerWait
122
+ /** every verb the owner's open objects ask, none once the turn is not the owner's */
123
+ verbs: OwnerWait[]
124
+ /** why the agents owe a move; empty on every other turn */
125
+ owes: Owed[]
126
+ /** the owner's newest word that asks something with no agent answer since: a `working`, a read, a take answer nothing
127
+ * (the hook names it on a held thread of the agents' move); null once an agent answered */
128
+ unanswered: Message | null
129
+ /** something is owed by someone: the turn is not done */
130
+ active: boolean
131
+ /** done with the owner's yes: an OK, an « ok with a fix » whose fix is done, the ask done */
132
+ validated: boolean
133
+ holder: Holder | null
134
+ /** the newest `working` no act followed, whatever its age */
135
+ working: { who: string; at: string; note: string; session?: string } | null
136
+ next: NextVersion | null
137
+ laneAsk: LaneAsk | null
138
+ aside: { until: string; moved: boolean } | null
139
+ holds: Hold[]
140
+ /** an ask's thread: where its ask stands */
141
+ ask: { state: AskState; at: string } | null
142
+ cursor: Cursor | null
143
+ /** its recaps (review/recap.ts): the newest the owner accepted, which readers start at; one waiting on the owner's
144
+ * verdict; the owner's request no recap answered yet; an offer open or declined. Null when it holds none */
145
+ recap: RecapState | null
146
+ /** the newest message of any of its items (no read mark, no hand over), else the head's time: the row's time */
147
+ updated: string
148
+ }
149
+
150
+ const kept = new WeakMap<Thread, { members: number; messages: number; now: number; s: ThreadState }>()
151
+
152
+ /** the thread's state now; read once per thread, its messages and the clock */
153
+ export function threadState(t: Thread, now = new Date()): ThreadState {
154
+ const members = membersOf(t)
155
+ let messages = 0
156
+ for (const x of members) messages += x.thread.length
157
+ const k = kept.get(t)
158
+ if (k !== undefined && k.members === members.length && k.messages === messages && k.now === now.getTime()) return k.s
159
+ const s = stateOfThread(t, members, now)
160
+ kept.set(t, { members: members.length, messages, now: now.getTime(), s })
161
+ return s
162
+ }
163
+
164
+ function stateOfThread(t: Thread, members: ReviewItem[], now: Date): ThreadState {
165
+ const closed = closedOf(t)
166
+ const next = promiseOf(t, closed)
167
+ const head = waits(t.head) && next === null
168
+ const waiting = waitingOf(t, head)
169
+ const owes = owesOf(t, now, closed, next)
170
+ const turn = turnFrom(t, members, now, waiting, owes)
171
+ const status = statusOf(t.head, members)
172
+ const asked = askItemOf(t)
173
+ const ask = asked !== null ? ((s) => ({ state: s?.state ?? 'open', at: s?.at ?? asked.item.created }))(askStateOf(t)) : null
174
+ const first = waiting[0]
175
+ const verbs = turn === 'yours' || turn === 'aside' ? (waiting.length > 0 ? [...new Set(waiting.map((w) => w.wait))] : (['answer'] as OwnerWait[])) : []
176
+ const wait: Wait = turn === 'done' || turn === 'agents' ? turn : (first?.wait ?? 'answer')
177
+ const last = workingsOf(t, now).last
178
+ const until = asideUntilAt(t, now)
179
+ return {
180
+ turn,
181
+ closed,
182
+ status,
183
+ headWaits: head,
184
+ waitsOwner: waiting,
185
+ wait,
186
+ ...(first !== undefined && turn !== 'done' && turn !== 'agents' ? { waitsOn: first.on } : {}),
187
+ ...(first !== undefined && turn === 'agents' ? { owed: first.wait } : {}),
188
+ verbs,
189
+ owes: turn === 'agents' ? owes : [],
190
+ unanswered: unansweredWord(t),
191
+ active: turn !== 'done',
192
+ validated: validatedOf({ turn, status, ...(ask !== null ? { ask: ask.state } : {}) }),
193
+ holder: holderOf(t),
194
+ working: last === null ? null : { who: last.who, at: last.at, note: last.note, ...(last.session ? { session: last.session } : {}) },
195
+ next,
196
+ laneAsk: laneAskOf(members),
197
+ aside: until === null ? null : { until, moved: movedSince(members) },
198
+ holds: holdsOf(members),
199
+ ask,
200
+ cursor: cursorOf(t, now),
201
+ recap: recapStateOf(members),
202
+ updated: updatedOf(t, members),
203
+ }
204
+ }
205
+
206
+ /** whose move: what waits on the owner first, then what the agents owe, then an object that holds it open; the owner's words
207
+ * after what waits on the owner pass the ball (AFTER_MOVE); the owner's turn set aside reads aside */
208
+ function turnFrom(t: Thread, members: ReviewItem[], now: Date, waiting: OwnerWaiting[], owes: Owed[]): Turn {
209
+ const base = ((): 'yours' | 'agents' | 'done' => {
210
+ // a version, a question, a change, words asking the owner's verdict, an open ask's record, the owner's note on the owner's move
211
+ if (waiting.some((w) => w.what !== 'hold')) return 'yours'
212
+ if (owes.length > 0) return 'agents'
213
+ // an object that holds it open: the owner's move (a branch to merge) even once the owner's verdict closed the head; the owner's close
214
+ // released it
215
+ if (waiting.some((w) => w.what === 'hold')) return 'yours'
216
+ return 'done'
217
+ })()
218
+ const turn = turnAfterMoves(base, members)
219
+ return turn === 'yours' && asideUntilAt(t, now) !== null ? 'aside' : turn
220
+ }
221
+
222
+ /** the owner's turn passes to the agents while the owner's words or the owner's request for a lane are the newest move; a version an agent sends
223
+ * is a move of its own; any other turn stays */
224
+ export function turnAfterMoves<T extends Turn>(base: T, members: readonly ReviewItem[]): T | 'agents' {
225
+ if (base !== 'yours') return base
226
+ let latest: { at: string; move: Move } | null = null
227
+ for (const x of members) {
228
+ if (x.item.origin.by === 'agent' && (latest === null || x.item.created >= latest.at)) latest = { at: x.item.created, move: 'agent-answer' }
229
+ for (const m of x.thread) {
230
+ const move = messageMove(x, m)
231
+ if (AFTER_MOVE[move] !== 'none' && (latest === null || m.at >= latest.at)) latest = { at: m.at, move }
232
+ }
233
+ }
234
+ return latest !== null && AFTER_MOVE[latest.move] === 'agents' ? 'agents' : base
235
+ }
236
+
237
+ /** how the thread stands closed, null while open: its ask's state on an ask's thread, else its head's, with the act that
238
+ * closed it */
239
+ function closedOf(t: Thread): Closed | null {
240
+ const x = t.head
241
+ if (askItemOf(t) !== null) {
242
+ const a = askStateOf(t)
243
+ return a !== null && isClosedAskState(a.state) ? { at: a.at, by: 'ask', who: a.who, why: a.state } : null
244
+ }
245
+ const s = stateOf(x, false)
246
+ if (s.state !== 'closed') return null
247
+ const why = s.why ?? 'closed'
248
+ for (let i = x.thread.length - 1; i >= 0; i--) {
249
+ if (stateOf({ ...x, thread: x.thread.slice(0, i) }, false).state === 'closed') continue
250
+ const m = x.thread[i]!
251
+ return { at: m.at, by: partyOf(m.who) === 'owner' ? 'owner' : 'agent', who: m.who, why }
252
+ }
253
+ // closed from its start: the owner's own save, a version its kind's acts settle
254
+ return { at: x.item.created, by: 'owner', who: 'owner', why }
255
+ }
256
+
257
+ /** when a close moots what was asked before it: every close, whoever closed (a closed thread waits on the owner for nothing) */
258
+ const mootCut = (c: Closed | null): string | null => c?.at ?? null
259
+
260
+ /** every open object of the owner's turn, in the dock's order: the ask's own record, each open question, proposed change or
261
+ * message that asks the owner's verdict oldest first, the version that waits for the owner's verdict, the owner's note an agent asked about,
262
+ * an object of the owner's move that holds it open */
263
+ function waitingOf(t: Thread, head: boolean): OwnerWaiting[] {
264
+ const out: OwnerWaiting[] = []
265
+ const h = t.head.item
266
+ const ask = askStateOf(t)?.state
267
+ const facts = askFactsOf(t)
268
+ if (facts !== null && !isClosedAskState(ask)) out.push({ wait: askVerb(facts.kind), on: { kind: 'ask' }, id: h.id, what: 'ask', title: threadTitle(t) })
269
+ // a question with a row per thing waits as one, by its first row
270
+ const rows = new Set<string>()
271
+ const firstRow = (g: string): Message | undefined => membersOf(t).flatMap((x) => x.thread).find((y) => y.ask?.row?.group === g && y.ask.row.i === 0)
272
+ for (const m of [...openAsksOf(t), ...openItemVerdictsOf(t)].sort((a, b) => a.at.localeCompare(b.at))) {
273
+ const g = m.ask?.row?.group
274
+ if (g !== undefined && rows.has(g)) continue
275
+ if (g !== undefined) rows.add(g)
276
+ const id = `${m.on}/${g === undefined ? m.id : (firstRow(g)?.id ?? m.id)}`
277
+ const what = m.instructions ? 'steps' : m.propose ? 'change' : m.ask ? 'question' : 'words'
278
+ const step = m.step !== undefined ? { step: true as const } : {}
279
+ out.push(m.asksVerdict === true && m.ask === undefined && m.propose === undefined ? { wait: 'judge', on: verdictOn(m), id, what, ...step } : { wait: requestVerb(m), on: { type: requestType(m) }, id, what, ...(m.instructions ? { title: m.instructions.title } : {}), ...step })
280
+ }
281
+ if (head) out.push({ wait: 'judge', on: { kind: h.on ? h.on.slice(0, h.on.indexOf(':')) : h.subject.kind }, id: h.id, what: 'version', n: t.versions.length })
282
+ const notes = [...(h.origin.by === 'agent' ? [] : [t.head]), ...t.answers.filter((x) => t.joined.has(x.item.id))]
283
+ const note = notes.find((x) => moveOf(stateOf(x, false).state) === 'owner')
284
+ if (note !== undefined) out.push({ wait: 'answer', on: { type: 'note' }, id: note.item.id, what: 'note' })
285
+ const hold = heldOpen(membersOf(t)).find((x) => holdMoveOf(x) === 'owner')
286
+ if (hold !== undefined) out.push({ wait: 'do', on: { kind: hold.address.slice(0, hold.address.indexOf(':')) }, id: h.id, what: 'hold', title: hold.address })
287
+ return out
288
+ }
289
+
290
+ /** what the agents owe, oldest first. After an agent's close, only what came after it: the close answered the rest */
291
+ function owesOf(t: Thread, now: Date, closed: Closed | null, next: NextVersion | null): Owed[] {
292
+ const members = membersOf(t)
293
+ const out: Owed[] = []
294
+ // the owner's request for a lane waits on the orchestrator until an agent acts in the thread (review/lane-ask.ts)
295
+ const lane = laneAskOf(members)
296
+ if (lane !== null) out.push({ kind: 'lane-ask', at: lane.at, ask: lane })
297
+ const notes = [...(t.head.item.origin.by === 'agent' ? [] : [t.head]), ...t.answers.filter((x) => t.joined.has(x.item.id))]
298
+ for (const x of notes) if (moveOf(stateOf(x, false).state) === 'agents') out.push({ kind: 'note', id: x.item.id, at: x.item.created })
299
+ const word = owedWordOf(t)
300
+ if (word !== null) out.push(word)
301
+ const h = t.head
302
+ if (h.item.origin.by === 'agent') {
303
+ if (isOpening(h.item)) {
304
+ // opened with words: in work while the agent's latest update says so; a withdraw ends it until a newer update;
305
+ // the owner's close of an ask settles a line the machine wrote before it
306
+ const u = updatesOf(h).at(-1)
307
+ const w = itemWithdrawOf(h)
308
+ const ended = w !== undefined && (u === undefined || u.at <= w.at)
309
+ const settled = u !== undefined && byMachine(u) && closed?.by === 'ask' && closed.at >= u.at
310
+ if (u !== undefined && !ended && !settled && (u.update?.state === 'broken' || u.update?.state === 'better')) out.push({ kind: 'in-work', id: h.item.id, at: u.at, broken: openBrokenOf(h).at(-1) ?? null })
311
+ } else {
312
+ const r = reworkOf(h, false, now)
313
+ if (r !== null) out.push({ kind: 'rework', lane: r.lane, at: r.since, until: r.until })
314
+ const v = verdictOf(h)
315
+ if (v === null && inWork(h) && withdrawnOf(h) === undefined) out.push({ kind: 'in-work', id: h.item.id, at: updatesOf(h).at(-1)?.at ?? h.item.created, broken: openBrokenOf(h).at(-1) ?? null })
316
+ // the owner's OK with a note or rectangles: owed until an agent reads it (a bare one owes nothing)
317
+ if (v !== null && v.status === 'approved' && !v.seen && (v.comment.trim() !== '' || v.rects.length > 0)) out.push({ kind: 'approval-note', id: h.item.id, at: v.at })
318
+ if (v !== null && r === null && stateOf(h, false).state === 'claimed') out.push({ kind: OWED_OF[v.status] ?? 'redo', id: h.item.id, at: v.at, seen: v.seen })
319
+ }
320
+ }
321
+ if (next !== null) out.push({ kind: 'promise', at: next.at, next })
322
+ for (const x of heldOpen(members)) if (holdMoveOf(x) === 'agents') out.push({ kind: 'hold', at: x.at, address: x.address })
323
+ const owed = closed?.by === 'agent' ? out.filter((o) => o.at > closed.at) : out
324
+ return owed.sort((a, b) => a.at.localeCompare(b.at))
325
+ }
326
+
327
+ /** the owner's newest word that asks work (a tick inside an unfinished list is no word: review/thread-events.ts) with no agent
328
+ * answer since: unseen, or read by an agent with no act since that word (a version, a message, a close, a `working`;
329
+ * never a read or a take). An act before the read counts: an agent that acted, then marked it read, owes nothing */
330
+ function owedWordOf(t: Thread): Owed | null {
331
+ const members = membersOf(t)
332
+ // unseen first: every word of the owner's no agent marked seen that wakes one, the opening that raised a note aside
333
+ // the owner's reopen not read yet asks work too: it takes back what was done
334
+ const reopens = (x: ReviewItem): Message[] => {
335
+ const unread = new Set(toAcknowledge(x, 'agent'))
336
+ return x.thread.filter((m) => m.op === 'reopen' && partyOf(m.who) === 'owner' && unread.has(m.id))
337
+ }
338
+ const unseen = members.flatMap((x) => [...wakingUnread(x).filter((m) => m !== openingOf(x)), ...reopens(x)].map((m) => ({ x, m }))).reduce<{ x: ReviewItem; m: Message } | null>((a, b) => (a === null || b.m.at >= a.m.at ? b : a), null)
339
+ if (unseen !== null) return { kind: 'word', id: `${unseen.x.item.id}/${unseen.m.id}`, at: unseen.m.at, word: unseen.m, read: null }
340
+ const r = readWordOf(t)
341
+ return r === null ? null : { kind: 'word', id: `${r.on}/${r.word.id}`, at: r.word.at, word: r.word, read: { who: r.who, at: r.at } }
342
+ }
343
+
344
+ /** an agent wrote in it after he set it aside */
345
+ const movedSince = (members: readonly ReviewItem[]): boolean => {
346
+ const msgs = members.flatMap((x) => x.thread)
347
+ const set = msgs.filter((m) => m.snooze).map((m) => m.at).sort().at(-1) ?? ''
348
+ return msgs.some((m) => m.at > set && m.who !== 'owner' && m.op !== 'seen') || members.some((x) => x.item.created > set)
349
+ }
350
+
351
+ /** the newest message of any item (a read mark or a hand over moves nothing), else the head's time */
352
+ function updatedOf(t: Thread, members: readonly ReviewItem[]): string {
353
+ return members.reduce((u, x) => {
354
+ const m = x.thread.filter((y) => !handedOver(y) && y.op !== 'seen').at(-1)?.at ?? x.item.created
355
+ return m > u ? m : u
356
+ }, t.head.item.created)
357
+ }
358
+
359
+ /** everything in the thread validated, the row's quiet green: nothing is owed by anyone (its turn done) and the owner
360
+ * said yes to it: an OK, an « ok with a fix » whose fix is done, or the ask done. A no, a « not doing it », a withdrawn
361
+ * or replaced head, a thread closed by an agent alone is done, never validated */
362
+ export const validatedOf = (f: { turn: Turn; status: string; ask?: AskState }): boolean =>
363
+ f.turn === 'done' && (f.ask !== undefined ? f.ask === 'done' : f.status === 'approved' || f.status === 'approved-with-fix')
364
+
365
+ /** the thread's state as a person it is shared with reads it (wiki tools/shipkit/advisors.md, What the advisor sees):
366
+ * whose move and whether it is closed come from the real thread `real`; what waits, by the copy's own cell ids, from
367
+ * the copy's state `copy`. The owner's turn reads « waits for the owner » (aside) to them, unless he deferred the thread
368
+ * to them; when the copy's head is an older version (`headKept` false), nothing of it waits and its status is the
369
+ * thread's only once the thread is done */
370
+ export function personState(real: ThreadState, copy: ThreadState, o: { deferred: boolean; headKept: boolean }): ThreadState {
371
+ const turn: Turn = o.deferred && real.turn === 'aside' ? 'yours' : real.turn === 'yours' || real.turn === 'aside' ? 'aside' : real.turn
372
+ return {
373
+ ...copy,
374
+ turn,
375
+ closed: real.closed,
376
+ status: o.headKept ? copy.status : real.turn === 'done' ? real.status : 'pending',
377
+ headWaits: o.headKept && copy.headWaits,
378
+ waitsOwner: o.headKept ? copy.waitsOwner : copy.waitsOwner.filter((w) => w.what !== 'version'),
379
+ active: turn !== 'done',
380
+ validated: copy.validated && (o.headKept || real.turn === 'done'),
381
+ }
382
+ }
383
+
384
+ // ── the band: the state and the registry ──
385
+
386
+ export const BANDS = ['yours', 'aside', 'working', 'waiting', 'done'] as const
387
+ export type Band = (typeof BANDS)[number]
388
+
389
+ export const BAND_WORDS: Record<Band, string> = { yours: 'your turn', aside: 'set aside', working: 'an agent works on it', waiting: 'waiting for an agent', done: 'done' }
390
+
391
+ /** what the band reads of a thread's state */
392
+ export type BandFacts = Pick<ThreadState, 'turn' | 'holder' | 'working' | 'laneAsk' | 'next'>
393
+
394
+ const laneOf = (p: Parties, name: string, session: string | undefined) => p.lanes.find((l) => l.name === name && (session === undefined || l.session === session))
395
+
396
+ /** a live agent works the thread now: its `working` not ended, of a session or a lane still live; a live lane that holds
397
+ * it. A lane the registry cannot find has ended unless its watch lives. A session that only holds it hears, by its
398
+ * watch or at its next prompt, and works nothing: a session's watch lives for days */
399
+ export function worksNow(f: BandFacts, p: Parties, now = new Date()): boolean {
400
+ const h = f.holder
401
+ const w = f.working
402
+ if (w != null && now.getTime() - Date.parse(w.at) <= WORKING_FRESH_MS) {
403
+ if (w.who === 'agent') {
404
+ if (h?.session !== undefined && p.sessions.some((s) => s.id === h.session && s.live)) return true
405
+ } else {
406
+ const l = laneOf(p, w.who, h?.lane === w.who ? h.session : undefined)
407
+ if (l !== undefined && (l.live || l.watch)) return true
408
+ }
409
+ }
410
+ if (h?.lane === undefined) return false
411
+ const l = laneOf(p, h.lane, h.session)
412
+ return l !== undefined && (l.live || l.watch)
413
+ }
414
+
415
+ /** the band: the turn, an agent's move split by whether a live agent works it now (wiki tools/shipkit/threads-how-it-fits.md,
416
+ * The bands) */
417
+ export const bandOf = (f: BandFacts, p: Parties, now = new Date()): Band =>
418
+ f.turn !== 'agents' ? f.turn : (f.laneAsk != null && laneAskOwed(f.laneAsk, p)) || !worksNow(f, p, now) ? 'waiting' : 'working'
419
+
420
+ /** a `working` line past its time on the agents' move, as the owner's row says it (« said working 14 h ago, nothing since »);
421
+ * a promised version counts its own time; null while it counts or on any other turn */
422
+ export function staleWorkingOf(f: Pick<ThreadState, 'turn' | 'working' | 'next'>, now = new Date()): string | null {
423
+ if (f.turn !== 'agents') return null
424
+ if (f.next != null) return lateOf(f.next, now)
425
+ const w = f.working
426
+ if (w == null) return null
427
+ const age = now.getTime() - Date.parse(w.at)
428
+ return age > WORKING_FRESH_MS ? `${w.who === 'agent' ? '' : `${w.who} `}said working ${ageWords(age)} ago, nothing since` : null
429
+ }
430
+
431
+ /** a lane the registry knows live, or whose watch lives */
432
+ export const laneLives = (p: Parties, lane: string, session: string | undefined): boolean => p.lanes.some((l) => l.name === lane && (session === undefined || l.session === session) && (l.live || l.watch))
433
+
434
+ // ── words a row says of a state ──
435
+
436
+ /** an age as a row says it: « 12 min », « 14 h », « 3 days » */
437
+ export const ageWords = (ms: number): string => {
438
+ const min = Math.max(1, Math.round(ms / 60_000))
439
+ if (min < 60) return `${min} min`
440
+ const h = Math.round(min / 60)
441
+ return h < 48 ? `${h} h` : `${Math.round(h / 24)} days`
442
+ }
443
+
444
+ /** who an agent's act names, as a line says it: its lane, else « an agent » */
445
+ export const agentWords = (who: string): string => (who === 'agent' ? 'an agent' : who)
446
+
447
+ /** a time as a line says it: « 14:02 » today, else « Mon 30 Nov, 18:00 » */
448
+ export function whenWords(iso: string, now = new Date()): string {
449
+ const d = new Date(iso)
450
+ const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
451
+ if (d.toDateString() === now.toDateString()) return hm
452
+ return `${['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()]} ${d.getDate()} ${['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()]}, ${hm}`
453
+ }
454
+
455
+ /** a promised version past its time, as a line says it (« L382 promised v2 by 14:30, late 3 h »), null while it counts */
456
+ export function lateOf(n: Pick<NextVersion, 'who' | 'until' | 'n'>, now = new Date()): string | null {
457
+ const over = now.getTime() - Date.parse(n.until)
458
+ return over > 0 ? `${agentWords(n.who)} promised v${n.n} by ${whenWords(n.until, now)}, late ${ageWords(over)}` : null
459
+ }
460
+
461
+ /** the words a « waiting for an agent » head says: who takes one */
462
+ export const waitingWords = (repo: string): string => `nobody works on these now: a session in ${repo} takes one with sk thread take <address>`
463
+
464
+ // ── what waits on the owner: the verbs ──
465
+
466
+ export const WAITS = ['judge', 'answer', 'do', 'agents', 'done'] as const
467
+ export type Wait = (typeof WAITS)[number]
468
+ /** the verbs of the owner's turn */
469
+ export const OWNER_WAITS = ['judge', 'answer', 'do'] as const satisfies readonly Wait[]
470
+ export type OwnerWait = (typeof OWNER_WAITS)[number]
471
+ export const isOwnerWait = (w: string): w is OwnerWait => (OWNER_WAITS as readonly string[]).includes(w)
472
+
473
+ /** a url's `waits=judge,answer` (the inbox's key): the owner's verbs it names, null when it names none */
474
+ export function waitsOfParam(v: string | null): OwnerWait[] | null {
475
+ const ws = OWNER_WAITS.filter((w) => (v ?? '').split(',').includes(w))
476
+ return ws.length > 0 ? ws : null
477
+ }
478
+
479
+ /** the one matcher of every verbs filter (the threads page, the inbox): none picked lists all, else a thread whose
480
+ * verbs hold one picked */
481
+ export const waitsMatch = (sel: readonly OwnerWait[] | null, verbs: readonly string[]): boolean => sel === null || verbs.some((v) => (sel as readonly string[]).includes(v))
482
+
483
+ const DO_ANSWERS: ReadonlySet<string> = new Set(['checklist', 'url', 'secret', 'file'])
484
+ const DO_ASKS: ReadonlySet<string> = new Set(['action', 'purchase', 'credential'])
485
+
486
+ /** an ask's own record: an action, a purchase or a credential is done, a decision or an answer is answered */
487
+ export const askVerb = (kind: string): OwnerWait => (DO_ASKS.has(kind) ? 'do' : 'answer')
488
+
489
+ /** the verb of one open request in the dock: a proposed change is judged, a question that takes a checklist, a url, a
490
+ * secret or a file is done, any other question is answered */
491
+ export const requestVerb = (m: Pick<Message, 'propose' | 'ask'>): OwnerWait => (m.propose !== undefined ? 'judge' : DO_ANSWERS.has(kindOfAsk(m as Message)) ? 'do' : 'answer')
492
+
493
+ /** what a thread waits on from the owner first: the type of message, or the kind of the object, a row draws as its icon */
494
+ export type WaitsOn = { type: MessageType } | { kind: string }
495
+
496
+ /** an open request's type: a proposed change, a secret field, a checklist, any other question */
497
+ const requestType = (m: Message): MessageType => (m.propose !== undefined ? 'change' : kindOfAsk(m) === 'secret' ? 'secret' : kindOfAsk(m) === 'checklist' ? 'checklist' : 'question')
498
+
499
+ /** a message that asks the owner's verdict: the object it links when it links one (a reflection, a draft), else its words */
500
+ const verdictOn = (m: Message): WaitsOn => {
501
+ const a = m.about?.[0]
502
+ return a !== undefined && a.includes(':') ? { kind: a.slice(0, a.indexOf(':')) } : { type: 'message' }
503
+ }
504
+
505
+ // ── the parts the state is read from ──
506
+
507
+ /** an agent's promise of the thread's next version (`sk thread working <address> "…" --next <by>`): who, when said, by
508
+ * when, the number it will take. It stands until a version comes after it or a close; past `until` it is late, never
509
+ * gone, so a promise not kept stays in sight */
510
+ export interface NextVersion {
511
+ who: string
512
+ session?: string
513
+ at: string
514
+ until: string
515
+ n: number
516
+ line: string
517
+ }
518
+
519
+ function promiseOf(t: Thread, closed: Closed | null): NextVersion | null {
520
+ let best: Message | null = null
521
+ for (const x of membersOf(t)) for (const m of x.thread) if (m.next !== undefined && m.op === 'working' && partyOf(m.who) === 'agent' && (best === null || m.at >= best.at)) best = m
522
+ if (best === null) return null
523
+ const at = best.at
524
+ if (membersOf(t).some((x) => x.item.origin.by === 'agent' && x.item.created > at)) return null
525
+ if (closed !== null && closed.at >= at) return null
526
+ return { who: best.who, ...(best.session ? { session: best.session } : {}), at, until: best.next!.until, n: t.versions.length + 1, line: best.note ?? '' }
527
+ }
528
+
529
+ /** a head waits for the owner's verdict: an agent's version, none yet, not left with his « no answer », not withdrawn, not
530
+ * a draft, not closed by its agent */
531
+ export const waits = (x: ReviewItem): boolean =>
532
+ x.item.origin.by === 'agent' && (!asksNoVerdict(x.item) || x.item.asksVerdict === true) && !inWork(x) && verdictOf(x) === null && leftUnansweredOf(x) === null && withdrawnOf(x) === undefined && closerOf(x) === null
533
+
534
+ /** the agent that closed this version with its thread (`sk thread close`), while that close stands: null when none did,
535
+ * or when a verdict or a reopen came after it */
536
+ export function closerOf(x: ReviewItem): string | null {
537
+ for (let i = x.thread.length - 1; i >= 0; i--) {
538
+ const m = x.thread[i]!
539
+ if (m.closes !== undefined && m.op === 'done') return m.who
540
+ if (m.op !== undefined && m.op !== 'seen' && m.op !== 'working' && m.op !== 'take') return null
541
+ if (m.verdict !== undefined) return null
542
+ }
543
+ return null
544
+ }
545
+
546
+ /** what the list says of a version: the owner's verdict, else withdrawn, a draft, closed by its agent, replaced, or waiting for
547
+ * the owner; a report a version answers shows the bug's status, its version's at the newest version */
548
+ export function statusOf(x: ReviewItem, items: readonly ReviewItem[]): ShownStatus {
549
+ if (x.item.origin.by !== 'agent') {
550
+ let item = answererOf(x.item.id, items)
551
+ const seen = new Set<string>()
552
+ for (let next = item; next && !seen.has(next.item.id); next = supersederOf(next.item.id, items)) {
553
+ seen.add(next.item.id)
554
+ item = next
555
+ }
556
+ if (item) return statusOf(item, items)
557
+ const st = stateOf(x, false)
558
+ if (st.state !== 'closed') return 'raised'
559
+ return st.why === 'wontfix' || st.why === 'dropped' ? 'wontfix' : st.why === 'rated' ? 'rated' : 'fixed'
560
+ }
561
+ const v = verdictOf(x)
562
+ if (v) return v.status
563
+ if (leftUnansweredOf(x) !== null) return 'no-answer'
564
+ if (withdrawnOf(x) !== undefined) return 'withdrawn'
565
+ if (inWork(x)) return 'wip'
566
+ if (closerOf(x) !== null) return 'closed'
567
+ if (asksNoVerdict(x.item)) return 'fixed'
568
+ return supersederOf(x.item.id, items) ? 'superseded' : 'pending'
569
+ }
570
+
571
+ /** the newest ask state written in the thread with its time and who wrote it, null on a thread that is no ask's or never
572
+ * said one */
573
+ export function askStateOf(t: Thread): (NonNullable<Message['askState']> & { at: string; who: string }) | null {
574
+ let last: (NonNullable<Message['askState']> & { at: string; who: string }) | null = null
575
+ for (const x of membersOf(t)) for (const m of x.thread) if (m.askState && (last === null || m.at >= last.at)) last = { ...m.askState, at: m.at, who: m.who }
576
+ return last
577
+ }
578
+
579
+ /** when a thread set aside comes back, null when it is not set aside now: the newest « set aside » still ahead, unless
580
+ * he acted on the thread after it, or an agent sent an urgent message after it */
581
+ function asideUntilAt(t: Thread, now: Date): string | null {
582
+ let snooze: { at: string; until: string | null } | null = null
583
+ const msgs = membersOf(t).flatMap((x) => x.thread)
584
+ for (const m of msgs) if (m.snooze && (snooze === null || m.at >= snooze.at)) snooze = { at: m.at, until: m.snooze.until }
585
+ if (snooze === null || snooze.until === null || Date.parse(snooze.until) <= now.getTime()) return null
586
+ const after = msgs.filter((m) => m.at > snooze!.at)
587
+ if (after.some((m) => m.urgent === true && partyOf(m.who) === 'agent')) return null
588
+ if (after.some((m) => partyOf(m.who) === 'owner' && m.op !== 'seen' && m.snooze === undefined && m.mute === undefined && m.carried === undefined)) return null
589
+ return snooze.until
590
+ }
591
+
592
+ /** each question and proposed change of the agents that no message of the owner's answers yet (`re` names it) and no newer
593
+ * object supersedes (review/supersede.ts), oldest first; the close moots the ones before it, never one an agent asks
594
+ * after it */
595
+ export function openAsksOf(t: Thread): (Message & { on: string })[] {
596
+ const members = membersOf(t)
597
+ const gone = replacersOf(members)
598
+ const out = members.flatMap((x) => x.thread.filter((m) => partyOf(m.who) === 'agent' && !gone.has(m.id) && (m.propose !== undefined ? proposeOpen(x.thread, m) : askOpen(x.thread, m))).map((m) => ({ ...m, on: x.item.id })))
599
+ return afterClose(t, out).sort((a, b) => a.at.localeCompare(b.at))
600
+ }
601
+
602
+ /** each message of the thread that asks the owner's verdict and has none, oldest first, the ones before the close moot */
603
+ export function openItemVerdictsOf(t: Thread): (Message & { on: string })[] {
604
+ const members = membersOf(t)
605
+ return afterClose(t, openVerdictAsks(members, new Set(replacersOf(members).keys())))
606
+ }
607
+
608
+ const afterClose = <M extends Pick<Message, 'at'>>(t: Thread, ms: M[]): M[] => {
609
+ if (ms.length === 0) return ms
610
+ const cut = mootCut(closedOf(t))
611
+ return cut === null ? ms : ms.filter((m) => m.at > cut)
612
+ }
613
+
614
+ /** a request written before the close is moot: it waits on nobody, its cell reads « closed, not answered »; null while open */
615
+ export const mootAt = (s: Pick<ThreadState, 'closed'>): string | null => mootCut(s.closed ?? null)
616
+
617
+ /** the lane that reworks the thread on its claim now, null when none does */
618
+ export const reworkingOf = (s: Pick<ThreadState, 'owes'>): { lane: string; since: string; until: number } | null => {
619
+ const r = s.owes.find((o) => o.kind === 'rework')
620
+ return r?.kind === 'rework' ? { lane: r.lane, since: r.at, until: r.until } : null
621
+ }
622
+
623
+ export const isMoot = (s: Pick<ThreadState, 'closed'>, m: Pick<Message, 'at'>): boolean => {
624
+ const cut = mootCut(s.closed ?? null)
625
+ return cut !== null && m.at <= cut
626
+ }
627
+
628
+ /** the owner's newest word that asks an agent for work (a tick inside an unfinished list is no word); the words that raised a
629
+ * note he closed are answered by the close */
630
+ function newestAskingWord(members: readonly ReviewItem[]): { x: ReviewItem; m: Message } | null {
631
+ let his: { x: ReviewItem; m: Message } | null = null
632
+ for (const x of members)
633
+ for (const m of x.thread) {
634
+ if (partyOf(m.who) !== 'owner' || m.op === 'seen' || m.laneAsk !== undefined || wakeOf(x, m) === 'trace' || !asksWork(x, m)) continue
635
+ if (m === openingOf(x) && stateOf(x, false).state === 'closed') continue
636
+ if (his === null || m.at >= his.m.at) his = { x, m }
637
+ }
638
+ return his
639
+ }
640
+
641
+ /** the owner's newest word that asks something, read by an agent, with no agent act in the thread since that word: still owed */
642
+ function readWordOf(t: Thread): { who: string; at: string; word: Message; on: string } | null {
643
+ const members = membersOf(t)
644
+ const all = members.flatMap((x) => x.thread.map((m) => ({ x, m })))
645
+ const his = newestAskingWord(members)
646
+ if (his === null) return null
647
+ const read = all.filter(({ m }) => m.op === 'seen' && partyOf(m.who) === 'agent' && m.of?.includes(his.m.id)).reduce<Message | null>((a, { m }) => (a === null || m.at >= a.at ? m : a), null)
648
+ if (read === null) return null
649
+ // a take by a lane (an assign, a lane's own take) puts a named agent on the owner's word; a session's bare take does not
650
+ const act = (m: Message): boolean => m.op !== 'seen' && m.rename === undefined && (m.op !== 'take' || m.who !== 'agent')
651
+ const acted = all.some(({ m }) => partyOf(m.who) === 'agent' && act(m) && m.at >= his.m.at) || members.some((x) => x.item.origin.by === 'agent' && x.item.created >= his.m.at)
652
+ return acted ? null : { who: read.who, at: read.at, word: his.m, on: his.x.item.id }
653
+ }
654
+
655
+ /** an open ask's thread is counted as its ask, once (the asks badge, its needs pings); a closed ask is counted nowhere */
656
+ export const countedAsItsAsk = (t: Thread): boolean => askItemOf(t) !== null && !isClosedAskState(askStateOf(t)?.state)
657
+
658
+ /** the active pending heads first in the order they were sent, then every other thread, newest first */
659
+ export function orderedThreads(items: readonly ReviewItem[]): Thread[] {
660
+ const all = threadsOf(items)
661
+ const first = (x: ReviewItem): boolean => waits(x) || (x.item.origin.by === 'agent' && inWork(x))
662
+ const pending = all.filter((t) => first(t.head)).sort((a, b) => oldest(a.head, b.head))
663
+ const rest = all.filter((t) => !first(t.head)).sort((a, b) => newest(a.head, b.head))
664
+ return [...pending, ...rest]
665
+ }
666
+
667
+ const STOP = new Set(['a', 'an', 'the', 'of', 'on', 'in', 'at', 'to', 'and', 'with', 'by', 'de', 'la', 'le', 'les', 'du', 'des', 'au', 'aux', 'l', 'd', 'et', 'en'])
668
+
669
+ /** two titles share most of their words (Dice over the words, stop words aside): a new version sent without --supersedes */
670
+ export function closeTitles(a: string, b: string): boolean {
671
+ const wa = new Set(slugWords(a).filter((w) => !STOP.has(w)))
672
+ const wb = new Set(slugWords(b).filter((w) => !STOP.has(w)))
673
+ if (wa.size === 0 || wb.size === 0) return false
674
+ const common = [...wa].filter((w) => wb.has(w)).length
675
+ return (2 * common) / (wa.size + wb.size) >= 0.6
676
+ }
677
+
678
+ /** the head of an active thread that already covers this subject, null when none. Subjects first: two that each name
679
+ * one thing are one subject exactly when they name the same; else the same topic and a subject its kind calls near;
680
+ * else a close title */
681
+ export function coveringHead(item: { title: string; topic?: string; subject: Subject }, items: readonly ReviewItem[], spec: Spec = NO_SPEC): { head: ReviewItem; by: 'subject' | 'near' | 'title' } | null {
682
+ const key = subjectKey(item.subject, spec)
683
+ const comparable = threadsOf(items)
684
+ .filter((t) => threadState(t).active)
685
+ .filter((t) => {
686
+ const k = subjectKey(t.head.item.subject, spec)
687
+ return key === null || k === null || k === key
688
+ })
689
+ const same = key === null ? undefined : comparable.find((t) => subjectKey(t.head.item.subject, spec) === key)
690
+ if (same) return { head: same.head, by: 'subject' }
691
+ const near = spec.kinds[item.subject.kind]?.near
692
+ const close = near ? comparable.find((t) => t.head.item.topic === item.topic && t.head.item.subject.kind === item.subject.kind && near(item.subject, t.head.item.subject)) : undefined
693
+ if (close) return { head: close.head, by: 'near' }
694
+ const title = comparable.find((t) => closeTitles(item.title, t.head.item.title))
695
+ return title ? { head: title.head, by: 'title' } : null
696
+ }
697
+
698
+ /** what moved since the owner's last act in the store (a verdict, a word, a note, an answer; never a read: the hub marks what he
699
+ * sees read a moment after the page opens, which would empty the line): the threads an agent wrote in since, and how
700
+ * many of them are the owner's turn. Null before the owner's first act. The line he reads on waking */
701
+ export function sinceHeLeft(items: readonly ReviewItem[], now = new Date()): { at: string; moved: number; yours: number } | null {
702
+ let at = ''
703
+ for (const x of items) {
704
+ if (x.item.origin.by === 'owner' && x.item.created > at) at = x.item.created
705
+ for (const m of x.thread) if (m.who === 'owner' && m.op !== 'seen' && m.at > at) at = m.at
706
+ }
707
+ if (at === '') return null
708
+ const moved = threadsOf(items).filter((t) => membersOf(t).some((x) => (x.item.origin.by === 'agent' && x.item.created > at) || x.thread.some((m) => partyOf(m.who) === 'agent' && m.op !== 'seen' && !handedOver(m) && m.at > at)))
709
+ return { at, moved: moved.length, yours: moved.filter((t) => threadState(t, now).turn === 'yours').length }
710
+ }
711
+
712
+ /** the owner's notes of a thread still open, oldest first: its head when he raised it, and the notes that joined by their
713
+ * address alone */
714
+ export const openNotesOf = (t: Thread): ReviewItem[] =>
715
+ [...(t.head.item.origin.by === 'agent' ? [] : [t.head]), ...t.answers.filter((x) => t.joined.has(x.item.id))].filter((x) => stateOf(x, false).state !== 'closed').sort(oldest)
716
+
717
+ /** the item words by address answer (`sk thread reply <address>`): the owner's newest open note, the one he waits on, else
718
+ * the thread's head */
719
+ export const replyTargetOf = (t: Thread): string => (openNotesOf(t).at(-1) ?? t.head).item.id
720
+
721
+ /** the owner's newest word that asks something with no agent answer since: a version, a reply, an update, a question, a
722
+ * change, a close; a `working`, a read, a take, a hand-over answer nothing (band.ts AFTER_MOVE). Null when answered */
723
+ export function unansweredWord(t: Thread): Message | null {
724
+ const members = membersOf(t)
725
+ const all = members.flatMap((x) => x.thread.map((m) => ({ x, m })))
726
+ const his = newestAskingWord(members)
727
+ if (his === null) return null
728
+ const answered = all.some(({ x, m }) => m.at >= his.m.at && partyOf(m.who) === 'agent' && !byMachine(m) && messageMove(x, m) === 'agent-answer') || members.some((x) => x.item.origin.by === 'agent' && x.item.created >= his.m.at)
729
+ return answered ? null : his.m
730
+ }
731
+
732
+ /** what « it is fixed » does on a thread (`sk thread fixed`): `asked` a note of the owner, by its id, closes it; else the owner's one open note in
733
+ * the thread closes (two or more are named, one picked by its id); else the newest version he answered « ok with a fix »
734
+ * closes (done), and one he rejected or that is in work asks the owner's verdict again (an update `fixed`) */
735
+ export function fixedPlan(t: Thread, asked: ReviewItem, o: { byAddress?: boolean } = {}): { op: 'fixed' | 'done' | 'update'; id: string } | { error: string } {
736
+ // an address names the thread, never its head note: a closed note heading it stands for nothing
737
+ if (asked.item.origin.by !== 'agent' && !o.byAddress) return { op: 'fixed', id: asked.item.id }
738
+ const notes = openNotesOf(t)
739
+ if (notes.length === 1) return { op: 'fixed', id: notes[0]!.item.id }
740
+ if (notes.length > 1) return { error: `${notes.length} open notes of his in this thread: sk thread fixed <id> "<what was done>" on the one you fixed: ${notes.map((x) => `${x.item.id} "${x.item.title}"`).join('; ')}` }
741
+ const h = t.head
742
+ const st = stateOf(h, false)
743
+ // a fix or the agent's own call is done, nothing more to judge; a rework or a rethink asks the owner's verdict again
744
+ const v = verdictOf(h)?.status
745
+ if (st.state === 'claimed' && (v === 'approved-with-fix' || v === 'your-call')) return { op: 'done', id: h.item.id }
746
+ if (st.state === 'claimed' || st.state === 'draft') return { op: 'update', id: h.item.id }
747
+ if (st.state === 'asks') return { error: `${h.item.id} waits on the verdict of the owner already: nothing to say fixed` }
748
+ return { error: `${h.item.id} is closed already (${st.why ?? 'closed'}): nothing to say fixed` }
749
+ }
750
+
751
+ // ── the reader's cut at the newest accepted recap ──
752
+
753
+ /** where a reader of the thread starts: the newest recap the owner accepted; `hidden` says what before it folds away (an
754
+ * item by its id with `m` null, else one of its messages) */
755
+ export interface RecapCut {
756
+ recap: RecapRef
757
+ hidden: (item: string, m: Pick<Message, 'id' | 'at'> | null) => boolean
758
+ }
759
+
760
+ /** the cut at the newest accepted recap, null with none (until the owner's ok the thread reads whole). Before it, what
761
+ * still waits on the owner or is owed stays in sight: each object of the owner's turn, everything the agents owe, the
762
+ * owner's words no agent read. A recap never hides an open item */
763
+ export function recapCut(t: Thread, s: ThreadState = threadState(t)): RecapCut | null {
764
+ const recap = s.recap?.accepted ?? null
765
+ if (recap === null) return null
766
+ const keeps = new Set<string>()
767
+ const keep = (id: string): void => {
768
+ keeps.add(id)
769
+ keeps.add(id.split('/').at(-1)!)
770
+ }
771
+ for (const w of s.waitsOwner) keep(w.id)
772
+ for (const o of [...owesOf(t, new Date(), s.closed, s.next), ...s.owes]) if ('id' in o) keep(o.id)
773
+ for (const x of membersOf(t)) for (const m of wakingUnread(x)) keeps.add(m.id)
774
+ for (const n of openNotesOf(t)) keeps.add(n.item.id)
775
+ return { recap, hidden: (item, m) => (m === null ? !keeps.has(item) && membersOf(t).some((x) => x.item.id === item && x.item.created < recap.at) : m.id !== recap.id && m.at < recap.at && !keeps.has(m.id)) }
776
+ }
777
+
778
+ // ── the guards on a thread's state ──
779
+
780
+ /** why an agent may not close the conversation (`sk thread close`), null when it may: an ask's thread closes by its ask;
781
+ * a closed one is closed already; anything waiting on the owner keeps it open (a question, a change, words asking the owner's
782
+ * verdict, a version with media to judge, a hold of the owner's move). A version of words that waits needs no verdict once
783
+ * closed, so it lets the close through */
784
+ export function agentCloseRefusal(t: Thread, now = new Date()): string | null {
785
+ const s = threadState(t, now)
786
+ if (s.ask !== null) return `${t.head.item.id} is an ask's thread: it closes by its ask (sk asks done <ask> "<what was done>")`
787
+ if (s.closed !== null) return `${t.head.item.id} is closed already (${s.closed.why})`
788
+ const media = (x: ReviewItem): boolean => x.item.views.length > 0 || x.item.trailer !== undefined || x.item.draft !== undefined || x.item.states !== undefined
789
+ const pending = t.versions.filter((x) => x.item.origin.by === 'agent' && statusOf(x, membersOf(t)) === 'pending' && media(x))
790
+ const waits = [
791
+ ...s.waitsOwner.flatMap((w) => (w.what === 'question' || w.what === 'steps' ? [`the question ${w.id.split('/').at(-1)}`] : w.what === 'change' ? [`the change ${w.id.split('/').at(-1)}`] : w.what === 'words' ? [`the words asking a verdict ${w.id.split('/').at(-1)}`] : w.what === 'hold' ? [`the hold ${w.title ?? ''}`] : [])),
792
+ ...pending.map((x) => `the version ${x.item.id}, a change to judge`),
793
+ ]
794
+ return waits.length === 0 ? null : `${waits.join(', ')} still wait${waits.length > 1 ? '' : 's'} on the owner: withdraw what was posted by mistake (sk thread withdraw <id> --why "<why>"), else wait for the answer, then close`
795
+ }
796
+
797
+ /** why he may not set the thread aside, null when he may: only a thread of the owner's turn (or set aside already) is */
798
+ export const asideRefusal = (s: Pick<ThreadState, 'turn'>): string | null => (s.turn === 'yours' || s.turn === 'aside' ? null : 'only a thread of your turn is set aside: this one waits on an agent')