rvlib-shipkit 2.11.0 → 2.13.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 (298) hide show
  1. package/CHANGELOG.md +56 -12
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/check.ts +1 -1
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -0
  7. package/src/checks/SK003-claude-md-shape.check.ts +1 -1
  8. package/src/checks/SK004-gitignore-policy.check.ts +27 -2
  9. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  10. package/src/checks/SK008-reviewer-agent.check.ts +2 -2
  11. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  12. package/src/checks/SK015-nested-repo.check.ts +1 -1
  13. package/src/checks/SK035-public-clean.check.ts +46 -0
  14. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  15. package/src/cli/cmd_Backup.ts +152 -0
  16. package/src/cli/cmd_Ci.ts +8 -11
  17. package/src/cli/cmd_Drill.ts +145 -0
  18. package/src/cli/cmd_Home.ts +50 -3
  19. package/src/cli/cmd_Media.ts +96 -5
  20. package/src/cli/cmd_Review.ts +8 -2
  21. package/src/cli/cmd_Shot.ts +5 -2
  22. package/src/cli/cmd_Smoke.ts +4 -1
  23. package/src/cli/cmd_Social.ts +226 -0
  24. package/src/cli/cmd_Start.ts +1 -1
  25. package/src/cli/cmd_Time.ts +1 -1
  26. package/src/cli/cmd_Trailer.ts +9 -2
  27. package/src/cli/cmd_Veille.ts +173 -0
  28. package/src/cli/family-pages.ts +3 -0
  29. package/src/cli/registry.ts +13 -2
  30. package/src/cli.ts +5 -2
  31. package/src/collections/actions.ts +1 -49
  32. package/src/collections/checks.ts +2 -1
  33. package/src/collections/collection-types.ts +11 -2
  34. package/src/collections/providers.ts +4 -4
  35. package/src/collections/review.ts +2 -1
  36. package/src/collections/tests.ts +19 -8
  37. package/src/contracts/apply-contracts.ts +1 -3
  38. package/src/contracts/contract-manifests.ts +2 -3
  39. package/src/contracts/contract-types.ts +0 -1
  40. package/src/contracts/contracts-engine.ts +0 -3
  41. package/src/core/app-icon.ts +9 -3
  42. package/src/core/bun-builtins.ts +2 -2
  43. package/src/core/discover-checks.ts +37 -5
  44. package/src/core/fix-scope.ts +4 -2
  45. package/src/core/floor-resolve.ts +68 -48
  46. package/src/core/floor.ts +9 -0
  47. package/src/core/git-root.ts +24 -0
  48. package/src/core/last-good.ts +3 -1
  49. package/src/core/layout.ts +8 -0
  50. package/src/core/log-stamp.ts +36 -0
  51. package/src/core/loop-watch.ts +93 -0
  52. package/src/core/machine-link.ts +134 -0
  53. package/src/core/memory-watch.ts +41 -0
  54. package/src/core/one-way-in-policy.ts +27 -19
  55. package/src/core/run-ci.ts +6 -8
  56. package/src/core/run-fixers.ts +9 -9
  57. package/src/core/slots.ts +21 -0
  58. package/src/core/tree-rev.ts +60 -0
  59. package/src/core/unit-files.ts +42 -0
  60. package/src/drill/render.ts +140 -0
  61. package/src/drill/run.ts +269 -0
  62. package/src/fleet/scan-fleet.ts +6 -5
  63. package/src/home/daemon-jobs.ts +201 -0
  64. package/src/home/global-context.ts +34 -1
  65. package/src/home/home-routes.ts +22 -15
  66. package/src/home/hubs.ts +10 -3
  67. package/src/home/inbox-shape.ts +61 -6
  68. package/src/home/inbox.ts +75 -4
  69. package/src/home/lib-watch.ts +10 -3
  70. package/src/home/machine-stores.ts +15 -29
  71. package/src/home/run-daemon.ts +15 -18
  72. package/src/home/run-pm.ts +2 -0
  73. package/src/home/serve-daemon.ts +4 -3
  74. package/src/home/serve-web.ts +110 -1
  75. package/src/hooks/commit-message.ts +28 -19
  76. package/src/hooks/leak-guard.ts +10 -3
  77. package/src/hooks/run-hooks.ts +2 -6
  78. package/src/identities/identities.ts +334 -0
  79. package/src/identities/machine-route.ts +126 -0
  80. package/src/identities/machine.ts +62 -0
  81. package/src/init-repo.ts +1 -1
  82. package/src/ledger/check-stats.ts +10 -9
  83. package/src/ledger/gate-checks.ts +32 -1
  84. package/src/ledger/record-kept.ts +112 -0
  85. package/src/ledger/repo-view.ts +10 -0
  86. package/src/ledger/run-log.ts +17 -12
  87. package/src/ledger/run-timeline.ts +8 -4
  88. package/src/ledger/store.ts +7 -0
  89. package/src/ledger/suite-log.ts +17 -13
  90. package/src/media-kinds.ts +9 -1
  91. package/src/media-store/backup/daemon.ts +73 -0
  92. package/src/media-store/backup/keys.ts +25 -0
  93. package/src/media-store/backup/manifest.ts +193 -0
  94. package/src/media-store/backup/restore.ts +192 -0
  95. package/src/media-store/backup/run.ts +278 -0
  96. package/src/media-store/backup/secret.ts +86 -0
  97. package/src/media-store/backup/snapshot.ts +64 -0
  98. package/src/media-store/backup/sources.ts +199 -0
  99. package/src/media-store/content.ts +11 -1
  100. package/src/media-store/daemon.ts +56 -70
  101. package/src/media-store/hand.ts +58 -0
  102. package/src/media-store/put.ts +122 -0
  103. package/src/media-store/space.ts +73 -11
  104. package/src/pages/forward.ts +35 -0
  105. package/src/pages/frame-client.ts +118 -0
  106. package/src/pages/routes.ts +29 -0
  107. package/src/pages/unit.ts +92 -0
  108. package/src/plan/planner.ts +12 -0
  109. package/src/plan/repo-source.ts +19 -5
  110. package/src/reflect/transcript.ts +35 -10
  111. package/src/release/public-clean.ts +301 -0
  112. package/src/release/published-here.ts +22 -0
  113. package/src/release/run-bump.ts +2 -1
  114. package/src/release/run-release.ts +4 -1
  115. package/src/repo-config.ts +53 -2
  116. package/src/review/http.ts +16 -2
  117. package/src/review/media-kind.ts +3 -3
  118. package/src/review/media-read.ts +3 -3
  119. package/src/review/model.ts +24 -5
  120. package/src/review/notes.ts +77 -0
  121. package/src/review/project.ts +6 -38
  122. package/src/review/routes.ts +8 -13
  123. package/src/review/store.ts +46 -4
  124. package/src/review/trailer-media.ts +24 -3
  125. package/src/review/trailer-shots.ts +106 -0
  126. package/src/review/unit.ts +1 -1
  127. package/src/scaffold/files/agent-handoff.md +3 -0
  128. package/src/scaffold/files/agent-index.md +4 -12
  129. package/src/scaffold/project-scaffold.ts +5 -4
  130. package/src/serve/embed.ts +1 -1
  131. package/src/serve/hub-app/col-card.tsx +3 -17
  132. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  133. package/src/serve/hub-app/cols-svc.ts +12 -14
  134. package/src/serve/hub-app/dock-st.ts +4 -2
  135. package/src/serve/hub-app/dock-view.tsx +2 -0
  136. package/src/serve/hub-app/frames-st.ts +35 -0
  137. package/src/serve/hub-app/hash-route.ts +64 -1
  138. package/src/serve/hub-app/home-st.ts +31 -7
  139. package/src/serve/hub-app/home-strip.css +9 -1
  140. package/src/serve/hub-app/home-strip.tsx +7 -6
  141. package/src/serve/hub-app/home.html +5 -0
  142. package/src/serve/hub-app/hub-app.tsx +49 -5
  143. package/src/serve/hub-app/hub.css +29 -11
  144. package/src/serve/hub-app/icons.tsx +16 -1
  145. package/src/serve/hub-app/identities-st.ts +210 -0
  146. package/src/serve/hub-app/identities-view.tsx +352 -0
  147. package/src/serve/hub-app/identities.css +48 -0
  148. package/src/serve/hub-app/identity-address.ts +52 -0
  149. package/src/serve/hub-app/inbox-st.ts +59 -6
  150. package/src/serve/hub-app/inbox-view.tsx +48 -6
  151. package/src/serve/hub-app/inbox.css +12 -1
  152. package/src/serve/hub-app/index.html +3 -0
  153. package/src/serve/hub-app/keys.ts +10 -2
  154. package/src/serve/hub-app/list-walk.ts +89 -0
  155. package/src/serve/hub-app/machine-st.ts +12 -0
  156. package/src/serve/hub-app/media-view.tsx +2 -1
  157. package/src/serve/hub-app/pages-frames.tsx +134 -0
  158. package/src/serve/hub-app/pages-svc.ts +111 -0
  159. package/src/serve/hub-app/palette-st.ts +18 -3
  160. package/src/serve/hub-app/palette-view.tsx +9 -2
  161. package/src/serve/hub-app/planned-view.tsx +2 -1
  162. package/src/serve/hub-app/project-list.css +18 -14
  163. package/src/serve/hub-app/project-list.tsx +88 -49
  164. package/src/serve/hub-app/projects-svc.ts +33 -3
  165. package/src/serve/hub-app/repo-sections.ts +19 -2
  166. package/src/serve/hub-app/repo-st.ts +75 -19
  167. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  168. package/src/serve/hub-app/review/review-kit.ts +30 -7
  169. package/src/serve/hub-app/review/review-page.tsx +1 -1
  170. package/src/serve/hub-app/review/review-st.ts +33 -11
  171. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  172. package/src/serve/hub-app/review/review-views.tsx +84 -19
  173. package/src/serve/hub-app/review/thread-st.ts +1 -10
  174. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  175. package/src/serve/hub-app/review.css +17 -8
  176. package/src/serve/hub-app/site/site-part.tsx +173 -0
  177. package/src/serve/hub-app/site/site-st.ts +157 -0
  178. package/src/serve/hub-app/site.css +35 -0
  179. package/src/serve/hub-app/social/calendar.tsx +182 -0
  180. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  181. package/src/serve/hub-app/social/kit.tsx +244 -0
  182. package/src/serve/hub-app/social/post-card.tsx +456 -0
  183. package/src/serve/hub-app/social/problems.tsx +60 -0
  184. package/src/serve/hub-app/social/social-model.ts +154 -0
  185. package/src/serve/hub-app/social/social-page.tsx +674 -0
  186. package/src/serve/hub-app/social/social-st.ts +986 -0
  187. package/src/serve/hub-app/social.css +289 -0
  188. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  189. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  190. package/src/serve/hub-app/stores.css +54 -0
  191. package/src/serve/hub-app/test-view.tsx +9 -2
  192. package/src/serve/hub-app/tests-svc.ts +16 -1
  193. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  194. package/src/serve/hub-app/timeline-view.tsx +3 -2
  195. package/src/serve/hub-app/tree-build.ts +6 -0
  196. package/src/serve/hub-app/tree-row.tsx +27 -4
  197. package/src/serve/hub-app/tree-svc.ts +18 -49
  198. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  199. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  200. package/src/serve/hub-app/veille.css +84 -0
  201. package/src/serve/hub-runtime.ts +14 -9
  202. package/src/serve/project-gutter-route.ts +44 -12
  203. package/src/serve/resources-wire.ts +48 -0
  204. package/src/serve/run-lanes.ts +7 -4
  205. package/src/serve/same-origin.ts +1 -1
  206. package/src/serve/serve-hub.ts +27 -18
  207. package/src/serve/tracked-watch.ts +24 -3
  208. package/src/serve/warm-cell.ts +5 -1
  209. package/src/shipkit-files.ts +15 -4
  210. package/src/shipkit.ts +0 -1
  211. package/src/shot/box.ts +162 -0
  212. package/src/shot/browser-slot.ts +62 -0
  213. package/src/shot/client.ts +43 -7
  214. package/src/shot/clip-encoder.ts +93 -12
  215. package/src/shot/film-box.ts +188 -0
  216. package/src/shot/shooter.ts +50 -15
  217. package/src/shot/shot-ask.ts +10 -2
  218. package/src/shot/stepped-clip.ts +5 -4
  219. package/src/site/desk.ts +242 -0
  220. package/src/site/routes.ts +66 -0
  221. package/src/site/unit.ts +62 -0
  222. package/src/social/brands.ts +22 -0
  223. package/src/social/compose.ts +97 -0
  224. package/src/social/desk-index.ts +123 -0
  225. package/src/social/desk-wire.ts +64 -0
  226. package/src/social/drafts.ts +183 -0
  227. package/src/social/house.ts +24 -0
  228. package/src/social/load.ts +319 -0
  229. package/src/social/md.ts +70 -0
  230. package/src/social/media-facts.ts +53 -0
  231. package/src/social/media-kind.ts +189 -0
  232. package/src/social/media-limit.ts +42 -0
  233. package/src/social/media-of.ts +30 -0
  234. package/src/social/migrate.ts +123 -0
  235. package/src/social/open.ts +17 -0
  236. package/src/social/post-url.ts +158 -0
  237. package/src/social/presence.ts +332 -0
  238. package/src/social/public-read.ts +53 -0
  239. package/src/social/publish/bluesky.ts +168 -0
  240. package/src/social/publish/discord.ts +76 -0
  241. package/src/social/publish/index.ts +24 -0
  242. package/src/social/publish/secret.ts +13 -0
  243. package/src/social/push.ts +31 -0
  244. package/src/social/richtext.ts +37 -0
  245. package/src/social/routes.ts +180 -0
  246. package/src/social/stats.ts +134 -0
  247. package/src/social/text.ts +267 -0
  248. package/src/social/tracker-route.ts +39 -0
  249. package/src/social/tracker.ts +255 -0
  250. package/src/social/unit.ts +53 -0
  251. package/src/social/writes.ts +130 -0
  252. package/src/start-repo.ts +14 -9
  253. package/src/stores/collection.ts +27 -0
  254. package/src/stores/desk.ts +336 -0
  255. package/src/stores/model.ts +187 -0
  256. package/src/stores/routes.ts +126 -0
  257. package/src/stores/unit.ts +57 -0
  258. package/src/suite/calibrate.ts +127 -0
  259. package/src/suite/core-counters.ts +91 -0
  260. package/src/suite/judge-suites.ts +94 -34
  261. package/src/suite/suite-cli.ts +44 -10
  262. package/src/suite/suite-cpu-preload.ts +34 -9
  263. package/src/trailer/adapter.ts +4 -0
  264. package/src/trailer/build.ts +42 -11
  265. package/src/trailer/ffmpeg.ts +11 -0
  266. package/src/trailer/footage.ts +30 -13
  267. package/src/trailer/grammar.ts +18 -2
  268. package/src/trailer/graph.ts +28 -6
  269. package/src/trailer/passage.ts +21 -6
  270. package/src/trailer/plan.ts +74 -3
  271. package/src/trailer/shelf.ts +16 -0
  272. package/src/trailer/stitch.ts +67 -26
  273. package/src/trailer/url.ts +1 -1
  274. package/src/trailer/versions.ts +24 -0
  275. package/src/ts/gate-typecheck.ts +32 -0
  276. package/src/ts/typecheck-cli.ts +9 -11
  277. package/src/tui/tui-app.tsx +0 -1
  278. package/src/veille/asks.ts +155 -0
  279. package/src/veille/auto.ts +31 -0
  280. package/src/veille/batch.ts +27 -0
  281. package/src/veille/chrome.ts +127 -0
  282. package/src/veille/collection.ts +28 -0
  283. package/src/veille/desk.ts +242 -0
  284. package/src/veille/identity.ts +80 -0
  285. package/src/veille/import.ts +68 -0
  286. package/src/veille/log.ts +183 -0
  287. package/src/veille/platforms.ts +118 -0
  288. package/src/veille/reads.ts +66 -0
  289. package/src/veille/replied.ts +110 -0
  290. package/src/veille/routes.ts +185 -0
  291. package/src/veille/service.ts +81 -0
  292. package/src/veille/watch.ts +116 -0
  293. package/src/veille/worth.ts +46 -0
  294. package/src/wiki/scan-md.ts +18 -0
  295. package/src/collections/posts.ts +0 -142
  296. package/src/contracts/manifests/social.contract.ts +0 -20
  297. package/src/scaffold/files/agent-coding.md +0 -35
  298. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,267 @@
1
+ // a repo's public life as text (wiki build/shipkit/social.md, `sk social`): the overview and its views, and the page
2
+ // a repo may keep of it (`sk social state`), all read off one model (presence.ts) over the repo's identity. The page
3
+ // holds nothing that moves with the clock or a live API: those live in `sk social` alone
4
+ import type { DeskAccount, Desk } from './load.ts'
5
+ import { commitMoments, countBy, coverage, dayOf, dayRange, daysBetween, FAMILIES, familyOf, planOf, postedOf, rhythm, type Sent, unposted, weekday } from './presence.ts'
6
+ import type { StatsEntry } from './stats.ts'
7
+
8
+ /** the desk as the text views read it: the accounts of the speaking identity, the drafts it speaks, what was posted */
9
+ type Model = { social: Desk & { accounts: DeskAccount[] }; sent: Sent[] }
10
+
11
+ /** the model of one identity of the desk (default the repo's own): its accounts, the drafts it speaks, every post */
12
+ export const socialModel = (desk: Desk, identity = desk.speaksAs): Model => {
13
+ const accounts = desk.identities.find((i) => i.id === identity)?.accounts ?? []
14
+ const social = { ...desk, accounts, drafts: desk.drafts.filter((d) => d.identity === identity) }
15
+ return { social, sent: postedOf(social, commitMoments(social, desk.root)) }
16
+ }
17
+
18
+ /** the accounts a view lists: every one online, and any other a post went to; by family, then in their order */
19
+ const listed = ({ social, sent }: Model): DeskAccount[] =>
20
+ social.accounts
21
+ .filter((a) => a.live !== '' || sent.some((s) => s.platform === a.id))
22
+ .sort((a, b) => FAMILIES.indexOf(familyOf(a)) - FAMILIES.indexOf(familyOf(b)))
23
+
24
+ /** a hashtag as the platforms match it, whatever its case */
25
+ const tagsOf = (s: Sent): string[] => [...new Set(s.tags.map((t) => t.toLowerCase()))]
26
+
27
+ const pad = (s: string | number, n: number): string => String(s).padEnd(n)
28
+ const lpad = (s: string | number, n: number): string => String(s).padStart(n)
29
+ const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`
30
+ const bar = (n: number, max: number, width = 24): string => '█'.repeat(Math.max(n > 0 ? 1 : 0, Math.round((n / Math.max(max, 1)) * width)))
31
+
32
+ /** `name ████ n`, one line a key, the bars on one scale */
33
+ function bars(rows: readonly [string, number][], width = 24): string[] {
34
+ const w = Math.max(0, ...rows.map(([k]) => k.length))
35
+ const max = Math.max(0, ...rows.map(([, n]) => n))
36
+ return rows.map(([k, n]) => `${pad(k, w)} ${pad(bar(n, max, width), width)} ${lpad(n, 3)}`)
37
+ }
38
+
39
+ const WEEKDAY = new Intl.DateTimeFormat('en-GB', { timeZone: 'UTC', weekday: 'long' })
40
+ const TIME = new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/Paris', hour: '2-digit', minute: '2-digit' })
41
+ const SOURCE: Readonly<Record<Sent['source'], string>> = { id: 'from its id', commit: 'from the commit', page: "from the post's date", unknown: 'date unknown' }
42
+ const when = (s: Sent): string => (s.at == null ? 'date unknown' : `${dayOf(s.at)} ${TIME.format(s.at)} (${SOURCE[s.source]})`)
43
+
44
+ function headline({ social, sent }: Model): string {
45
+ const dated = sent.filter((s) => s.at != null).map((s) => dayOf(s.at!))
46
+ const span = dated.length ? `, ${dated[0]} to ${dated.at(-1)}` : ''
47
+ return `${plural(sent.length, 'post')} on ${plural(new Set(sent.map((s) => s.platform)).size, 'account')} from ${plural(new Set(sent.map((s) => s.slug)).size, 'draft')}${span}; ${plural(unposted(social, sent).length, 'draft')} written and not posted`
48
+ }
49
+
50
+ function sourcesLine(sent: readonly Sent[]): string {
51
+ const n = (src: Sent['source']): number => sent.filter((s) => s.source === src).length
52
+ const by = (src: Sent['source']): string => [...new Set(sent.filter((s) => s.source === src).map((s) => s.platform))].join(', ')
53
+ const parts = [`${n('id')} from the post's id`, `${n('commit')} from the commit that recorded it${n('commit') ? ` (${by('commit')})` : ''}`]
54
+ if (n('page')) parts.push(`${n('page')} from the devlog post's date`)
55
+ parts.push(`${n('unknown')} unknown${n('unknown') ? ` (${by('unknown')})` : ''}`)
56
+ return `dates: ${parts.join(', ')}`
57
+ }
58
+
59
+ /** a numbers cell: what a free public read gave, or « unknown » and why */
60
+ function numbersCell(a: DeskAccount, recorded: number, stats: Readonly<Record<string, StatsEntry>> | null, free: readonly string[]): string {
61
+ if (!free.includes(a.id)) return 'unknown (no free read)'
62
+ if (stats == null) return 'not asked (--offline)'
63
+ const e = stats[a.id]
64
+ if (e?.counts == null) return e ? `unknown (${e.line})` : 'unknown (not asked yet)'
65
+ const c = e.counts
66
+ const age = e.at == null ? '' : `, ${Math.round((Date.now() - e.at) / 60_000)} min ago`
67
+ const here = c.posts == null || c.posts === recorded ? '' : ` (${recorded} recorded in the drafts)`
68
+ return `${Object.entries(c)
69
+ .map(([k, v]) => `${v} ${k}`)
70
+ .join(', ')}${here}${age}`
71
+ }
72
+
73
+ /** `sk social`: where we stand, to read in ten seconds; `today` and the numbers are the clock's and the APIs' */
74
+ export function overviewText(m: Model, today: string, stats: Readonly<Record<string, StatsEntry>> | null, free: readonly string[]): string[] {
75
+ const { social, sent } = m
76
+ const out = [`Social: where we stand on ${WEEKDAY.format(Date.parse(`${today}T12:00:00Z`))} ${today}, Paris`, headline(m), '']
77
+ const week = new Set(dayRange(dayRangeStart(today, 7), today))
78
+ out.push(`${pad('account', 10)} ${pad('family', 7)} ${lpad('7 days', 6)} ${lpad('total', 5)} ${pad('last post', 10)} ${lpad('ago', 5)} public numbers`)
79
+ for (const a of listed(m)) {
80
+ const mine = sent.filter((s) => s.platform === a.id)
81
+ const dated = mine.filter((s) => s.at != null)
82
+ const last = dated.at(-1)
83
+ const lastDay = last ? dayOf(last.at!) : null
84
+ out.push(
85
+ `${pad(a.id, 10)} ${pad(familyOf(a), 7)} ${lpad(dated.filter((s) => week.has(dayOf(s.at!))).length, 6)} ${lpad(mine.length, 5)} ${pad(lastDay ?? 'never', 10)} ${lpad(lastDay ? `${daysBetween(lastDay, today)} d` : '', 5)} ${numbersCell(a, mine.length, stats, free)}`,
86
+ )
87
+ }
88
+ const r = rhythm(sent, today)
89
+ const last14 = dayRange(dayRangeStart(today, 14), today)
90
+ const posted = new Set(r.days)
91
+ out.push('', 'Rhythm, any account, the last 14 days:')
92
+ out.push(` ${last14.map((d) => d.slice(8)).join(' ')}`, ` ${last14.map((d) => ` ${posted.has(d) ? '▮' : '·'}`).join(' ')}`)
93
+ const since = r.days[0] ? daysBetween(r.days[0], today) + 1 : 0
94
+ out.push(
95
+ ` ${plural(r.days.length, 'day')} with a post of the ${since} since the first; streak ${plural(r.streak, 'day')}; longest gap ${r.gap ? `${plural(r.gap.days, 'day')} (${r.gap.from} to ${r.gap.to})` : 'none'}`,
96
+ )
97
+ out.push('', 'Posts by kind (the draft\'s kind):', ...bars(countBy(sent, (s) => [s.kind || '(none)'])).map((l) => ` ${l}`))
98
+ out.push('', 'Posts by topic:', ...bars(countBy(sent, (s) => (s.topics.length ? s.topics : ['(no topics)']))).map((l) => ` ${l}`))
99
+ const never = social.topics.filter((t) => !sent.some((s) => s.topics.includes(t)))
100
+ if (never.length) out.push(` never posted: ${never.join(', ')}`)
101
+ const tags = countBy(sent, tagsOf)
102
+ out.push('', `Hashtags, on ${plural(sent.filter((s) => s.tags.length).length, 'post')} that carry any:`, ` ${tags.map(([t, n]) => `${t} ${n}`).join(' ') || 'none'}`)
103
+ const waiting = unposted(social, sent)
104
+ out.push('', `Drafts not posted (${waiting.length}), the newest first: sk social post <draft>`)
105
+ for (const d of waiting.slice(0, 8)) out.push(` ${pad(d.slug, 46)} ${pad(d.kind, 12)} ${d.topics.join(', ')}`)
106
+ if (waiting.length > 8) out.push(` … and ${waiting.length - 8} more: sk social plan`)
107
+ out.push('', sourcesLine(sent))
108
+ if (social.errors.length) out.push('', `${plural(social.errors.length, 'error')} in .shipkit/social/:`, ...social.errors.map((e) => ` ${e}`))
109
+ return out
110
+ }
111
+
112
+ /** the first of the `n` days that end on `today` */
113
+ const dayRangeStart = (today: string, n: number): string => new Date(Date.parse(`${today}T00:00:00Z`) - (n - 1) * 86_400_000).toISOString().slice(0, 10)
114
+
115
+ /** one row an account, one column a day, the posts of each cell; a column of 3 up to 31 days, else of 1 */
116
+ export function timelineText(m: Model, from: string, to: string): string[] {
117
+ const days = dayRange(from, to)
118
+ const wide = days.length <= 31
119
+ const cell = (n: number): string => (wide ? lpad(n ? String(n) : '·', 3) : n ? (n > 9 ? '+' : String(n)) : '·')
120
+ const head = (f: (d: string) => string): string => `${pad('', 10)}${days.map((d) => (wide ? lpad(f(d), 3) : f(d).slice(-1))).join('')}`
121
+ const out = wide
122
+ ? [head((d) => d.slice(8)), head(weekday)]
123
+ : [head((d) => d.slice(8, 9)), head((d) => d.slice(9))]
124
+ const rows = listed(m).map((a) => {
125
+ const n = new Map<string, number>()
126
+ for (const s of m.sent) if (s.platform === a.id && s.at != null) n.set(dayOf(s.at), (n.get(dayOf(s.at)) ?? 0) + 1)
127
+ return `${pad(a.id, 10)}${days.map((d) => cell(n.get(d) ?? 0)).join('')}`
128
+ })
129
+ const all = new Map<string, number>()
130
+ for (const s of m.sent) if (s.at != null) all.set(dayOf(s.at), (all.get(dayOf(s.at)) ?? 0) + 1)
131
+ return [...out, ...rows, `${pad('all', 10)}${days.map((d) => cell(all.get(d) ?? 0)).join('')}`]
132
+ }
133
+
134
+ /** the topics against the families: the drafts posted in each, the drafts waiting, then the gaps by name */
135
+ export function coverageText(m: Model): string[] {
136
+ const rows = coverage(m.social, m.sent)
137
+ const cols = [...FAMILIES, 'waiting'] as const
138
+ const cell = (n: number): string => lpad(n ? String(n) : '·', 8)
139
+ const out = [`${pad('topic', 12)}${cols.map((c) => lpad(c, 8)).join('')}`]
140
+ for (const r of rows) out.push(`${pad(r.topic, 12)}${FAMILIES.map((f) => cell(r.families[f])).join('')}${cell(r.waiting)}`)
141
+ out.push('', 'drafts a topic reached in each family (a draft counts once a family); waiting: written, posted nowhere', '', ...coverageGaps(rows))
142
+ return out
143
+ }
144
+
145
+ function coverageGaps(rows: ReturnType<typeof coverage>): string[] {
146
+ const none = (f: (r: (typeof rows)[number]) => boolean): string => rows.filter(f).map((r) => r.topic).join(', ') || 'none'
147
+ return [
148
+ `never posted: ${none((r) => FAMILIES.every((f) => r.families[f] === 0))}`,
149
+ `never on the feed: ${none((r) => r.families.feed === 0)}`,
150
+ `never on the shorts: ${none((r) => r.families.shorts === 0)}`,
151
+ `written, never posted: ${none((r) => r.waiting > 0 && FAMILIES.every((f) => r.families[f] === 0))}`,
152
+ ]
153
+ }
154
+
155
+ /** one draft across every account its headings reach */
156
+ export function postText(m: Model, slug: string): string[] {
157
+ const d = m.social.drafts.find((x) => x.slug === slug)
158
+ if (d == null) return [`no draft ${slug}`]
159
+ const out = [`${d.slug}: ${d.title}`, `kind ${d.kind || '(none)'}, status ${d.status}, topics ${d.topics.join(', ') || '(none)'}${d.article ? `, devlog post ${d.article.draft ? 'in draft' : d.article.date}` : ''}`, '']
160
+ const family = new Map(m.social.accounts.map((a) => [a.id, familyOf(a)]))
161
+ const fam = (p: (typeof d.posts)[number]): (typeof FAMILIES)[number] => family.get(p.platform) ?? 'other'
162
+ const posts = [...d.posts].sort((x, y) => FAMILIES.indexOf(fam(x)) - FAMILIES.indexOf(fam(y)))
163
+ const w = Math.max(0, ...posts.map((p) => p.key.length))
164
+ for (const p of posts) {
165
+ const s = m.sent.find((x) => x.slug === d.slug && x.key === p.key)
166
+ out.push(`${pad(p.key, w)} ${pad(fam(p), 7)} ${s ? `posted ${when(s)} ${s.url}` : `waiting, ${p.length} characters${p.tags.length ? `, ${p.tags.join(' ')}` : ''}`}`)
167
+ }
168
+ const left = d.posts.filter((p) => p.posted === '').length
169
+ out.push('', left ? `${left} of ${d.posts.length} messages waiting` : `every message posted`)
170
+ const errors = m.social.errors.filter((e) => e.includes(d.slug))
171
+ if (errors.length) out.push('', ...errors)
172
+ return out
173
+ }
174
+
175
+ const SHORT_DAY = new Intl.DateTimeFormat('en-GB', { timeZone: 'UTC', weekday: 'short' })
176
+ /** `Wed 10-28` */
177
+ const dayName = (day: string): string => `${SHORT_DAY.format(Date.parse(`${day}T12:00:00Z`))} ${day.slice(5)}`
178
+
179
+ /** `sk social plan`: the next 7 days, each slot of the rhythm with its draft or « empty », the missed, the ready */
180
+ export function planText(m: Model, today: string): string[] {
181
+ const { social, sent } = m
182
+ const p = planOf(social, sent, today)
183
+ const draft = new Map(social.drafts.map((d) => [d.slug, d]))
184
+ const line = (slug: string): string => {
185
+ const d = draft.get(slug)
186
+ if (d == null) return slug
187
+ const posted = d.posts.filter((x) => x.posted !== '').length
188
+ return `${pad(d.slug, 46)} ${pad(d.kind || '(none)', 9)} ${pad(`${posted}/${d.posts.length} posted`, 12)} ${d.title}`
189
+ }
190
+ const out = [`The week ahead, ${dayName(p.from)} to ${dayName(p.to)} ${p.to.slice(0, 4)}, Paris: .shipkit/social/rhythm.md`, '']
191
+ if (social.weekly.length === 0) out.push(' no slot: .shipkit/social/rhythm.md holds none')
192
+ const w = Math.max(0, ...p.slots.map((x) => x.slot.tag.length))
193
+ for (const x of p.slots) {
194
+ const when = x.slot.day === 'week' ? `week of ${dayName(x.day)}` : `${dayName(x.day)} ${pad(x.slot.time, 5)}`
195
+ const [first, ...more] = x.drafts
196
+ out.push(` ${pad(when, 18)} ${pad(x.slot.tag, w)} ${first == null ? 'empty' : line(first)}`)
197
+ for (const slug of more) out.push(` ${pad('', 18)} ${pad('', w)} ${line(slug)}`)
198
+ }
199
+ out.push('', `Slotted, the day passed, posted nowhere (${p.missed.length})${p.missed.length ? ': move its slot or post it' : ''}`, ...p.missed.map((s) => ` ${draft.get(s)?.slot?.day ?? ''} ${line(s)}`))
200
+ out.push('', `Ready, no slot (${p.ready.length}), picked first, then the newest: slot: <YYYY-MM-DD> <tag> in its draft.md`, ...p.ready.map((s) => ` ${line(s)}`))
201
+ return out
202
+ }
203
+
204
+ /** the page: the same model with no number that moves with the clock or a live API */
205
+ export function socialStateText(m: Model): string {
206
+ const { social, sent } = m
207
+ const dated = sent.filter((s) => s.at != null)
208
+ const lines = [
209
+ '# Social: where we stand',
210
+ '',
211
+ `Generated by \`sk social state\` from the drafts of \`.shipkit/social/\`, the accounts of ${social.identities.find((i) => i.id === social.speaksAs)?.name ?? 'its identity'} and the commits that recorded each post. Never edit it by hand. Today's numbers (the last 7 days, the days since, the streak, the followers): \`sk social\`; one draft: \`sk social post <draft>\`.`,
212
+ '',
213
+ `- ${headline(m)}`,
214
+ `- ${sourcesLine(sent)}`,
215
+ `- a day is a day in Paris; a family is the accounts' group: \`feed\` (group \`short\`), \`shorts\` (group \`vertical\`), \`other\``,
216
+ '',
217
+ '## Accounts',
218
+ '',
219
+ '| account | family | posts | first | last | hashtags used most |',
220
+ '|---|---|---:|---|---|---|',
221
+ ]
222
+ for (const a of listed(m)) {
223
+ const mine = sent.filter((s) => s.platform === a.id)
224
+ const d = mine.filter((s) => s.at != null).map((s) => dayOf(s.at!))
225
+ const tags = countBy(mine, tagsOf)
226
+ .slice(0, 3)
227
+ .map(([t, n]) => `${t} ${n}`)
228
+ .join(', ')
229
+ lines.push(`| ${a.id} | ${familyOf(a)} | ${mine.length} | ${d[0] ?? 'never'} | ${d.at(-1) ?? 'never'} | ${tags} |`)
230
+ }
231
+ const days = [...new Set(dated.map((s) => dayOf(s.at!)))]
232
+ lines.push('', '## Timeline', '')
233
+ if (days.length) {
234
+ lines.push('```mermaid', 'timeline', ' title Posts a day, by account')
235
+ for (const day of days.slice(-21)) {
236
+ const by = countBy(
237
+ dated.filter((s) => dayOf(s.at!) === day),
238
+ (s) => [s.platform],
239
+ )
240
+ lines.push(` ${day} : ${by.map(([p, n]) => `${p} ${n}`).join(' : ')}`)
241
+ }
242
+ lines.push('```', '')
243
+ const last = days.at(-1)!
244
+ const first = days[0]! > dayRangeStart(last, 28) ? days[0]! : dayRangeStart(last, 28)
245
+ lines.push(`Posts a day, ${first} to ${last} (at most the 28 days up to the last post):`, '', '```text', ...timelineText(m, first, last), '```', '')
246
+ const r = rhythm(sent, last)
247
+ lines.push(`${plural(r.days.length, 'day')} with a post; the longest gap ${r.gap ? `${plural(r.gap.days, 'day')} (${r.gap.from} to ${r.gap.to})` : 'none'}.`, '')
248
+ } else lines.push('No post yet.', '')
249
+ const kinds = countBy(sent, (s) => [s.kind || '(none)'])
250
+ lines.push('## Kinds', '')
251
+ if (kinds.length) lines.push('```mermaid', 'pie title Posts by kind', ...kinds.map(([k, n]) => ` "${k}" : ${n}`), '```', '')
252
+ lines.push('## Topics against families', '', '| topic | feed | shorts | other | waiting |', '|---|---:|---:|---:|---:|')
253
+ const rows = coverage(social, sent)
254
+ for (const r of rows) lines.push(`| ${r.topic} | ${FAMILIES.map((f) => r.families[f] || '').join(' | ')} | ${r.waiting || ''} |`)
255
+ lines.push('', 'Drafts a topic reached in each family (a draft counts once a family); waiting: written, posted nowhere.', '', ...coverageGaps(rows).map((l) => `- ${l}`), '')
256
+ const tags = countBy(sent, tagsOf)
257
+ lines.push('## Hashtags', '', '```text', ...(tags.length ? bars(tags) : ['none']), '```', '')
258
+ const waiting = unposted(social, sent)
259
+ lines.push(`## Drafts not posted (${waiting.length})`, '')
260
+ const family = new Map(social.accounts.map((a) => [a.id, familyOf(a)]))
261
+ // a family by its name, an account outside both by its own
262
+ const reach = (d: (typeof waiting)[number]): string[] => [...new Set(d.posts.map((p) => (family.get(p.platform) === 'other' ? p.platform : family.get(p.platform)!)))]
263
+ for (const d of waiting) lines.push(`- \`${d.slug}\` ${d.kind || '(no kind)'}; ${d.topics.join(', ') || 'no topics'}; to ${reach(d).join(', ') || 'no account'}`)
264
+ lines.push('')
265
+ return lines.join('\n')
266
+ }
267
+
@@ -0,0 +1,39 @@
1
+ // the post tracker's machine routes, for the extension in an identity's Chrome profile (wiki build/shipkit/social.md,
2
+ // The post tracker): its rules, a url it saw, the links it read on our profile, each step of a check. Only the extension
3
+ // sends `x-post-tracker` (a page elsewhere cannot without a preflight nobody answers), its `x-shipkit-profile` names the
4
+ // profile's email, the email names the identity. null: not a path of these
5
+ import { loadIdentities } from '../identities/identities.ts'
6
+ import { bad, NO_STORE } from '../review/http.ts'
7
+ import { debug, profileRead, seenUrl, trackerRules } from './tracker.ts'
8
+
9
+ const PREFIX = '/api/social/tracker/'
10
+
11
+ export async function postTrackerRoute(req: Request, path: string): Promise<Response | null> {
12
+ if (!path.startsWith(PREFIX)) return null
13
+ if (req.headers.get('x-post-tracker') !== '1') return bad('x-post-tracker?', 403)
14
+ const email = (req.headers.get('x-shipkit-profile') ?? '').toLowerCase()
15
+ const identity = (await loadIdentities()).identities.find((i) => email !== '' && i.rows.some((r) => r.field === 'email' && r.value.toLowerCase() === email))
16
+ if (identity == null) return bad(`this Chrome profile (${email || 'signed in nowhere'}) is no identity's: its email is no identity.md's email`, 403)
17
+ const at = path.slice(PREFIX.length)
18
+ try {
19
+ if (at === 'rules' && req.method === 'GET') return Response.json({ ok: true, ...(await trackerRules(identity.id)) }, { headers: NO_STORE })
20
+ if (req.method !== 'POST') return bad(`${req.method} ${path}?`, 405)
21
+ const b = (await req.json().catch(() => ({}))) as { url?: unknown; at?: unknown; platform?: unknown; step?: unknown; detail?: unknown; urls?: unknown }
22
+ if (at === 'seen') {
23
+ if (typeof b.url !== 'string') return bad('{ url } expected')
24
+ return Response.json({ ok: true, result: await seenUrl(identity.id, b.url, typeof b.at === 'number' ? b.at : Date.now()) }, { headers: NO_STORE })
25
+ }
26
+ const platform = String(b.platform ?? '?').slice(0, 40)
27
+ if (at === 'debug') {
28
+ debug(platform, String(b.step ?? '?').slice(0, 40), String(b.detail ?? '').slice(0, 2000))
29
+ return Response.json({ ok: true }, { headers: NO_STORE })
30
+ }
31
+ if (at === 'profile-read') {
32
+ const urls = Array.isArray(b.urls) ? b.urls.filter((u): u is string => typeof u === 'string').slice(0, 200) : []
33
+ return Response.json({ ok: true, ...(await profileRead(identity.id, platform, urls)) }, { headers: NO_STORE })
34
+ }
35
+ return bad(`no route POST ${path}`, 404)
36
+ } catch (e) {
37
+ return bad(e)
38
+ }
39
+ }
@@ -0,0 +1,255 @@
1
+ // the post tracker (wiki build/shipkit/social.md, The post tracker): the message last opened per identity and platform,
2
+ // the post urls seen since (the account's public read, the extension in the identity's Chrome profile, a copy of that
3
+ // profile's History), each written on its line or kept as « seen » until he says where it goes. Machine level: the
4
+ // state lives in the home folder, an open names the repo whose draft it is
5
+ import { Database } from 'bun:sqlite'
6
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { homedir, tmpdir } from 'node:os'
8
+ import { dirname, join } from 'node:path'
9
+ import { homeDir } from '../home/home-paths.ts'
10
+ import { loadIdentities, type Account } from '../identities/identities.ts'
11
+ import { chromeProfile } from '../veille/chrome.ts'
12
+ import type { Desk } from './load.ts'
13
+ import { openDesk } from './open.ts'
14
+ import { matchPost, type PostMatch, postTime, profileChecks, trackRules } from './post-url.ts'
15
+ import { hasPublicRead, POLL_AT_MS, publicPosts } from './public-read.ts'
16
+ import { setPosted } from './writes.ts'
17
+
18
+ /** an open counts this long: a post seen later is no longer taken for it */
19
+ export const OPEN_FRESH_MS = 30 * 60_000
20
+ /** « search » with no open on record looks this far back */
21
+ export const HISTORY_BACK_MS = 24 * 3600_000
22
+ /** a post's time may run a little ahead of the machine's clock */
23
+ const CLOCK_SLACK_MS = 60_000
24
+
25
+ export type Open = { root: string; slug: string; key: string; at: number }
26
+ export type Seen = { identity: string; platform: string; url: string; at: number }
27
+ export type TrackerState = { opens: Record<string, Open>; seen: Seen[] }
28
+ type Post = { slug: string; key: string; platform: string; posted: string }
29
+ export type Decision = { kind: 'record'; slug: string; key: string } | { kind: 'seen' } | { kind: 'known' } | { kind: 'drop' }
30
+
31
+ const file = (): string => join(homeDir(), 'social-tracker.json')
32
+ const logFile = (): string => join(homeDir(), 'post-tracker.log')
33
+ const openKey = (identity: string, platform: string): string => `${identity}/${platform}`
34
+
35
+ /** where a post url goes: on the line opened moments ago, else « seen » (our account for sure), else nowhere; a url
36
+ * already on a line or already waiting is never taken twice, and a line with a url is never written over */
37
+ export function decide(m: PostMatch, at: number, open: Open | undefined, seen: readonly Seen[], posts: readonly Post[], canon: (url: string) => string): Decision {
38
+ if (posts.some((p) => p.posted !== '' && canon(p.posted) === m.url) || seen.some((s) => s.url === m.url)) return { kind: 'known' }
39
+ const target = open && at >= open.at && at - open.at <= OPEN_FRESH_MS ? posts.find((p) => p.slug === open.slug && p.key === open.key) : undefined
40
+ if (target && target.posted === '') return { kind: 'record', slug: target.slug, key: target.key }
41
+ return m.sure ? { kind: 'seen' } : { kind: 'drop' }
42
+ }
43
+
44
+ let state: TrackerState | null = null
45
+ /** moves at every write of a line: a page fetches its desk again */
46
+ let stamp = 0
47
+ const debugLines: Record<string, string[]> = {}
48
+
49
+ function load(): TrackerState {
50
+ if (state) return state
51
+ try {
52
+ const raw = JSON.parse(readFileSync(file(), 'utf8')) as Partial<TrackerState>
53
+ state = { opens: raw.opens ?? {}, seen: raw.seen ?? [] }
54
+ } catch {
55
+ state = { opens: {}, seen: [] }
56
+ }
57
+ // a restart keeps the polls of a fresh open
58
+ for (const [k, open] of Object.entries(state.opens)) schedulePolls(k, open)
59
+ return state
60
+ }
61
+
62
+ function save(): void {
63
+ mkdirSync(dirname(file()), { recursive: true })
64
+ writeFileSync(file(), JSON.stringify(load(), null, 2))
65
+ }
66
+
67
+ /** one step of a check (the extension's or the desk's): a line of the home's post-tracker.log, and the tooltip */
68
+ export function debug(platform: string, step: string, detail: string): void {
69
+ const line = `${new Date().toISOString()} ${platform} ${step}: ${detail}`
70
+ debugLines[platform] = [...(debugLines[platform] ?? []), line.slice(11, 19) + line.slice(24)].slice(-8)
71
+ try {
72
+ mkdirSync(dirname(logFile()), { recursive: true })
73
+ appendFileSync(logFile(), `${line}\n`)
74
+ } catch (e) {
75
+ console.error(`FAIL post tracker: ${logFile()} not written: ${(e as Error).message}`)
76
+ }
77
+ }
78
+
79
+ /** what a desk shows: the urls of an identity waiting, the stamp, the last check steps */
80
+ export const trackerView = (identity: string): { seen: Seen[]; stamp: number; debug: Record<string, string[]> } => ({ seen: load().seen.filter((s) => s.identity === identity), stamp, debug: debugLines })
81
+
82
+ const accountsOf = (desk: Desk, identity: string): Account[] => desk.identities.find((i) => i.id === identity)?.accounts ?? []
83
+ const guildOf = (accounts: readonly Account[]): string => accounts.find((a) => a.id === 'discord')?.guild ?? ''
84
+ const postsOf = (desk: Desk, identity: string): Post[] => desk.drafts.filter((d) => d.identity === identity).flatMap((d) => d.posts)
85
+
86
+ /** the identity's accounts, machine level: no repo needed to match a url */
87
+ async function identityAccounts(identity: string): Promise<Account[]> {
88
+ return (await loadIdentities()).identities.find((i) => i.id === identity)?.accounts ?? []
89
+ }
90
+
91
+ /** one url seen at `at`, for an identity: matched, decided, written in the open's repo (or `root`'s), or kept */
92
+ async function ingest(identity: string, url: string, at: number, root?: string): Promise<Decision['kind'] | 'other'> {
93
+ const accounts = await identityAccounts(identity)
94
+ const m = matchPost(url, accounts, guildOf(accounts))
95
+ if (m == null) return 'other'
96
+ const s = load()
97
+ const open = s.opens[openKey(identity, m.platform)]
98
+ const where = root ?? open?.root
99
+ const desk = where == null ? null : (await openDesk(where)).desk
100
+ const posts = desk == null ? [] : postsOf(desk, identity)
101
+ const canon = (u: string): string => matchPost(u, accounts, guildOf(accounts))?.url ?? u
102
+ const d = decide(m, at, open != null && desk != null && open.root === desk.root ? open : undefined, s.seen, posts, canon)
103
+ if (d.kind === 'record' && desk != null) {
104
+ setPosted(desk, d.slug, d.key, m.url)
105
+ stamp++
106
+ } else if (d.kind === 'seen') {
107
+ s.seen.push({ identity, platform: m.platform, url: m.url, at })
108
+ save()
109
+ }
110
+ return d.kind
111
+ }
112
+
113
+ /** « Post » or « Open all » opened a message's compose page: a post of that platform seen next goes to its line */
114
+ export function noteOpen(root: string, identity: string, platform: string, slug: string, key: string, at = Date.now()): void {
115
+ const k = openKey(identity, platform)
116
+ const open = { root, slug, key, at }
117
+ load().opens[k] = open
118
+ save()
119
+ schedulePolls(k, open)
120
+ }
121
+
122
+ const polls = new Map<string, ReturnType<typeof setTimeout>>()
123
+ const sameOpen = (a: Open | undefined, b: Open): boolean => a != null && a.at === b.at && a.slug === b.slug && a.key === b.key && a.root === b.root
124
+
125
+ /** the public reads of a platform that has one, at POLL_AT_MS after the open; a newer open replaces them */
126
+ function schedulePolls(k: string, open: Open): void {
127
+ const [identity = '', platform = ''] = k.split('/')
128
+ if (!hasPublicRead(platform)) return
129
+ clearTimeout(polls.get(k))
130
+ polls.delete(k)
131
+ const due = POLL_AT_MS.map((ms) => open.at + ms).filter((t) => t > Date.now())
132
+ const next = (): void => {
133
+ const t = due.shift()
134
+ if (t == null) return void polls.delete(k)
135
+ const timer = setTimeout(() => void poll(identity, platform, open).then((done) => (done ? polls.delete(k) : next())), t - Date.now())
136
+ timer.unref?.()
137
+ polls.set(k, timer)
138
+ }
139
+ next()
140
+ }
141
+
142
+ /** one public read of the account; true once there is nothing left to wait for */
143
+ async function poll(identity: string, platform: string, open: Open): Promise<boolean> {
144
+ if (!sameOpen(load().opens[openKey(identity, platform)], open)) return true
145
+ try {
146
+ const { desk } = await openDesk(open.root)
147
+ const target = postsOf(desk, identity).find((p) => p.slug === open.slug && p.key === open.key)
148
+ const a = accountsOf(desk, identity).find((x) => x.id === platform)
149
+ if (target == null || target.posted !== '' || a == null) return true
150
+ const posts = ((await publicPosts(a)) ?? []).filter((x) => x.at >= open.at - CLOCK_SLACK_MS)
151
+ let done = false
152
+ for (const p of posts.sort((x, y) => x.at - y.at)) if ((await ingest(identity, p.url, Math.max(p.at, open.at), open.root)) === 'record') done = true
153
+ return done
154
+ } catch (e) {
155
+ console.error(`FAIL post tracker: the public read of ${platform}: ${(e as Error).message}`)
156
+ return false
157
+ }
158
+ }
159
+
160
+ /** the extension's rules for one identity: the patterns of its accounts, the profile checks, the opens still waiting */
161
+ export async function trackerRules(identity: string): Promise<{ flags: string; rules: unknown; checks: unknown; opens: Record<string, number> }> {
162
+ const s = load()
163
+ const now = Date.now()
164
+ const opens: Record<string, number> = {}
165
+ const accounts = await identityAccounts(identity)
166
+ for (const [k, o] of Object.entries(s.opens)) {
167
+ const [id, platform = ''] = k.split('/')
168
+ if (id !== identity || now - o.at > OPEN_FRESH_MS) continue
169
+ const { desk } = await openDesk(o.root)
170
+ if (postsOf(desk, identity).some((p) => p.slug === o.slug && p.key === o.key && p.posted === '')) opens[platform] = o.at
171
+ }
172
+ return { flags: 'i', rules: trackRules(accounts, guildOf(accounts)), checks: profileChecks(accounts), opens }
173
+ }
174
+
175
+ /** a url the extension saw in the identity's profile */
176
+ export async function seenUrl(identity: string, url: string, at: number): Promise<string> {
177
+ const now = Date.now()
178
+ return ingest(identity, url, at <= now && at > now - HISTORY_BACK_MS ? at : now)
179
+ }
180
+
181
+ /** the links read on our profile: the newest post of ours made since the open, dated by its id, taken as any url;
182
+ * `done` false asks the extension to read again */
183
+ export async function profileRead(identity: string, platform: string, urls: readonly string[]): Promise<{ done: boolean; result: string }> {
184
+ const open = load().opens[openKey(identity, platform)]
185
+ if (open == null || Date.now() - open.at > OPEN_FRESH_MS) {
186
+ debug(platform, 'profile read', 'no open waiting for a url: nothing to do')
187
+ return { done: true, result: 'no-open' }
188
+ }
189
+ const { desk } = await openDesk(open.root)
190
+ const accounts = accountsOf(desk, identity)
191
+ if (!postsOf(desk, identity).some((p) => p.slug === open.slug && p.key === open.key && p.posted === '')) return { done: true, result: 'no-open' }
192
+ const dated = [...new Set(urls)].flatMap((u) => {
193
+ const m = matchPost(u, accounts, guildOf(accounts))
194
+ const at = m && m.platform === platform && m.sure ? postTime(platform, m.url) : null
195
+ return m && at != null ? [{ url: m.url, at }] : []
196
+ })
197
+ const fresh = dated.filter((o) => o.at >= open.at - CLOCK_SLACK_MS).sort((x, y) => y.at - x.at)
198
+ debug(platform, 'profile read', `${urls.length} links, ${dated.length} dated posts of ours, ${fresh.length} since the open`)
199
+ const newest = fresh[0]
200
+ if (newest == null) return { done: false, result: 'none-yet' }
201
+ const kind = await ingest(identity, newest.url, Math.max(newest.at, open.at), open.root)
202
+ debug(platform, 'profile read', `${newest.url}: ${kind}`)
203
+ return { done: true, result: kind }
204
+ }
205
+
206
+ /** « here »: a waiting url written on a line he names; « ✕ »: forgotten */
207
+ export function settleSeen(desk: Desk, url: string, to: { slug: string; key: string } | null): void {
208
+ const s = load()
209
+ const seen = s.seen.find((x) => x.url === url)
210
+ if (seen == null) throw new Error(`${url} no longer waits`)
211
+ if (to != null) {
212
+ setPosted(desk, to.slug, to.key, url)
213
+ stamp++
214
+ }
215
+ s.seen = s.seen.filter((x) => x !== seen)
216
+ save()
217
+ }
218
+
219
+ const CHROME_DIR = join(homedir(), 'Library/Application Support/Google/Chrome')
220
+ /** Chrome counts microseconds from 1601 */
221
+ const EPOCH_GAP_MS = 11_644_473_600_000
222
+
223
+ /** every url the profile visited since `since`, read from a COPY of its History (the live file is never opened) */
224
+ export function historyUrls(profileDir: string, since: number): { url: string; at: number }[] {
225
+ const src = join(CHROME_DIR, profileDir, 'History')
226
+ if (!existsSync(src)) throw new Error(`no Chrome History in ${profileDir}`)
227
+ const tmp = mkdtempSync(join(tmpdir(), 'post-tracker-'))
228
+ try {
229
+ for (const f of ['History', 'History-wal', 'History-journal']) if (existsSync(join(CHROME_DIR, profileDir, f))) copyFileSync(join(CHROME_DIR, profileDir, f), join(tmp, f))
230
+ const db = new Database(join(tmp, 'History'))
231
+ try {
232
+ const rows = db.query('SELECT url, last_visit_time AS t FROM urls WHERE last_visit_time > ?').all((since + EPOCH_GAP_MS) * 1000) as { url: string; t: number }[]
233
+ return rows.map((r) => ({ url: r.url, at: Math.round(r.t / 1000 - EPOCH_GAP_MS) }))
234
+ } finally {
235
+ db.close()
236
+ }
237
+ } finally {
238
+ rmSync(tmp, { recursive: true, force: true })
239
+ }
240
+ }
241
+
242
+ /** « search »: the identity profile's History since the platform's last open (else the last day), each url of that
243
+ * platform taken as any url; the counts by what became of them */
244
+ export async function searchHistory(desk: Desk, identity: string, platform: string): Promise<Record<string, number>> {
245
+ const email = desk.identities.find((i) => i.id === identity)?.rows.find((r) => r.field === 'email')?.value ?? ''
246
+ const since = load().opens[openKey(identity, platform)]?.at ?? Date.now() - HISTORY_BACK_MS
247
+ const accounts = accountsOf(desk, identity)
248
+ const counts: Record<string, number> = {}
249
+ for (const u of historyUrls(chromeProfile(email), since).sort((x, y) => x.at - y.at)) {
250
+ if (matchPost(u.url, accounts, guildOf(accounts))?.platform !== platform) continue
251
+ const kind = await ingest(identity, u.url, u.at, desk.root)
252
+ counts[kind] = (counts[kind] ?? 0) + 1
253
+ }
254
+ return counts
255
+ }
@@ -0,0 +1,53 @@
1
+ // a repo's own parts of the social desks (wiki build/shipkit/social.md, A project's parts), declared once in a
2
+ // `social({...})` unit of any `<name>.shipkit.ts`. Every unit file imports this module, so it stays light: the desk
3
+ // finds, imports and calls the unit on the server, and the hub never bundles project code
4
+ import { existsSync } from 'node:fs'
5
+ import { importFresh } from '../core/discover-checks.ts'
6
+ import { unitFilesDeclaring } from '../core/unit-files.ts'
7
+
8
+ /** what the desk shows of a draft's `post.md` beyond its front matter */
9
+ export interface ArticleInfo {
10
+ /** its address on the identity's site */
11
+ url: string
12
+ }
13
+
14
+ export interface SocialDef {
15
+ /** the words a draft's `topics` take; another word fails the load. Unset, any word */
16
+ topics?: readonly string[]
17
+ /** a draft folder holding a `post.md`: its address on the site */
18
+ article?(dir: string): ArticleInfo
19
+ /** the article as the site renders it, html; its media paths under `mediaBase` */
20
+ preview?(dir: string, mediaBase: string): string | Promise<string>
21
+ /** the review topic his notes on a draft are raised to (default `social`) */
22
+ notes?: string
23
+ }
24
+
25
+ export type SocialUnit = SocialDef & { kind: 'social' }
26
+
27
+ const WORD = /^[a-z][a-z0-9-]*$/
28
+
29
+ /** why a social unit cannot be read, or null */
30
+ export function socialProblem(d: SocialDef): string | null {
31
+ for (const t of d.topics ?? []) if (!WORD.test(t)) return `social: topic '${t}' is a lowercase word`
32
+ for (const f of ['article', 'preview'] as const) if (d[f] !== undefined && typeof d[f] !== 'function') return `social: ${f} is a function`
33
+ if (d.notes !== undefined && !WORD.test(d.notes)) return `social: notes '${d.notes}' is a review topic, a lowercase word`
34
+ return null
35
+ }
36
+
37
+ export function social(d: SocialDef): SocialUnit {
38
+ const why = socialProblem(d)
39
+ if (why !== null) throw new Error(why)
40
+ return { ...d, kind: 'social' }
41
+ }
42
+
43
+ /** the repo's social unit, or null; two of them is an error naming both files */
44
+ export async function loadSocialUnit(root: string): Promise<SocialUnit | null> {
45
+ if (!existsSync(root)) return null
46
+ const units: { file: string; unit: SocialUnit }[] = []
47
+ for (const f of unitFilesDeclaring(root, 'social')) {
48
+ const d = (await importFresh(f)) as { kind?: unknown } | undefined
49
+ if (d?.kind === 'social') units.push({ file: f, unit: d as SocialUnit })
50
+ }
51
+ if (units.length > 1) throw new Error(`two social units: ${units.map((u) => u.file).join(' and ')}; keep one`)
52
+ return units[0]?.unit ?? null
53
+ }