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