rvlib-shipkit 2.27.0 → 2.28.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 (338) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/hooks.ts +10 -3
  4. package/src/agent-time/live.ts +11 -5
  5. package/src/agent-time/registry.ts +289 -0
  6. package/src/agent-time/store.ts +2 -2
  7. package/src/annex/born.ts +2 -2
  8. package/src/annex/offload.ts +12 -11
  9. package/src/asks/ask-after.ts +6 -2
  10. package/src/asks/ask-bar-fold.ts +57 -0
  11. package/src/asks/ask-migrate.ts +280 -0
  12. package/src/asks/ask-steps-fold.ts +166 -0
  13. package/src/asks/ask-store.ts +586 -0
  14. package/src/assets/kits/identity-kit.ts +106 -38
  15. package/src/assets/kits/poster-thumbnail.ts +282 -0
  16. package/src/checks/SK003-claude-md-shape.check.ts +92 -25
  17. package/src/checks/SK004-gitignore-policy.check.ts +8 -4
  18. package/src/checks/SK013-one-way-in-policy.check.ts +10 -0
  19. package/src/checks/SK026-asks-autoclose.check.ts +9 -23
  20. package/src/checks/SK038-speaks-as.check.ts +3 -3
  21. package/src/checks/SK042-post-kinds.check.ts +26 -24
  22. package/src/checks/SK049-thread-answers-hook.check.ts +81 -0
  23. package/src/checks/SK050-retired-commands.check.ts +127 -0
  24. package/src/cli/cmd_Asks.ts +204 -53
  25. package/src/cli/cmd_Backup.ts +151 -8
  26. package/src/cli/cmd_Calls.ts +1 -0
  27. package/src/cli/cmd_Commands.ts +140 -34
  28. package/src/cli/cmd_Contracts.ts +1 -0
  29. package/src/cli/cmd_Keys.ts +1 -0
  30. package/src/cli/cmd_Lanes.ts +15 -4
  31. package/src/cli/cmd_Messages.ts +152 -1
  32. package/src/cli/cmd_Needs.ts +1 -0
  33. package/src/cli/cmd_Review.ts +931 -229
  34. package/src/cli/cmd_Secret.ts +255 -34
  35. package/src/cli/cmd_Social.ts +36 -33
  36. package/src/cli/cmd_SocialDrafts.ts +235 -0
  37. package/src/cli/cmd_Sound.ts +22 -1
  38. package/src/cli/cmd_Start.ts +3 -2
  39. package/src/cli/cmd_ThreadHolds.ts +34 -0
  40. package/src/cli/cmd_ThreadKinds.ts +146 -0
  41. package/src/cli/cmd_ThreadReflect.ts +83 -0
  42. package/src/cli/cmd_ThreadSyncNeeds.ts +62 -0
  43. package/src/cli/cmd_Vault.ts +1 -1
  44. package/src/cli/cmd_When.ts +1 -0
  45. package/src/cli/family-help.ts +2 -2
  46. package/src/cli/family-pages.ts +1 -1
  47. package/src/cli/kit/builtins.ts +1 -0
  48. package/src/cli/kit/verb.ts +6 -2
  49. package/src/cli/registry.ts +21 -2
  50. package/src/cli.ts +5 -2
  51. package/src/collections/actions.ts +25 -74
  52. package/src/collections/collection-types.ts +9 -5
  53. package/src/collections/md-body.ts +5 -3
  54. package/src/collections/pings.ts +13 -6
  55. package/src/collections/providers.ts +53 -61
  56. package/src/collections/reflections.ts +9 -4
  57. package/src/core/discover-checks.ts +18 -3
  58. package/src/core/git.ts +31 -0
  59. package/src/core/house-layout.ts +17 -0
  60. package/src/core/layout.ts +10 -5
  61. package/src/core/locked-write.ts +4 -1
  62. package/src/core/machine-db.ts +5 -3
  63. package/src/core/migrate-layout.ts +8 -10
  64. package/src/home/activity.ts +8 -15
  65. package/src/home/daemon-jobs.ts +13 -1
  66. package/src/home/home-paths.ts +6 -3
  67. package/src/home/home-routes.ts +8 -0
  68. package/src/home/inbox-shape.ts +233 -100
  69. package/src/home/inbox.ts +26 -71
  70. package/src/home/machine-fold.ts +10 -15
  71. package/src/home/machine-host.ts +19 -1
  72. package/src/home/other-macs.ts +2 -2
  73. package/src/home/serve-web.ts +6 -5
  74. package/src/home/space-page.ts +1 -1
  75. package/src/home/vault-page.ts +51 -17
  76. package/src/home/vault-words.ts +2 -2
  77. package/src/hooks/one-way-in-guard.ts +24 -2
  78. package/src/hq/files-send.ts +27 -28
  79. package/src/hq/hq-db.ts +4 -1
  80. package/src/hq/hq-local.ts +37 -4
  81. package/src/hq/hq-routes.ts +10 -2
  82. package/src/hq/hq-store.ts +6 -2
  83. package/src/hq/kinds/ask.ts +6 -6
  84. package/src/hq/outbox.ts +5 -3
  85. package/src/hq/replica.ts +1 -2
  86. package/src/hq/vault-route.ts +112 -0
  87. package/src/identities/collection.ts +2 -2
  88. package/src/identities/identities.ts +9 -8
  89. package/src/identities/machine-route.ts +8 -3
  90. package/src/ledger/db.ts +8 -1
  91. package/src/media-store/backup/daemon.ts +48 -8
  92. package/src/media-store/backup/keys.ts +1 -1
  93. package/src/media-store/backup/manifest.ts +20 -2
  94. package/src/media-store/backup/prune.ts +365 -0
  95. package/src/media-store/backup/retention.ts +122 -0
  96. package/src/media-store/backup/run.ts +14 -8
  97. package/src/media-store/backup/sources.ts +18 -17
  98. package/src/media-store/backup/thread-copy.ts +340 -0
  99. package/src/media-store/copy/config.ts +3 -4
  100. package/src/media-store/copy/store.ts +2 -2
  101. package/src/media-store/db.ts +2 -2
  102. package/src/media-store/forget.ts +118 -0
  103. package/src/media-store/purge.ts +3 -2
  104. package/src/media-store/space-listing.ts +20 -4
  105. package/src/media-store/space.ts +6 -5
  106. package/src/messages/guard.ts +49 -0
  107. package/src/messages/model.ts +1 -1
  108. package/src/messages/objects.ts +201 -0
  109. package/src/messages/routes.ts +2 -2
  110. package/src/messages/score.ts +1 -1
  111. package/src/messages/write.ts +285 -0
  112. package/src/pages/frame-client.ts +181 -4
  113. package/src/reflections/reflections-queue.ts +1 -1
  114. package/src/release/gate-checkout.ts +2 -1
  115. package/src/release/git-facts.ts +3 -2
  116. package/src/release/public-clean.ts +3 -2
  117. package/src/repo-config.ts +40 -18
  118. package/src/review/anim.ts +1 -1
  119. package/src/review/answer-kinds.ts +131 -0
  120. package/src/review/band.ts +53 -0
  121. package/src/review/branch-hold.ts +84 -0
  122. package/src/review/card-db.ts +16 -6
  123. package/src/review/card-rows.ts +4 -3
  124. package/src/review/cells.ts +297 -65
  125. package/src/review/close.ts +92 -0
  126. package/src/review/draft-card.ts +8 -16
  127. package/src/review/draft-model.ts +2 -2
  128. package/src/review/events.ts +171 -0
  129. package/src/review/format.ts +128 -14
  130. package/src/review/glyphs.ts +63 -0
  131. package/src/review/gone.ts +1 -1
  132. package/src/review/holds-sync.ts +62 -0
  133. package/src/review/holds.ts +85 -0
  134. package/src/review/house-kind-defs.ts +41 -0
  135. package/src/review/inbox-hook.ts +22 -9
  136. package/src/review/inbox-read.ts +201 -0
  137. package/src/review/instructions.ts +199 -0
  138. package/src/review/kind-apply.ts +61 -0
  139. package/src/review/kind-catalog.ts +96 -0
  140. package/src/review/kinds.ts +278 -0
  141. package/src/review/lane-ask.ts +109 -0
  142. package/src/review/model.ts +396 -86
  143. package/src/review/move.ts +3 -3
  144. package/src/review/need-address.ts +15 -0
  145. package/src/review/need-threads.ts +93 -0
  146. package/src/review/object-card.ts +48 -0
  147. package/src/review/object-read.ts +31 -0
  148. package/src/review/owner-verdict.ts +36 -0
  149. package/src/review/parties.ts +182 -0
  150. package/src/review/previews.ts +3 -1
  151. package/src/review/projections.ts +235 -0
  152. package/src/review/referring.ts +54 -0
  153. package/src/review/reflection-object.ts +195 -0
  154. package/src/review/routes.ts +137 -32
  155. package/src/review/secret-route.ts +80 -0
  156. package/src/review/snooze.ts +38 -0
  157. package/src/review/stage-card.ts +4 -4
  158. package/src/review/store.ts +366 -85
  159. package/src/review/supersede.ts +116 -0
  160. package/src/review/take-back.ts +52 -0
  161. package/src/review/thread-fold.ts +20 -7
  162. package/src/review/threads.ts +236 -39
  163. package/src/review/traces.ts +218 -0
  164. package/src/review/trailer-card.ts +2 -2
  165. package/src/review/unit.ts +71 -5
  166. package/src/review/verdict-items.ts +73 -0
  167. package/src/review/verdict-write.ts +15 -0
  168. package/src/review/wait.ts +85 -0
  169. package/src/review/watchers.ts +22 -9
  170. package/src/scaffold/files/claude-settings-local.json +2 -0
  171. package/src/secrets/archive-mark.ts +52 -0
  172. package/src/secrets/archive.ts +83 -0
  173. package/src/secrets/copy.ts +14 -14
  174. package/src/secrets/keychain-write.ts +48 -0
  175. package/src/secrets/keychain.ts +8 -5
  176. package/src/secrets/lapse-mark.ts +33 -0
  177. package/src/secrets/lapse.ts +60 -0
  178. package/src/secrets/list.ts +16 -22
  179. package/src/secrets/manager.ts +31 -16
  180. package/src/secrets/read.ts +161 -33
  181. package/src/secrets/tail.ts +31 -0
  182. package/src/serve/hub-app/asks-page.tsx +2 -1
  183. package/src/serve/hub-app/auto-text.tsx +14 -6
  184. package/src/serve/hub-app/benign-errors.ts +15 -1
  185. package/src/serve/hub-app/card-head.tsx +49 -0
  186. package/src/serve/hub-app/check-view.tsx +3 -2
  187. package/src/serve/hub-app/code-copy.ts +35 -0
  188. package/src/serve/hub-app/col-card.tsx +31 -40
  189. package/src/serve/hub-app/col-list-page.tsx +5 -2
  190. package/src/serve/hub-app/col-tables-view.tsx +7 -4
  191. package/src/serve/hub-app/col-tables.ts +5 -5
  192. package/src/serve/hub-app/cols-svc.ts +4 -79
  193. package/src/serve/hub-app/commands/commands-page.tsx +2 -1
  194. package/src/serve/hub-app/controls.css +83 -0
  195. package/src/serve/hub-app/frames-st.ts +17 -1
  196. package/src/serve/hub-app/git-view.tsx +3 -2
  197. package/src/serve/hub-app/home-st.ts +57 -6
  198. package/src/serve/hub-app/home-strip.css +1 -6
  199. package/src/serve/hub-app/home-strip.tsx +2 -1
  200. package/src/serve/hub-app/home.html +3 -0
  201. package/src/serve/hub-app/house-wiki-view.tsx +20 -0
  202. package/src/serve/hub-app/hub-app.tsx +48 -32
  203. package/src/serve/hub-app/hub-types.ts +2 -0
  204. package/src/serve/hub-app/hub.css +50 -61
  205. package/src/serve/hub-app/icons.tsx +14 -4
  206. package/src/serve/hub-app/identities-view.tsx +4 -3
  207. package/src/serve/hub-app/inbox-st.ts +203 -42
  208. package/src/serve/hub-app/inbox-view.tsx +189 -101
  209. package/src/serve/hub-app/inbox.css +47 -44
  210. package/src/serve/hub-app/index.html +3 -0
  211. package/src/serve/hub-app/instructions.css +30 -0
  212. package/src/serve/hub-app/keys.ts +5 -3
  213. package/src/serve/hub-app/machine-st.ts +2 -2
  214. package/src/serve/hub-app/machines-view.tsx +4 -11
  215. package/src/serve/hub-app/machines.css +0 -9
  216. package/src/serve/hub-app/markdown.css +51 -0
  217. package/src/serve/hub-app/md-copy.tsx +18 -40
  218. package/src/serve/hub-app/md.ts +25 -9
  219. package/src/serve/hub-app/media-view.tsx +2 -2
  220. package/src/serve/hub-app/messages/messages-page.tsx +2 -1
  221. package/src/serve/hub-app/messages/messages-st.ts +1 -1
  222. package/src/serve/hub-app/messages.css +0 -1
  223. package/src/serve/hub-app/objects.css +51 -0
  224. package/src/serve/hub-app/page-keys.ts +1 -1
  225. package/src/serve/hub-app/pages-frames.tsx +11 -1
  226. package/src/serve/hub-app/palette-st.ts +4 -4
  227. package/src/serve/hub-app/pane-boundary.tsx +72 -0
  228. package/src/serve/hub-app/pane-errors.ts +54 -0
  229. package/src/serve/hub-app/plan-view.tsx +3 -2
  230. package/src/serve/hub-app/planned-view.tsx +3 -3
  231. package/src/serve/hub-app/planned.css +0 -4
  232. package/src/serve/hub-app/processes-view.tsx +3 -2
  233. package/src/serve/hub-app/project-list.css +5 -13
  234. package/src/serve/hub-app/project-list.tsx +3 -6
  235. package/src/serve/hub-app/projects-svc.ts +6 -2
  236. package/src/serve/hub-app/readme.css +9 -15
  237. package/src/serve/hub-app/reflections-page.tsx +54 -1
  238. package/src/serve/hub-app/releases/releases-page.tsx +3 -2
  239. package/src/serve/hub-app/releases.css +0 -1
  240. package/src/serve/hub-app/review/code-colors.ts +30 -0
  241. package/src/serve/hub-app/review/diff-view.tsx +75 -0
  242. package/src/serve/hub-app/review/dock.tsx +104 -0
  243. package/src/serve/hub-app/review/draft-card.tsx +2 -2
  244. package/src/serve/hub-app/review/group-block.tsx +209 -0
  245. package/src/serve/hub-app/review/instructions-view.tsx +116 -0
  246. package/src/serve/hub-app/review/item-verdict.tsx +38 -0
  247. package/src/serve/hub-app/review/kind-states.tsx +193 -0
  248. package/src/serve/hub-app/review/kind-view.tsx +1 -37
  249. package/src/serve/hub-app/review/kit.tsx +57 -54
  250. package/src/serve/hub-app/review/lane-bar.tsx +64 -0
  251. package/src/serve/hub-app/review/object-card.tsx +62 -0
  252. package/src/serve/hub-app/review/object-panel.tsx +179 -0
  253. package/src/serve/hub-app/review/question-views.tsx +385 -0
  254. package/src/serve/hub-app/review/review-cells.tsx +86 -105
  255. package/src/serve/hub-app/review/review-list.tsx +104 -47
  256. package/src/serve/hub-app/review/review-page.tsx +5 -4
  257. package/src/serve/hub-app/review/review-st.ts +68 -28
  258. package/src/serve/hub-app/review/review-thread.tsx +171 -40
  259. package/src/serve/hub-app/review/review-views.tsx +35 -31
  260. package/src/serve/hub-app/review/thread-close.tsx +124 -0
  261. package/src/serve/hub-app/review/thread-control.tsx +4 -4
  262. package/src/serve/hub-app/review/thread-st.ts +222 -22
  263. package/src/serve/hub-app/review/trailer-card.tsx +1 -1
  264. package/src/serve/hub-app/review/trailer-timeline.tsx +2 -2
  265. package/src/serve/hub-app/review.css +216 -57
  266. package/src/serve/hub-app/section-head.tsx +51 -0
  267. package/src/serve/hub-app/social/calendar.tsx +5 -11
  268. package/src/serve/hub-app/social/comms-page.tsx +23 -10
  269. package/src/serve/hub-app/social/kit.tsx +8 -15
  270. package/src/serve/hub-app/social/next-release.tsx +3 -5
  271. package/src/serve/hub-app/social/post-card.tsx +3 -0
  272. package/src/serve/hub-app/social/post-page.tsx +80 -0
  273. package/src/serve/hub-app/social/problems.tsx +5 -9
  274. package/src/serve/hub-app/social/social-model.ts +13 -5
  275. package/src/serve/hub-app/social/social-page.tsx +1 -1
  276. package/src/serve/hub-app/social/social-st.ts +42 -5
  277. package/src/serve/hub-app/social.css +7 -17
  278. package/src/serve/hub-app/space.css +1 -1
  279. package/src/serve/hub-app/stores/stores-page.tsx +6 -2
  280. package/src/serve/hub-app/thread-row.tsx +101 -0
  281. package/src/serve/hub-app/time-ago.tsx +3 -2
  282. package/src/serve/hub-app/time-view.tsx +2 -1
  283. package/src/serve/hub-app/time.css +2 -5
  284. package/src/serve/hub-app/tree-row.tsx +1 -9
  285. package/src/serve/hub-app/vault-view.tsx +4 -4
  286. package/src/serve/hub-app/veille/veille-page.tsx +2 -11
  287. package/src/serve/hub-app/veille.css +0 -1
  288. package/src/serve/hub-app/waiting-svc.ts +4 -4
  289. package/src/serve/hub-app/when-view.tsx +6 -3
  290. package/src/serve/hub-app/wiki-st.ts +30 -4
  291. package/src/serve/hub-app/wikis-view.tsx +4 -3
  292. package/src/serve/hub-runtime.ts +20 -6
  293. package/src/serve/project-gutter-route.ts +16 -6
  294. package/src/serve/project-gutter.ts +6 -53
  295. package/src/serve/same-origin.ts +3 -0
  296. package/src/serve/secret-gate.ts +21 -0
  297. package/src/serve/serve-hub.ts +29 -20
  298. package/src/serve/tailnet-caller.ts +117 -0
  299. package/src/shipkit.ts +2 -2
  300. package/src/site/desk.ts +2 -2
  301. package/src/smoke/run-smoke.ts +3 -4
  302. package/src/social/brands.ts +4 -0
  303. package/src/social/card-drafts.ts +11 -19
  304. package/src/social/desk-index.ts +34 -13
  305. package/src/social/drafts.ts +4 -4
  306. package/src/social/import-drafts.ts +244 -0
  307. package/src/social/kind-pages.ts +3 -3
  308. package/src/social/kinds.ts +1 -1
  309. package/src/social/load.ts +89 -64
  310. package/src/social/media-kind.ts +68 -161
  311. package/src/social/media-of.ts +5 -4
  312. package/src/social/open.ts +3 -2
  313. package/src/social/post-object.ts +120 -0
  314. package/src/social/post-sources.ts +136 -0
  315. package/src/social/post-text.ts +103 -0
  316. package/src/social/posts.ts +378 -0
  317. package/src/social/presence.ts +7 -5
  318. package/src/social/publish/index.ts +17 -5
  319. package/src/social/publish/secret.ts +2 -2
  320. package/src/social/release-stage.ts +58 -57
  321. package/src/social/routes.ts +64 -24
  322. package/src/social/stage.ts +42 -57
  323. package/src/social/text.ts +4 -3
  324. package/src/social/thumbnail.ts +135 -43
  325. package/src/social/tracker.ts +1 -1
  326. package/src/social/writes.ts +12 -29
  327. package/src/stores/desk.ts +16 -11
  328. package/src/stores/unit.ts +2 -2
  329. package/src/trailer/sound/eleven.ts +33 -3
  330. package/src/urls/rows.ts +1 -1
  331. package/src/vault/vault-http.ts +11 -3
  332. package/src/vault/vault-import.ts +6 -1
  333. package/src/veille/identity.ts +2 -2
  334. package/src/wiki/graph-pages.ts +13 -1
  335. package/src/wiki/scan-md.ts +1 -1
  336. package/src/asks/asks-queue.ts +0 -424
  337. package/src/messages/suggest.ts +0 -96
  338. package/src/social/migrate.ts +0 -123
@@ -0,0 +1,586 @@
1
+ // the asks of a repo (wiki tools/shipkit/threads-asks.md, An ask's thread): each one a thread `ask:<id>` of the repo's
2
+ // thread store, `<id>` its number and slug. Its head holds the facts no message says (`ask`, review/model.ts AskHead),
3
+ // its words are the head's `what` until newer instructions supersede them (a message `instructions`, its words and its
4
+ // facts as they stand now), its status and closed day the thread's askState messages, its later day the thread's snooze. The one module every reader and writer of asks goes through: nothing else writes an ask's facts
5
+ import { mutateLease, withMutateLease } from '../core/locked-write.ts'
6
+ import { allStoredSince, type HeldOf } from '../secrets/held.ts'
7
+ import { SECRET_NAME } from '../secrets/name.ts'
8
+ import { kindOfAsk, ticksOf } from '../review/answer-kinds.ts'
9
+ import { askKindOf, ASK_KINDS, isAskItem, partyOf, type AskHead, type AskKind, type AskWait, type Message, type MessageAsk, type ReviewItem } from '../review/model.ts'
10
+ import { addMessage, appendMessage, hasStore, openThread, postAsk, readAll, storeDir, updateHead } from '../review/store.ts'
11
+ import { askStateOf, asideUntil, membersOf, openAsksOf, orderedThreads, type Thread } from '../review/threads.ts'
12
+ import { currentInstructions, foldsOf, replacersOf } from '../review/supersede.ts'
13
+ import { instructionsRefusal, parseInstructions, stepSections } from '../review/instructions.ts'
14
+ import { AFTER_FORMS, afterMs, afterWords } from './ask-after.ts'
15
+
16
+ export type { AskWait } from '../review/model.ts'
17
+
18
+ export const CLOSED = ['done', 'declined'] as const
19
+ export type Closed = (typeof CLOSED)[number]
20
+ export type AskStatus = 'open' | Closed
21
+ export const isClosed = (status: string): status is Closed => (CLOSED as readonly string[]).includes(status)
22
+
23
+ /** one ask as every reader sees it. `id` the key of its thread's address (`014-turn-on-filevault`), `head` the item id
24
+ * of its thread's head. `closed`, `why`: the day it closed and the reason said then (his decline, a proof). `stores`:
25
+ * every secret name it asks to store, its `secrets` and the ones a store line of its body names. `after`: the local
26
+ * moment its thread is set aside until (`YYYY-MM-DD` or `YYYY-MM-DDTHH:MM`), `afterAt` the same in epoch ms */
27
+ export type Ask = {
28
+ id: string
29
+ address: string
30
+ head: string
31
+ status: AskStatus
32
+ kind: AskKind
33
+ created: string
34
+ closed: string | null
35
+ why: string | null
36
+ blocks: string
37
+ check: string | null
38
+ waits: AskWait[]
39
+ pinged: string | null
40
+ secrets: string[]
41
+ logins: string[]
42
+ stores: string[]
43
+ after: string | null
44
+ afterAt: number | null
45
+ title: string
46
+ body: string
47
+ }
48
+
49
+ /** a store line in an ask's body: `<tool> secret set <name>`, as `sk secret set` and a secret manager of the same shape write it */
50
+ const STORE_LINE = /\bsecret set\s+([A-Za-z0-9][A-Za-z0-9._@/-]*)/g
51
+ const ID_RE = /^\d+-[a-z0-9-]+$/
52
+
53
+ export const askAddress = (id: string): string => `ask:${id}`
54
+
55
+ /** the id a reference names: `014-x`, `014-x.md`, `done/014-x.md`, `ask:014-x`; a bare number stays a number */
56
+ export const askIdOf = (ref: string): string => ref.trim().replace(/^ask:/, '').replace(/^(done|declined)\//, '').replace(/\.md$/, '')
57
+
58
+ const ONE_WAIT = /^([^\s,"]+)\s+"([^"]*)"\s*(?:,\s*|$)/
59
+
60
+ /** `SK002 "Steamworks appid", read-email "token refresh"`. The words are required and any other spelling throws, the
61
+ * source named: a hold with no words would cover every warning its check ever prints, agent work included */
62
+ export const parseWaits = (v: string | null, source: string): AskWait[] => {
63
+ const out: AskWait[] = []
64
+ let rest = (v ?? '').trim()
65
+ while (rest !== '') {
66
+ const m = ONE_WAIT.exec(rest)
67
+ if (m == null || m[2]!.trim() === '') throw new Error(`${source}: waits '${v}' is not <check id> "<words of its line>"[, <check id> "<words>"]: the words are required`)
68
+ out.push({ check: m[1]!, says: m[2]!.trim() })
69
+ rest = rest.slice(m[0].length)
70
+ }
71
+ return out
72
+ }
73
+
74
+ /** an id's slug: kebab, cut at a word boundary (never mid-word: a `…-rvlib-` stub reads as broken), a hard cut only
75
+ * when the first word alone is longer */
76
+ export function slugify(title: string, max = 40): string {
77
+ const full = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
78
+ if (full.length <= max) return full
79
+ const cut = full.slice(0, max)
80
+ const lastDash = cut.lastIndexOf('-')
81
+ return (lastDash > 0 ? cut.slice(0, lastDash) : cut).replace(/-+$/, '')
82
+ }
83
+
84
+ const pad = (n: number): string => String(n).padStart(2, '0')
85
+ /** a moment as an ask names it, local time: the bare day at midnight */
86
+ export const localStamp = (d: Date): string => {
87
+ const day = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
88
+ return d.getHours() === 0 && d.getMinutes() === 0 ? day : `${day}T${pad(d.getHours())}:${pad(d.getMinutes())}`
89
+ }
90
+ const today = (now = new Date()): string => localStamp(new Date(now.getFullYear(), now.getMonth(), now.getDate()))
91
+
92
+ /** the newest askState of the thread with its day, open when none was said */
93
+ function stateOf(t: Thread): { status: AskStatus; at: string | null; why: string | null } {
94
+ const last = askStateOf(t)
95
+ return last === null ? { status: 'open', at: null, why: null } : { status: last.state, at: last.at, why: last.why ?? null }
96
+ }
97
+
98
+ /** the ask a thread is, null for a thread that is none (no ask facts on its head) */
99
+ export function askOfThread(t: Thread, now = new Date()): Ask | null {
100
+ const h = t.head.item
101
+ if (!isAskItem(h) || h.ask === undefined) return null
102
+ const on = h.on!
103
+ const newer = currentInstructions(membersOf(t))
104
+ // the facts of the newest instructions; the day it was made and its one ping stay the head's
105
+ const f: AskHead = newer ? { ...newer.instructions.ask, created: h.ask.created, ...(h.ask.pinged ? { pinged: h.ask.pinged } : {}) } : h.ask
106
+ const s = stateOf(t)
107
+ const body = newer ? (newer.text ?? '') : (h.what ?? '')
108
+ const until = s.status === 'open' ? asideUntil(t, now) : null
109
+ const secrets = f.secrets ?? []
110
+ return {
111
+ id: on.slice('ask:'.length),
112
+ address: on,
113
+ head: h.id,
114
+ status: s.status,
115
+ kind: f.kind,
116
+ created: f.created,
117
+ closed: s.status === 'open' || s.at === null ? null : localStamp(new Date(new Date(s.at).setHours(0, 0, 0, 0))),
118
+ why: s.status === 'open' ? null : s.why,
119
+ blocks: f.blocks,
120
+ check: f.check ?? null,
121
+ waits: f.waits ?? [],
122
+ pinged: f.pinged ?? null,
123
+ secrets,
124
+ logins: f.logins ?? [],
125
+ stores: [...new Set([...secrets, ...[...body.matchAll(STORE_LINE)].map((m) => m[1]!.replace(/[.]+$/, ''))])],
126
+ after: until === null ? null : localStamp(new Date(until)),
127
+ afterAt: until === null ? null : Date.parse(until),
128
+ title: newer?.instructions.title ?? h.title,
129
+ body,
130
+ }
131
+ }
132
+
133
+ /** the asks among a store's items, by id */
134
+ export const asksIn = (items: readonly ReviewItem[], now = new Date()): Ask[] =>
135
+ orderedThreads(items)
136
+ .flatMap((t) => askOfThread(t, now) ?? [])
137
+ .sort((a, b) => a.id.localeCompare(b.id))
138
+
139
+ /** every ask of the repo, open and closed, by id */
140
+ export const listAsks = (root: string, now = new Date()): Ask[] => asksIn(readAll(storeDir(root)).items, now)
141
+
142
+ /** an open ask whose thread is set aside: out of the open count and the ping until then */
143
+ export const isLater = (a: Ask, now: number = Date.now()): boolean => !isClosed(a.status) && a.afterAt != null && now < a.afterAt
144
+
145
+ /** every ask neither done nor declined, the later ones included (isLater tells them apart) */
146
+ export const openAsks = (root: string, now = new Date()): Ask[] => listAsks(root, now).filter((a) => !isClosed(a.status))
147
+
148
+ /** the asks closed with this status, newest first */
149
+ export const closedAsks = (root: string, status: Closed): Ask[] =>
150
+ listAsks(root)
151
+ .filter((a) => a.status === status)
152
+ .reverse()
153
+
154
+ /** the asks the owner declined, newest first */
155
+ export const declinedAsks = (root: string): Ask[] => closedAsks(root, 'declined')
156
+
157
+ /** one ask by its id, its old file name or its number; throws naming why. `open`: only an open one */
158
+ export function findAsk(root: string, ref: string, o: { open?: boolean } = {}): Ask {
159
+ const id = askIdOf(ref)
160
+ const n = /^\d+$/.test(id) ? Number(id) : null
161
+ const all = listAsks(root).filter((a) => !o.open || !isClosed(a.status))
162
+ const hit = all.filter((a) => a.id === id || (n != null && parseInt(a.id, 10) === n))
163
+ if (hit.length === 1) return hit[0]!
164
+ throw new Error(hit.length === 0 ? `no ${o.open ? 'open ' : ''}ask ${ref} (sk asks lists them)` : `${ref} names ${hit.length} asks: ${hit.map((a) => a.id).join(', ')}`)
165
+ }
166
+
167
+ /** the checklist an ask's instructions carry, their steps (review/instructions.ts): each `##` title a line, a step marked
168
+ * ✅ done from the start, a choice step's options; null for instructions with no step */
169
+ export function stepsAskOf(body: string, o: { numbered?: boolean } = {}): MessageAsk | null {
170
+ const steps = parseInstructions(body, o).steps
171
+ if (steps.length === 0) return null
172
+ const done = steps.flatMap((s, i) => (s.done ? [i] : []))
173
+ const choices = steps.some((s) => s.choice !== null) ? { choices: steps.map((s) => s.choice) } : {}
174
+ return { kind: 'checklist', options: steps.map((s) => s.title), ...(done.length > 0 ? { done } : {}), ...choices }
175
+ }
176
+
177
+ /** a decision ask's options: its numbered lines `1. **<option>**: <words>`, as they read */
178
+ export function optionsOf(body: string): string[] {
179
+ return [...body.matchAll(/^\d+\.\s+(.+)$/gm)].map((m) => m[1]!.replace(/\*\*/g, '').trim()).filter((o) => o !== '' && !o.includes('{{'))
180
+ }
181
+
182
+ // the shape a walkthrough ask is written in (wiki tools/shipkit/threads-instructions.md): `sk ask --scaffold` prints it,
183
+ // the agent fills every {{placeholder}} in a file and gives it with --body
184
+ const STEPS_BODY = `## {{verb}} {{thing}}
185
+
186
+ Open **[{{page name}}]({{url, ids filled in}})**, then click **{{button}}**.
187
+
188
+ | field | value |
189
+ |---|---|
190
+ | {{field}} | \`{{value}}\` |
191
+
192
+ ## {{the next act he does}}
193
+
194
+ Open **[{{page name}}]({{url}})**, then paste:
195
+
196
+ \`\`\`
197
+ {{the exact text he pastes}}
198
+ \`\`\`
199
+ `
200
+
201
+ const DECISION_BODY = `1. **{{option}} (recommended)**: {{what it changes, what it costs}}
202
+ 2. **{{option}}**: {{what it changes, what it costs}}
203
+ `
204
+
205
+ /** the sections to fill for an ask of this kind */
206
+ export const scaffoldOf = (kind: AskKind): string => (kind === 'decision' ? DECISION_BODY : STEPS_BODY)
207
+
208
+ /** `again`: an ask the owner declined, asked again on purpose; `why` then says what changed. `readers`: who will read
209
+ * each secret, in words (secrets/who-reads.ts). `body`: its sections (`## N. <step>` each). `waits`: `<check id>
210
+ * "<words>"` pairs. `after`: the local moment it waits for (ask-after.ts afterValue) */
211
+ export type CreateOpts = {
212
+ kind?: string
213
+ blocks?: string
214
+ check?: string
215
+ why?: string
216
+ secrets?: string[]
217
+ after?: string
218
+ again?: boolean
219
+ readers?: Record<string, string>
220
+ logins?: string[]
221
+ body?: string
222
+ waits?: string
223
+ lane?: string
224
+ now?: Date
225
+ }
226
+
227
+ /** the ask the owner declined that a new one repeats: the same slug, or a secret it stores; null when none */
228
+ function declinedLike(asks: readonly Ask[], slug: string, secrets: readonly string[]): { ask: Ask; why: string } | null {
229
+ for (const a of asks.filter((x) => x.status === 'declined')) {
230
+ if (a.id.replace(/^\d+-/, '') === slug) return { ask: a, why: 'this ask' }
231
+ const name = secrets.find((s) => a.stores.includes(s))
232
+ if (name != null) return { ask: a, why: `the ask for ${name}` }
233
+ }
234
+ return null
235
+ }
236
+
237
+ /** the words of an ask: its why, who reads each secret, then its steps. Its title is the thread's, and its check a fact
238
+ * the hub folds under the steps, never his reading (wiki tools/shipkit/threads-instructions.md) */
239
+ function bodyOf(why: string, sections: string | undefined, secrets: readonly string[], readers: Record<string, string>): string {
240
+ const parts: string[] = []
241
+ if (why !== '') parts.push(`**Why**: ${why}`)
242
+ if (secrets.some((n) => readers[n] != null)) parts.push(`Who will read it once stored:\n\n${secrets.map((n) => `- \`${n}\`: ${readers[n] ?? 'not known'}`).join('\n')}`)
243
+ if (sections != null && sections.trim() !== '') parts.push(sections.trim())
244
+ return parts.join('\n\n')
245
+ }
246
+
247
+ type AskWords = { kind: AskKind; title: string; body: string; secrets: readonly string[]; logins: readonly string[] }
248
+
249
+ /** the questions an open ask's thread asks beside its instructions, from its body and facts: a decision's options a
250
+ * choice, each secret a secret field. Its steps are its instructions' own checklist, and the ask bar's « done ✓ » is
251
+ * the one « done » of an ask */
252
+ export function questionsOf(a: AskWords): Omit<Parameters<typeof postAsk>[2], 'who' | 'now'>[] {
253
+ const decision = a.kind === 'decision' ? optionsOf(a.body) : []
254
+ const inSteps = new Set(stepSecrets(a.body).map((f) => f.name))
255
+ return [
256
+ ...(decision.length >= 2 ? [{ text: a.title, options: decision, pick: 0 }] : []),
257
+ ...a.secrets.filter((name) => !inSteps.has(name)).map((name) => ({ text: `The value of ${name}`, kind: 'secret' as const, secret: { name, login: a.logins.includes(name) } })),
258
+ ]
259
+ }
260
+
261
+ /** the secret fields the steps of these words hold, in order */
262
+ const stepSecrets = (body: string): { name: string; login: boolean }[] =>
263
+ parseInstructions(body).steps.flatMap((s) => s.fields.flatMap((f) => (f.kind === 'secret' ? [{ name: f.name, login: f.login === true }] : [])))
264
+
265
+ /** each field the steps of an instructions message hold, posted as a question of its step (`step: { of, i }`): drawn in
266
+ * that step, never beside it. Its steps are the ones stored on it, so words of an older grammar map as they tick */
267
+ export async function postFields(store: string, head: string, ins: Message, o: { who: string; now: Date }): Promise<void> {
268
+ for (const p of stepSections(ins.text ?? '', ins.ask?.options ?? []))
269
+ for (const f of p.kind === 'step' ? p.step.fields : []) {
270
+ const i = p.kind === 'step' ? p.i : 0
271
+ const step = { of: ins.id, i }
272
+ if (f.kind === 'secret') await postAsk(store, head, { who: o.who, text: f.hint || `The value of ${f.name}`, kind: 'secret', secret: { name: f.name, ...(f.login ? { login: true } : {}) }, step, now: o.now })
273
+ else await postAsk(store, head, { who: o.who, text: f.hint || (f.kind === 'url' ? 'the link' : 'the value'), kind: f.kind, step, now: o.now })
274
+ }
275
+ }
276
+
277
+ /** an ask's instructions as one message: its words, its title and facts, the questions it folds, and its steps as its
278
+ * own checklist, so a tick answers the instructions themselves */
279
+ export function instructionsMessage(o: { who: string; title: string; body: string; facts: Omit<AskHead, 'created' | 'pinged'>; folds: string[]; ticked?: ReadonlySet<string>; numbered?: boolean }) {
280
+ const steps = stepsAskOf(o.body, { numbered: o.numbered === true })
281
+ if (steps === null) return { who: o.who, text: o.body, instructions: { title: o.title, ask: o.facts, folds: o.folds } }
282
+ const done = steps.options.flatMap((t, i) => ((steps.done ?? []).includes(i) || o.ticked?.has(stepKey(t)) === true ? [i] : []))
283
+ return { who: o.who, text: o.body, instructions: { title: o.title, ask: o.facts, folds: o.folds }, ask: { ...steps, ...(done.length > 0 ? { done } : {}) } }
284
+ }
285
+
286
+ /** a step's title as its tick is kept by: case and spaces aside */
287
+ export const stepKey = (title: string): string => title.replace(/\s+/g, ' ').trim().toLowerCase()
288
+
289
+ /** the titles of the steps he ticked on what stands as an ask's steps now (its instructions, or an older ask's « The
290
+ * steps » checklist), so new instructions keep a tick on a step whose title did not change. His pick on a choice step
291
+ * is not carried: a changed choice is a new question */
292
+ export function tickedTitles(t: Thread): Set<string> {
293
+ const members = membersOf(t)
294
+ const gone = replacersOf(members)
295
+ const out = new Set<string>()
296
+ for (const x of members)
297
+ for (const m of x.thread)
298
+ if (partyOf(m.who) === 'agent' && !gone.has(m.id) && m.ask?.kind === 'checklist' && (m.instructions !== undefined || m.text === 'The steps'))
299
+ for (const [i, s] of ticksOf(x.thread, m)) if (s.tick) out.add(stepKey(m.ask.options[i] ?? ''))
300
+ return out
301
+ }
302
+
303
+ /** where an ask's standing instructions are: each step's title and whether it is ticked, and the value he gave each
304
+ * text or url field of its steps, in order. Null for an ask whose words are no instructions: an older ask, its body
305
+ * read by its own grammar (stores/model.ts askSteps) */
306
+ export function askStepsNow(root: string, a: Ask): { steps: { title: string; done: boolean }[]; values: string[] } | null {
307
+ const t = orderedThreads(readAll(storeDir(root)).items).find((x) => x.head.item.id === a.head)
308
+ if (t === undefined) return null
309
+ const members = membersOf(t)
310
+ const cur = currentInstructions(members)
311
+ if (cur === null || cur.ask === undefined) return null
312
+ const all = members.flatMap((x) => x.thread)
313
+ const ticks = ticksOf(members.find((x) => x.thread.some((m) => m.id === cur.id))!.thread, cur)
314
+ const gone = replacersOf(members)
315
+ const values = all
316
+ .filter((q) => q.step?.of === cur.id && partyOf(q.who) === 'agent' && !gone.has(q.id) && (kindOfAsk(q) === 'text' || kindOfAsk(q) === 'url'))
317
+ .flatMap((q) => all.filter((y) => y.re === q.id && partyOf(y.who) === 'owner').at(-1)?.answer?.value ?? [])
318
+ return { steps: cur.ask.options.map((title, i) => ({ title, done: ticks.get(i)?.tick === true })), values }
319
+ }
320
+
321
+ /** questionsOf posted in the ask's thread; how many */
322
+ export async function postQuestions(store: string, head: string, a: AskWords, o: { who: string; now?: Date }): Promise<number> {
323
+ const qs = questionsOf(a)
324
+ for (const q of qs) await postAsk(store, head, { ...q, who: o.who, ...(o.now ? { now: o.now } : {}) })
325
+ return qs.length
326
+ }
327
+
328
+ /** the highest number an ask of the store took, 0 for none: numbers are never used twice */
329
+ const topNumber = (items: readonly ReviewItem[]): number =>
330
+ Math.max(0, ...items.flatMap((x) => (x.item.on?.startsWith('ask:') ? [parseInt(x.item.on.slice('ask:'.length), 10) || 0] : [])))
331
+
332
+ /** an ask's facts and the checks on them, one reading for a new ask and for new instructions of one */
333
+ function factsOf(title: string, opts: CreateOpts) {
334
+ const inSteps = stepSecrets(opts.body ?? '')
335
+ const secrets = [...new Set([...(opts.secrets ?? []), ...inSteps.map((f) => f.name)])]
336
+ const bad = secrets.find((s) => !SECRET_NAME.test(s))
337
+ if (bad != null) throw new Error(`refusing secret name '${bad}': letters, digits and . _ @ / - only, never a leading dash`)
338
+ const logins = [...new Set([...(opts.logins ?? []), ...inSteps.filter((f) => f.login).map((f) => f.name)])]
339
+ if (logins.some((l) => !secrets.includes(l))) throw new Error(`a login is one of the ask's secrets: ${logins.filter((l) => !secrets.includes(l)).join(', ')} is not`)
340
+ const kind = askKindOf(opts.kind ?? (secrets.length > 0 ? 'credential' : 'action'))
341
+ if (kind == null) throw new Error(`--kind ${opts.kind}: one of ${ASK_KINDS.join(', ')}`)
342
+ if (secrets.length > 0 && kind !== 'credential') throw new Error(`a secret is stored by a credential ask, not a ${kind} one`)
343
+ const check = opts.check ?? (secrets.length > 0 ? secrets.map((s) => `sk secret get ${s} >/dev/null`).join(' && ') : null)
344
+ const why = opts.why?.replace(/\s+/g, ' ').trim() ?? ''
345
+ const waits = opts.waits != null ? parseWaits(opts.waits, '--waits') : []
346
+ const refused = opts.body != null ? instructionsRefusal(opts.body) : null
347
+ if (refused !== null) throw new Error(`--body: ${refused}`)
348
+ if (slugify(title) === '') throw new Error('a title with no letter or digit names no ask')
349
+ const head = (created: string): AskHead => ({
350
+ kind,
351
+ created,
352
+ blocks: opts.blocks?.trim() || '-',
353
+ ...(check != null ? { check } : {}),
354
+ ...(waits.length > 0 ? { waits } : {}),
355
+ ...(secrets.length > 0 ? { secrets } : {}),
356
+ ...(logins.length > 0 ? { logins } : {}),
357
+ })
358
+ return { kind, secrets, logins, check, why, head }
359
+ }
360
+
361
+ /** a new ask: its thread `ask:<NNN>-<slug>` opened with its facts and words, then its questions, set aside when it
362
+ * waits for a later day. Numbered under the repo's asks lease, so two at once never take one number */
363
+ export async function createAsk(root: string, title: string, opts: CreateOpts = {}): Promise<Ask> {
364
+ const { kind, secrets, logins, why, head } = factsOf(title, opts)
365
+ if (opts.again === true && why === '') throw new Error('--again needs --why: what changed since the owner declined it')
366
+ const after = opts.after
367
+ if (after != null && afterMs(after) == null) throw new Error(`refusing after: '${after}': write ${AFTER_FORMS}`)
368
+ const slug = slugify(title)
369
+ const now = opts.now ?? new Date()
370
+ const store = storeDir(root)
371
+ const leased = await withMutateLease(mutateLease(root, 'asks'), { label: 'asks', print: () => {}, maxWaitMs: 45_000 }, async () => {
372
+ const items = readAll(store).items
373
+ const no = declinedLike(asksIn(items, now), slug, secrets)
374
+ if (opts.again !== true && no != null)
375
+ throw new Error(`refusing: the owner declined ${no.why} (${no.ask.address}) on ${no.ask.closed ?? '?'}: an ask the owner declined stays declined. Ask again only when a fact changed after the owner's no: sk ask "${title}" --again --why "<the fact and its source>"`)
376
+ const id = `${String(topNumber(items) + 1).padStart(3, '0')}-${slug}`
377
+ const repeats = opts.again === true && no != null ? `asked again after the owner declined ${no.ask.address} on ${no.ask.closed ?? '?'}: ` : ''
378
+ const body = bodyOf(why === '' ? '' : `${repeats}${why}`, opts.body, secrets, opts.readers ?? {})
379
+ const facts = head(today(now))
380
+ // the head holds the facts, its words are the instructions: one message, its steps its own checklist
381
+ const x = await openThread(store, askAddress(id), { title, ask: facts, now, ...(opts.lane ? { lane: opts.lane } : {}) })
382
+ const who = opts.lane ?? 'agent'
383
+ const { created: _day, ...rest } = facts
384
+ const ins = appendMessage(store, x.id, instructionsMessage({ who, title, body, facts: rest, folds: [] }), { now })
385
+ await postFields(store, x.id, ins, { who, now })
386
+ await postQuestions(store, x.id, { kind, title, body, secrets, logins }, { who, now })
387
+ const at = after == null ? null : afterMs(after)
388
+ if (at != null && at > now.getTime()) appendMessage(store, x.id, { who, snooze: { until: new Date(at).toISOString() } }, { now })
389
+ return id
390
+ })
391
+ if (!leased.ok) throw new Error(`no ask made: ${leased.warn}`)
392
+ return findAsk(root, leased.value)
393
+ }
394
+
395
+ /** an open ask's new instructions (wiki tools/shipkit/threads-asks.md, Superseded objects): its words, title and facts
396
+ * as a message that supersedes the instructions that stood (the head's words, or the newest instructions), naming the
397
+ * questions it folds with them (those the old instructions were posted with), then its questions anew, all at one
398
+ * moment. A fact not given again stands (kind, blocks, waits); its secrets, logins and check follow the new words.
399
+ * `holds`: the caller holds the thread or is the session of the lane that does (the cli asks review/parties.ts).
400
+ * Under the repo's asks lease, so two at once never both supersede the same instructions */
401
+ export async function reinstructAsk(root: string, ref: string, title: string, opts: CreateOpts & { holds: boolean; folds?: string[] }): Promise<Ask & { folded: string[] }> {
402
+ if (opts.again === true || opts.after != null) throw new Error('--again and --after go with a new ask; new instructions keep the ask, its number and its day')
403
+ if (!opts.holds) throw new Error(`--replaces ${ref}: only the agent that holds its thread, or its session, gives an ask new instructions (sk thread take ask:<id> first)`)
404
+ const store = storeDir(root)
405
+ const leased = await withMutateLease(mutateLease(root, 'asks'), { label: 'asks', print: () => {}, maxWaitMs: 45_000 }, async () => {
406
+ const a = findAsk(root, ref)
407
+ if (isClosed(a.status)) throw new Error(`${a.id} is ${a.status}: sk asks reopen ${a.id} first, then give it new instructions`)
408
+ const secrets = [...(opts.secrets ?? []), ...stepSecrets(opts.body ?? '').map((f) => f.name)]
409
+ const { kind, logins, why, head } = factsOf(title, { ...opts, kind: opts.kind ?? (secrets.length > 0 ? undefined : a.kind), blocks: opts.blocks ?? a.blocks })
410
+ const { created: _day, ...facts } = { ...head(a.created), ...(opts.waits == null && a.waits.length > 0 ? { waits: a.waits } : {}) }
411
+ const t = orderedThreads(readAll(store).items).find((x) => x.head.item.id === a.head)
412
+ if (t == null) throw new Error(`${a.id}: its thread is gone`)
413
+ const folds = [...new Set([...foldsOf(membersOf(t)), ...(opts.folds ?? [])])]
414
+ const body = bodyOf(why, opts.body, secrets, opts.readers ?? {})
415
+ const who = opts.lane ?? 'agent'
416
+ const now = opts.now ?? new Date()
417
+ const ins = appendMessage(store, a.head, instructionsMessage({ who, title, body, facts, folds, ticked: tickedTitles(t) }), { now })
418
+ await postFields(store, a.head, ins, { who, now })
419
+ await postQuestions(store, a.head, { kind, title, body, secrets, logins }, { who, now })
420
+ return { id: a.id, folds }
421
+ })
422
+ if (!leased.ok) throw new Error(`no new instructions written: ${leased.warn}`)
423
+ return { ...findAsk(root, leased.value.id), folded: leased.value.folds }
424
+ }
425
+
426
+ /** the ask's status said in its thread (`askState`), by the owner or an agent: a close closes its open questions with
427
+ * it. False when it already says that */
428
+ export function setAskState(root: string, a: Ask, state: AskStatus, o: { who: string; why?: string; now?: Date }): boolean {
429
+ if (a.status === state) return false
430
+ const why = o.why?.replace(/\s+/g, ' ').trim()
431
+ appendMessage(storeDir(root), a.head, { who: o.who, askState: { state, ...(why ? { why } : {}) } }, o.now ? { now: o.now } : {})
432
+ return true
433
+ }
434
+
435
+ /** an open ask done: the owner's « done ✓ », his proof, a check that passed */
436
+ export function doneAsk(root: string, ref: string, o: { who: string; why?: string; now?: Date }): Ask {
437
+ const a = findAsk(root, ref, { open: true })
438
+ setAskState(root, a, 'done', o)
439
+ return a
440
+ }
441
+
442
+ /** the owner's word that he will not do an open ask: its thread says declined with his reason. Undone by reopenAsk */
443
+ export function declineAsk(root: string, ref: string, why?: string, now?: Date): Ask {
444
+ const a = findAsk(root, ref, { open: true })
445
+ setAskState(root, a, 'declined', { who: 'owner', ...(why ? { why } : {}), ...(now ? { now } : {}) })
446
+ return a
447
+ }
448
+
449
+ /** a closed ask open again, its questions open with it */
450
+ export function reopenAsk(root: string, ref: string, o: { who: string; why?: string }): Ask {
451
+ const a = findAsk(root, ref)
452
+ if (!isClosed(a.status)) throw new Error(`${a.id} is open already`)
453
+ setAskState(root, a, 'open', o)
454
+ return a
455
+ }
456
+
457
+ /** the proof the owner gives (wiki preferences/human-loop/index.md: no URL, not done): it closes the ask, done */
458
+ export const proofAsk = (root: string, ref: string, url: string): Ask => doneAsk(root, ref, { who: 'owner', why: `proof: ${url.trim()}` })
459
+
460
+ /** a remark on an ask, open or closed: a message of its thread */
461
+ export function remarkAsk(root: string, ref: string, text: string, who = 'owner'): void {
462
+ const a = findAsk(root, ref)
463
+ addMessage(storeDir(root), a.head, who, text.replace(/\n+/g, ' ').trim())
464
+ }
465
+
466
+ /** the ask's one ping, its day on the head: false when it was pinged already, so a ping never fires twice */
467
+ export function markPinged(root: string, ref: string, now = new Date()): boolean {
468
+ const a = findAsk(root, ref)
469
+ if (a.pinged != null) return false
470
+ let fresh = false
471
+ updateHead(storeDir(root), a.head, (cur) => {
472
+ if (cur.ask === undefined || cur.ask.pinged !== undefined) return cur
473
+ fresh = true
474
+ return { ...cur, ask: { ...cur.ask, pinged: today(now) } }
475
+ })
476
+ return fresh
477
+ }
478
+
479
+ /** after the owner's answer in thread item `id`: an answer never closes an ask, its done condition does. Once every
480
+ * question of its thread is answered, its check runs (its values stored, its probe), and a pass closes it; an ask with
481
+ * no check waits for his « done ✓ » on its bar. The ask closed, null when nothing closed */
482
+ export async function followAskThread(root: string, id: string, o: CloseOpts = {}): Promise<Ask | null> {
483
+ const store = storeDir(root)
484
+ const items = readAll(store).items
485
+ const t = orderedThreads(items).find((x) => membersOf(x).some((y) => y.item.id === id))
486
+ if (t == null) return null
487
+ const a = askOfThread(t)
488
+ if (a == null || isClosed(a.status) || openAsksOf(t).length > 0) return null
489
+ const gone = replacersOf(membersOf(t))
490
+ const asks = membersOf(t).flatMap((y) => y.thread.filter((m) => m.ask !== undefined && !gone.has(m.id)).map((m) => ({ m, thread: y.thread })))
491
+ if (asks.length === 0) return null
492
+ // words alone are his « none »: the agent reads them, the ask stays open
493
+ if (asks.some(({ m, thread }) => kindOfAsk(m) !== 'checklist' && thread.filter((y) => y.re === m.id && partyOf(y.who) === 'owner').at(-1)?.answer === undefined)) return null
494
+ const r = await checkAsk(root, a.id, o)
495
+ return r.check === 'in' || r.check === 'passed' ? findAsk(root, a.id) : null
496
+ }
497
+
498
+ /** `held`: the store's read of a credential ask's names (secrets/read.ts heldHere by default), a test passes its own */
499
+ export type CloseOpts = { held?: HeldOf }
500
+
501
+ /** a credential ask closes once every value it names was stored on or after the day it was made. A value of no known
502
+ * day never closes it */
503
+ async function valuesIn(root: string, a: Ask, o: CloseOpts): Promise<boolean> {
504
+ if (a.kind !== 'credential' || a.secrets.length === 0) return false
505
+ const since = afterMs(a.created)
506
+ if (since == null) return false
507
+ const held = await (o.held ?? (async (names, cwd) => (await import('../secrets/read.ts')).heldHere({ names, cwd })))(a.secrets, root).catch(() => ({}))
508
+ return allStoredSince(held, a.secrets, since)
509
+ }
510
+
511
+ /** one ask's probe, run at the repo's root (a secret read is gated by the repo it runs in); else why it failed */
512
+ function probe(root: string, check: string): { passed: true } | { passed: false; why: string } {
513
+ // env named: bun's default is the env the process started with, blind to a later process.env write
514
+ const p = Bun.spawnSync(['bash', '-lc', check], { cwd: root, env: process.env, stdout: 'ignore', stderr: 'pipe' })
515
+ if (p.exitCode === 0) return { passed: true }
516
+ const tail = p.stderr.toString().trim().split('\n').at(-1) ?? ''
517
+ return { passed: false, why: `exit ${p.exitCode}${tail !== '' ? `: ${tail}` : ''}` }
518
+ }
519
+
520
+ /** `in`: a credential ask closed because every value it names was stored after it was made */
521
+ export type OneCheck = { check: 'none' } | { check: 'passed' } | { check: 'in' } | { check: 'failed'; why: string }
522
+
523
+ async function checkOne(root: string, a: Ask, o: CloseOpts): Promise<OneCheck> {
524
+ if (await valuesIn(root, a, o)) {
525
+ setAskState(root, a, 'done', { who: 'agent', why: 'every value it asks for is stored' })
526
+ return { check: 'in' }
527
+ }
528
+ if (a.check == null) return { check: 'none' }
529
+ const r = probe(root, a.check)
530
+ if (!r.passed) return { check: 'failed', why: r.why }
531
+ setAskState(root, a, 'done', { who: 'agent', why: 'its check passes' })
532
+ return { check: 'passed' }
533
+ }
534
+
535
+ /** probe every open ask and close the ones that now pass. Under the repo's asks lease: two runs racing here would each
536
+ * spawn every probe, which reach the world; the loser waits and finds nothing left to close.
537
+ * Its lines, read by SK026: `closed <id> (<why>)`, `still open <id>`, `N closed` */
538
+ export async function checkAsks(root: string, print: (line: string) => void = console.log, o: CloseOpts = {}): Promise<{ closed: number }> {
539
+ const leased = await withMutateLease(mutateLease(root, 'asks'), { label: 'asks check', print, maxWaitMs: 45_000 }, async () => {
540
+ let closed = 0
541
+ for (const a of openAsks(root)) {
542
+ const r = await checkOne(root, a, o)
543
+ if (r.check === 'in' || r.check === 'passed') {
544
+ print(`closed ${a.id} (${r.check === 'in' ? 'every value is in' : 'its check passes'})`)
545
+ closed++
546
+ } else print(`still open ${a.id}${r.check === 'none' ? ' (no probe)' : ''}`)
547
+ }
548
+ print(`${closed} closed`)
549
+ return { closed }
550
+ })
551
+ if (leased.ok) return leased.value
552
+ print(`WARN asks check skipped: ${leased.warn}`)
553
+ return { closed: 0 }
554
+ }
555
+
556
+ /** checkAsks for one open ask: its values, then its probe alone, under the same lease */
557
+ export async function checkAsk(root: string, ref: string, o: CloseOpts = {}): Promise<OneCheck> {
558
+ const leased = await withMutateLease(mutateLease(root, 'asks'), { label: 'asks check', print: () => {}, maxWaitMs: 45_000 }, async (): Promise<OneCheck> => {
559
+ const a = openAsks(root).find((x) => x.id === askIdOf(ref))
560
+ return a == null ? { check: 'failed', why: `${askIdOf(ref)} is no longer an open ask` } : checkOne(root, a, o)
561
+ })
562
+ return leased.ok ? leased.value : { check: 'failed', why: `the check did not run: ${leased.warn}` }
563
+ }
564
+
565
+ /** the open asks, then the later ones under `later` with their day; returns the open count, the later ones out of it */
566
+ export function renderAsksTable(root: string, print: (line: string) => void = console.log, opts?: { emptyText?: string; now?: number }): number {
567
+ const now = opts?.now ?? Date.now()
568
+ const all = openAsks(root, new Date(now))
569
+ const open = all.filter((a) => !isLater(a, now))
570
+ const later = all.filter((a) => isLater(a, now)).sort((a, b) => a.afterAt! - b.afterAt!)
571
+ const row = (a: Ask): string => `${a.status.padEnd(9)} ${a.kind.padEnd(10)} ${a.id.padEnd(44)} blocks: ${a.blocks}`
572
+ if (open.length === 0) print(opts?.emptyText ?? 'no open asks — all caught up 🎉')
573
+ for (const a of open) print(row(a))
574
+ if (later.length > 0) {
575
+ print('\nlater')
576
+ for (const a of later) print(`${row(a)} ${afterWords(a.after!)}`)
577
+ }
578
+ if (open.length > 0 || later.length > 0) print(`\n${open.length} open${later.length > 0 ? `, ${later.length} later` : ''}: sk thread show ask:<id> shows one whole`)
579
+ return open.length
580
+ }
581
+
582
+ export const isAskId = (s: string): boolean => ID_RE.test(s)
583
+
584
+ /** every ask of a repo for a reader that walks many repos: none for a repo whose store holds nothing, read with no
585
+ * write to it */
586
+ export const asksOfRepo = (root: string, now = new Date()): Ask[] => (hasStore(storeDir(root)) ? listAsks(root, now) : [])