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
@@ -1,16 +1,14 @@
1
1
  #!/usr/bin/env bun
2
- // the typecheck floor for a repo that has no typecheck script, as one small
3
- // binary the gate spawns, for the same reason source-graph-cli.ts exists: a
4
- // tool the gate REQUIRES must not be a published version behind the repo it
5
- // gates.
2
+ // the typecheck fallback of a bun with no `bun check` (ts/gate-typecheck.ts
3
+ // owns when it runs and when it dies): tsc cold over each project a tsconfig
4
+ // reaches, because `tsc --noEmit` over a solution style config compiles zero
5
+ // files and exits 0. A spawned binary, so the tool the gate requires is never
6
+ // a published version behind the repo it gates.
6
7
  //
7
- // One tsc run per project, sequential, output streamed straight through so the
8
- // task log and its last-line summary behave like any other subprocess task. It
9
- // runs EVERY project rather than stopping at the first red, because a caller
10
- // who fixes the one error tsc showed and re-runs into a second one has been
11
- // told the truth twice and believed it once.
8
+ // Sequential, output streamed straight through. It runs EVERY project rather
9
+ // than stopping at the first red, and a pass names what it checked.
12
10
  import { resolveTypecheckProjects } from 'rvlib-shipkit/src/ts/tsconfig-projects.ts'
13
- import { gateBuildInfoArgs } from 'rvlib-shipkit/src/ts/typecheck-cache.ts'
11
+ import { gateTscCmd } from 'rvlib-shipkit/src/ts/gate-typecheck.ts'
14
12
 
15
13
  export function typecheckCli(argv: string[]): number {
16
14
  const [tsc, tsconfig] = argv
@@ -31,7 +29,7 @@ export function typecheckCli(argv: string[]): number {
31
29
 
32
30
  let worst = 0
33
31
  for (const p of resolved.projects) {
34
- const r = Bun.spawnSync([tsc, '--noEmit', '-p', p, ...gateBuildInfoArgs(p)], { stdout: 'inherit', stderr: 'inherit' })
32
+ const r = Bun.spawnSync(gateTscCmd(tsc, p), { stdout: 'inherit', stderr: 'inherit' })
35
33
  if (r.exitCode !== 0) {
36
34
  console.log(`FAIL: ${p}`)
37
35
  worst = r.exitCode ?? 1
@@ -1,7 +1,6 @@
1
1
  // shipkit tui — the generic view: tab bar, list left, detail right, wire
2
2
  // lines normalized to one visual language (✓/✗/⚠/~/»). All data comes from
3
3
  // panels (tui-panel.ts); this file owns ONLY rendering + keys.
4
- import React from 'react'
5
4
  import { Box, Text, useApp, useInput } from 'ink'
6
5
  import { observer } from 'mobx-react-lite'
7
6
  import { markLine, ROW_MARK, type TuiRow } from './tui-panel.ts'
@@ -0,0 +1,155 @@
1
+ import { stateOf, type ReviewItem } from '../review/model.ts'
2
+ import { raiseItem, readAllCached } from '../review/store.ts'
3
+ import type { AutoRule, Raise } from '../review/unit.ts'
4
+ import { type Desk, reviewBrief } from './desk.ts'
5
+ import { COLUMNS, type FeedRow, type Interaction, type Platform, PLATFORMS } from './platforms.ts'
6
+
7
+ // the Veille's asks are items of the review store of the repo its watch list names in `asks:` (wiki
8
+ // build/shipkit/veille.md, Asks): « Proposer » raises one post, « Revoir » one pass over every column, on the lane
9
+ // `interaction`, where he starts an agent by hand. Read back by their subject `social`, never by their lane, never a
10
+ // second queue. The same review also opens by itself: the auto rule `veille-review`, shipkit's own
11
+
12
+ export const LANE = 'interaction'
13
+ /** the command he starts the lane's agent with, in the asks repo */
14
+ export const START_COMMAND = `SK_AGENT=${LANE} sk review next --lane ${LANE}`
15
+ /** the review names itself in its title; a post's ask holds one key */
16
+ export const REVIEW_TITLE = 'Revoir la Veille'
17
+ export const AUTO_ID = 'veille-review'
18
+
19
+ const subjectKeys = (x: ReviewItem): string[] | null => {
20
+ const s = x.item.subject as { kind?: unknown; keys?: unknown }
21
+ return s.kind === 'social' && Array.isArray(s.keys) ? s.keys.filter((k): k is string => typeof k === 'string') : null
22
+ }
23
+
24
+ /** the open items of the Veille: one post's by its key, the review of every column */
25
+ export function interactions(dir: string): { posts: Record<string, Interaction>; review: Interaction | null } {
26
+ const posts: Record<string, Interaction> = {}
27
+ let review: Interaction | null = null
28
+ for (const x of readAllCached(dir).items) {
29
+ const keys = subjectKeys(x)
30
+ if (keys == null) continue
31
+ const st = stateOf(x, false)
32
+ if (st.state === 'closed') continue
33
+ const it = { id: x.item.id, state: st.state, worker: st.worker ?? null }
34
+ if (x.item.title.startsWith(REVIEW_TITLE)) review ??= it
35
+ else for (const k of keys) posts[k] = it
36
+ }
37
+ return { posts, review }
38
+ }
39
+
40
+ /** « Proposer »: one post's ask, its brief the item's first message */
41
+ export async function raisePost(dir: string, o: { key: string; title: string; brief: string; topic: string | null }): Promise<string> {
42
+ const x = await raiseItem(dir, {
43
+ subject: { kind: 'social', keys: [o.key] },
44
+ origin: { by: 'owner', from: 'veille', lane: LANE },
45
+ ...(o.topic ? { topic: o.topic } : {}),
46
+ title: o.title,
47
+ text: o.brief,
48
+ })
49
+ return x.item.id
50
+ }
51
+
52
+ /** « Revoir »: one pass over every column's active posts, their compact lines the item's first message */
53
+ export async function raiseReview(dir: string, r: Raise, topic: string | null): Promise<string> {
54
+ const x = await raiseItem(dir, {
55
+ subject: r.subject,
56
+ origin: { by: 'owner', from: 'veille', lane: r.lane },
57
+ ...(topic ? { topic } : {}),
58
+ title: r.title,
59
+ text: r.what,
60
+ })
61
+ return x.item.id
62
+ }
63
+
64
+ export type Columns = ReadonlyMap<Platform, readonly FeedRow[]>
65
+ /** a raise of the Veille: its subject the posts' keys */
66
+ export type VeilleRaise = Raise & { subject: { kind: 'social'; keys: string[] } }
67
+
68
+ /** the review of every column, the one builder: « Revoir » and the auto rule raise exactly this; null when no column
69
+ * holds an active post */
70
+ export function reviewRaise(columns: Columns, voice: { as: string; pages: readonly string[] }): VeilleRaise | null {
71
+ const cols = COLUMNS.map((c) => ({ label: c.label, rows: columns.get(c.platform) ?? [] })).filter((c) => c.rows.length > 0)
72
+ if (cols.length === 0) return null
73
+ const n = cols.reduce((t, c) => t + c.rows.length, 0)
74
+ const by = [...cols].sort((a, b) => b.rows[0]!.worth - a.rows[0]!.worth)
75
+ return {
76
+ title: `${REVIEW_TITLE} : ${n} post${n > 1 ? 's' : ''} (${by.map((c) => `${c.label} ${c.rows.length}`).join(', ')})`,
77
+ what: reviewBrief(cols, voice),
78
+ lane: LANE,
79
+ subject: { kind: 'social', keys: by.flatMap((c) => c.rows.map((r) => r.key)) },
80
+ key: 'veille',
81
+ }
82
+ }
83
+
84
+ /** the active rows of each column, as « Revoir » reads them; our own accounts left out */
85
+ export function readColumns(desk: Desk, ours: ReadonlySet<string>): Columns {
86
+ const rows = desk.feed({ ours })
87
+ return new Map(PLATFORMS.map((p) => [p, rows.filter((r) => r.platform === p)]))
88
+ }
89
+
90
+ const lastAt = (x: ReviewItem): number => Math.max(Date.parse(x.item.created), ...x.thread.map((m) => Date.parse(m.at)))
91
+
92
+ const pending = (r: FeedRow): boolean => r.group !== 'done' && !r.handled && r.passed == null && r.reply == null && r.asked == null
93
+
94
+ /** the Veille waits for a review: a column holds posts nobody drafted, asked, handled or passed, no item of the Veille
95
+ * was raised or closed in the last `quietMin` minutes, and no review of it is still open */
96
+ export function waits(columns: Columns, items: readonly ReviewItem[], now: number, quietMin: number): boolean {
97
+ if (![...columns.values()].some((rows) => rows.some(pending))) return false
98
+ for (const x of items) {
99
+ if (subjectKeys(x) == null) continue
100
+ const closed = stateOf(x, false).state === 'closed'
101
+ if (!closed && x.item.title.startsWith(REVIEW_TITLE)) return false
102
+ if (now - Date.parse(x.item.created) < quietMin * 60_000) return false
103
+ if (closed && now - lastAt(x) < quietMin * 60_000) return false
104
+ }
105
+ return true
106
+ }
107
+
108
+ /** the one review when the Veille waits, exactly what « Revoir » raises, the platforms off left out */
109
+ export function veilleWhen(ctx: { items: readonly ReviewItem[]; now: Date }, columns: Columns | null, off: readonly Platform[], quietMin: number, voice: { as: string; pages: readonly string[] }): VeilleRaise | null {
110
+ if (columns == null) return null
111
+ const on: Columns = new Map([...columns].filter(([p]) => !off.includes(p)))
112
+ return waits(on, ctx.items, ctx.now.getTime(), quietMin) ? reviewRaise(on, voice) : null
113
+ }
114
+
115
+ const FRESH_MS = 60_000
116
+
117
+ /** the auto rule of one identity's Veille, in the review engine's shape: `when` reads a snapshot of the feed refreshed
118
+ * off its own call, so a tick costs a few filters, never a read of the log */
119
+ export function veilleAuto(desk: Desk, as: string, ours: () => ReadonlySet<string>): AutoRule {
120
+ let snapshot: { at: number; columns: Columns } | null = null
121
+ let refreshing = false
122
+ const columns = (): Columns | null => {
123
+ // cold: one synchronous read, else the first tick answers nothing
124
+ if (snapshot == null) snapshot = { at: Date.now(), columns: readColumns(desk, ours()) }
125
+ if (Date.now() - snapshot.at > FRESH_MS && !refreshing) {
126
+ refreshing = true
127
+ setTimeout(() => {
128
+ try {
129
+ snapshot = { at: Date.now(), columns: readColumns(desk, ours()) }
130
+ } catch (e) {
131
+ console.warn(`WARN veille auto: the feed of ${as} did not read (${(e as Error).message})`)
132
+ } finally {
133
+ refreshing = false
134
+ }
135
+ }, 0)
136
+ }
137
+ return snapshot.columns
138
+ }
139
+ // read before the first tick, which then stays well under the engine's budget
140
+ setTimeout(() => {
141
+ try {
142
+ columns()
143
+ } catch {
144
+ // the tick reads it again and says why
145
+ }
146
+ }, 0).unref()
147
+ return {
148
+ id: AUTO_ID,
149
+ every: '5m',
150
+ when: (ctx) => {
151
+ const w = desk.watch()
152
+ return veilleWhen(ctx, columns(), desk.off(), w.rules.autoReviewMin, { as, pages: w.voice })
153
+ },
154
+ }
155
+ }
@@ -0,0 +1,31 @@
1
+ import { basename } from 'node:path'
2
+ import type { AutoRule, ReviewUnit } from '../review/unit.ts'
3
+ import { AUTO_ID, veilleAuto } from './asks.ts'
4
+ import { hasVeille, identities } from './identity.ts'
5
+ import { oursOf, veilleOf } from './service.ts'
6
+
7
+ // the review that opens by itself (wiki build/shipkit/veille.md, A review): shipkit adds the rule `veille-review` to the
8
+ // rules of the repo a watch list names in `asks:`, beside the rules the repo's own review unit declares
9
+
10
+ /** the Veille rules of the repo at `root`: one an identity whose watch list names it, the first under `veille-review` */
11
+ export function veilleRules(root: string): AutoRule[] {
12
+ const name = basename(root)
13
+ return identities()
14
+ .filter((x) => hasVeille(x) && veilleOf(x).desk.watch().asks === name)
15
+ .map((x, i) => {
16
+ const rule = veilleAuto(veilleOf(x).desk, x.id, () => oursOf(x))
17
+ return i === 0 ? rule : { ...rule, id: `${AUTO_ID}-${x.id}` }
18
+ })
19
+ }
20
+
21
+ /** every auto rule of a repo's store: its unit's, then shipkit's own the unit does not name */
22
+ export function autoRulesOf(root: string, unit: ReviewUnit | null): AutoRule[] {
23
+ const own = unit?.auto ?? []
24
+ let builtIn: AutoRule[] = []
25
+ try {
26
+ builtIn = veilleRules(root)
27
+ } catch (e) {
28
+ console.error(`FAIL: veille: the auto rule of ${basename(root)} did not build: ${(e as Error).message}`)
29
+ }
30
+ return [...own, ...builtIn.filter((r) => !own.some((o) => o.id === r.id))]
31
+ }
@@ -0,0 +1,27 @@
1
+ import { hasVeille, identityOfProfile } from './identity.ts'
2
+ import { parseBatch } from './log.ts'
3
+ import { takeBatch } from './service.ts'
4
+
5
+ // the extension's one address (wiki build/shipkit/veille.md, The extension reads): the daemon's `/api/veille/batch`. Its
6
+ // header names the Chrome profile, the profile names the identity. Only the extension sends `x-post-tracker`: a page
7
+ // elsewhere cannot without a preflight the daemon never answers, so this route runs before the same origin guard
8
+
9
+ const NO_STORE = { 'Cache-Control': 'no-store' }
10
+ const warned = new Set<string>()
11
+
12
+ export async function veilleBatchRoute(req: Request, path: string): Promise<Response | null> {
13
+ if (path !== '/api/veille/batch') return null
14
+ if (req.method !== 'POST') return new Response('POST a batch', { status: 405 })
15
+ if (req.headers.get('x-post-tracker') !== '1') return Response.json({ error: 'x-post-tracker?' }, { status: 403, headers: NO_STORE })
16
+ const email = req.headers.get('x-shipkit-profile') ?? ''
17
+ const x = identityOfProfile(email)
18
+ const refuse = x == null ? `this Chrome profile (${email || 'signed in nowhere'}) is no identity's: its email is no identity.md's email` : hasVeille(x) ? null : `${x.id} has no watch list (${x.watchFile})`
19
+ if (refuse != null) {
20
+ if (!warned.has(refuse)) console.warn(`WARN veille: a batch refused: ${refuse}`)
21
+ warned.add(refuse)
22
+ return Response.json({ error: refuse }, { status: 403, headers: NO_STORE })
23
+ }
24
+ const b = parseBatch(await req.json().catch(() => null))
25
+ if (typeof b === 'string') return Response.json({ error: b }, { status: 400, headers: NO_STORE })
26
+ return Response.json({ ok: true, identity: x!.id, ...takeBatch(x!, b) }, { headers: NO_STORE })
27
+ }
@@ -0,0 +1,127 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+
5
+ // an identity's pages opened in ITS Chrome profile (wiki build/shipkit/veille.md, Identities: one Chrome profile each),
6
+ // the one signed in with the identity's email: one tab, or windows side by side across the top of the largest display
7
+ // with a file shown in the Finder below them, so he drags it in. Chrome because its windows take bounds from
8
+ // AppleScript. A file put on the clipboard the way Finder's « Copier » puts it, so a paste in a compose box attaches it
9
+
10
+ type Rect = { left: number; top: number; right: number; bottom: number }
11
+
12
+ /** the share of the screen's height the compose windows take; the Finder fills the rest */
13
+ const TOP = 0.66
14
+ const GAP = 8
15
+
16
+ /** n windows side by side across the top of a screen, and the one below them (screen points, top left origin) */
17
+ export function tile(screen: { x: number; y: number; w: number; h: number }, n: number): { top: Rect[]; below: Rect } {
18
+ const topH = Math.round(screen.h * TOP)
19
+ const w = (screen.w - GAP * (n + 1)) / n
20
+ const top = Array.from({ length: n }, (_, i) => {
21
+ const left = Math.round(screen.x + GAP + i * (w + GAP))
22
+ return { left, top: screen.y + GAP, right: Math.round(left + w), bottom: screen.y + topH }
23
+ })
24
+ return { top, below: { left: screen.x + GAP, top: screen.y + topH + GAP, right: screen.x + screen.w - GAP, bottom: screen.y + screen.h - GAP } }
25
+ }
26
+
27
+ async function osa(args: string[]): Promise<string> {
28
+ const p = Bun.spawn(['osascript', ...args], { stdout: 'pipe', stderr: 'pipe' })
29
+ const [out, err, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited])
30
+ if (code !== 0) throw new Error(`osascript: ${err.trim() || `exit ${code}`}`)
31
+ return out.trim()
32
+ }
33
+
34
+ type Screen = { x: number; y: number; w: number; h: number }
35
+
36
+ /** the largest display by its area in points (the room a window gets; pixels would pick a Retina laptop over a wider
37
+ * screen), the first of a tie */
38
+ export const largest = (screens: readonly Screen[]): Screen | undefined => screens.reduce<Screen | undefined>((a, s) => (a == null || s.w * s.h > a.w * a.h ? s : a), undefined)
39
+
40
+ /** the visible bounds (no menu bar, no dock) of every display, read at each click, in the top left origin AppleScript
41
+ * bounds use: Cocoa counts y up from the main display's foot */
42
+ async function screens(): Promise<Screen[]> {
43
+ const js = `ObjC.import('AppKit'); var a = $.NSScreen.screens; var main = a.objectAtIndex(0).frame.size.height; var out = [];
44
+ for (var i = 0; i < a.count; i++) { var v = a.objectAtIndex(i).visibleFrame; out.push({ x: v.origin.x, y: main - (v.origin.y + v.size.height), w: v.size.width, h: v.size.height }) }
45
+ JSON.stringify(out)`
46
+ return JSON.parse(await osa(['-l', 'JavaScript', '-e', js])) as Screen[]
47
+ }
48
+
49
+ const CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
50
+
51
+ /** one AppleScript line to Chrome, tried again twice when its link drops for a moment while it makes a window */
52
+ async function chrome(line: string): Promise<string> {
53
+ for (let k = 0; ; k++) {
54
+ try {
55
+ return await osa(['-e', `tell application "Google Chrome" to ${line}`])
56
+ } catch (e) {
57
+ if (k >= 2) throw e
58
+ await Bun.sleep(300)
59
+ }
60
+ }
61
+ }
62
+
63
+ const bounds = (r: Rect): string => `{${r.left}, ${r.top}, ${r.right}, ${r.bottom}}`
64
+
65
+ const LOCAL_STATE = join(homedir(), 'Library/Application Support/Google/Chrome/Local State')
66
+
67
+ /** the folder of the Chrome profile signed in with that email (an identity's, its `email`) */
68
+ export function chromeProfile(email: string): string {
69
+ if (email === '') throw new Error('the identity has no email: its Chrome profile is the one signed in with it')
70
+ const state = JSON.parse(readFileSync(LOCAL_STATE, 'utf8')) as { profile?: { info_cache?: Record<string, { user_name?: string; name?: string }> } }
71
+ const hit = Object.entries(state.profile?.info_cache ?? {}).find(([, v]) => v.user_name?.toLowerCase() === email.toLowerCase())
72
+ if (hit == null) throw new Error(`no Chrome profile is signed in with ${email}: sign in once in a profile of its own`)
73
+ return hit[0]
74
+ }
75
+
76
+ /** one page in a new tab of the Chrome profile signed in with `email`, its window left where it is */
77
+ export async function openTab(url: string, email: string): Promise<void> {
78
+ const open = Bun.spawn([CHROME, `--profile-directory=${chromeProfile(email)}`, url], { stdout: 'ignore', stderr: 'pipe' })
79
+ if ((await open.exited) !== 0) throw new Error(`open Chrome: ${(await new Response(open.stderr).text()).trim()}`)
80
+ }
81
+
82
+ /** the pages tiled in the Chrome profile signed in with `email`, then the media selected in a Finder window below them;
83
+ * `media` an absolute file or null */
84
+ export async function openAll(urls: readonly string[], media: string | null, email: string): Promise<void> {
85
+ if (urls.length === 0) throw new Error('rien à ouvrir : chaque plateforme est postée ou publie elle même')
86
+ const screen = largest(await screens())
87
+ if (screen == null) throw new Error('no display found')
88
+ const layout = tile(screen, urls.length)
89
+ const dir = chromeProfile(email)
90
+ // the Finder first, placed while Chrome makes its windows: he drags into the first one as soon as it shows
91
+ const finder = media == null ? Promise.resolve() : placeFinder(media, layout.below)
92
+ for (const [i, url] of urls.entries()) {
93
+ const before = Number(await chrome('count windows').catch(() => '0'))
94
+ // the binary itself: a running Chrome takes the window in its own process and this one exits; `open -n` started
95
+ // a second instance whose AppleScript link died with it (-609)
96
+ const open = Bun.spawn([CHROME, `--profile-directory=${dir}`, '--new-window', url], { stdout: 'ignore', stderr: 'pipe' })
97
+ if ((await open.exited) !== 0) throw new Error(`open Chrome: ${(await new Response(open.stderr).text()).trim()}`)
98
+ // the new window is the front one once Chrome has made it: wait for it, at most 5 s
99
+ for (let t = 0; t < 50 && Number(await chrome('count windows').catch(() => String(before))) <= before; t++) await Bun.sleep(100)
100
+ await chrome(`set bounds of window 1 to ${bounds(layout.top[i]!)}`)
101
+ }
102
+ await finder
103
+ }
104
+
105
+ /** the media selected in a Finder window, then that window moved to `box` */
106
+ async function placeFinder(media: string, box: Rect): Promise<void> {
107
+ const reveal = Bun.spawn(['open', '-R', media], { stdout: 'ignore', stderr: 'ignore' })
108
+ await reveal.exited
109
+ // the Finder brings its window forward on its own time: a moment, then its bounds
110
+ await Bun.sleep(700)
111
+ await osa(['-e', `tell application "Finder"\nset bounds of front window to ${bounds(box)}\nend tell`])
112
+ }
113
+
114
+ /** a file shown selected in the Finder */
115
+ export async function reveal(abs: string): Promise<void> {
116
+ const p = Bun.spawn(['open', '-R', abs], { stdout: 'ignore', stderr: 'pipe' })
117
+ if ((await p.exited) !== 0) throw new Error(`open -R ${abs}: ${(await new Response(p.stderr).text()).trim()}`)
118
+ }
119
+
120
+ const COPY = 'function run(argv){ObjC.import("AppKit");const pb=$.NSPasteboard.generalPasteboard;pb.clearContents;return pb.writeObjects($([$.NSURL.fileURLWithPath(argv[0])]))}'
121
+
122
+ /** a file on the macOS clipboard as Finder's « Copier » puts it: a paste in Chrome's compose box attaches the file */
123
+ export async function copyFile(abs: string): Promise<void> {
124
+ const p = Bun.spawn(['osascript', '-l', 'JavaScript', '-e', COPY, abs], { stdout: 'pipe', stderr: 'pipe' })
125
+ const [out, err, code] = [await new Response(p.stdout).text(), await new Response(p.stderr).text(), await p.exited]
126
+ if (code !== 0 || out.trim() !== 'true') throw new Error(`the clipboard refused ${abs}: ${err.trim() || out.trim() || `exit ${code}`}`)
127
+ }
@@ -0,0 +1,28 @@
1
+ // the Veille as a tree row (wiki build/shipkit/veille.md, The page): one row for the identity this repo shows the Veille
2
+ // of, the posts to answer now in its slot. Only the log's index is read, which a batch keeps in memory
3
+ import { VEILLE_COL, type Collection, type Instance } from '../collections/collection-types.ts'
4
+ import { veilleAt } from './routes.ts'
5
+ import { oursOf, veilleOf } from './service.ts'
6
+
7
+ export function veilleCollection(root: string): Collection | null {
8
+ let at: ReturnType<typeof veilleAt>
9
+ try {
10
+ at = veilleAt(root)
11
+ } catch {
12
+ return null
13
+ }
14
+ if (at == null) return null
15
+ const { identity } = at
16
+ return {
17
+ id: VEILLE_COL,
18
+ title: 'veille',
19
+ kind: 'veille',
20
+ media: 'text',
21
+ list: async () => {
22
+ const rows = veilleOf(identity).desk.feed({ ours: oursOf(identity) })
23
+ const now = rows.filter((r) => r.group === 'now' && !r.handled && r.reply == null).length
24
+ const slot = now === 0 ? 'nothing to answer now' : `${now} to answer now`
25
+ return [{ id: `veille:${identity.id}`, text: `${identity.name}'s Veille: ${slot}`, label: identity.name, slot, type: 'veille', path: 'veille/', virtual: true, state: 'ok' } satisfies Instance]
26
+ },
27
+ }
28
+ }
@@ -0,0 +1,242 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { handleKey } from './identity.ts'
4
+ import { fileKey, VeilleLog } from './log.ts'
5
+ import { type FeedRow, type Interaction, keyOf, type MediaPick, type Platform, PLATFORMS, type Replied, type Reply } from './platforms.ts'
6
+ import { kept, matches, type Watch, watch } from './watch.ts'
7
+ import { groupOf, parts, worthOf } from './worth.ts'
8
+
9
+ // one identity's desk (wiki build/shipkit/veille.md): the log ranked, what he handled, the reply drafts and the asks for
10
+ // one. What `sk veille feed` prints and the hub's Veille page shows
11
+ /** `all`: the « vus ou expirés » too; else only the active groups */
12
+ type FeedQuery = { now?: number; platform?: Platform; sinceMs?: number; top?: number; all?: boolean; ours?: ReadonlySet<string>; watch?: Watch; asks?: Record<string, Interaction> }
13
+
14
+ /** `<platform>:<author>` the way our own accounts are written, to leave them out */
15
+ export const ourKey = handleKey
16
+
17
+ export class Desk {
18
+ readonly log: VeilleLog
19
+ /** the marks, drafts and replies live beside the log; `watchFile` the identity's watch list */
20
+ constructor(
21
+ readonly dir: string,
22
+ readonly watchFile: string,
23
+ ) {
24
+ this.log = new VeilleLog(dir)
25
+ }
26
+
27
+ get repliesDir(): string {
28
+ return join(this.dir, 'replies')
29
+ }
30
+
31
+ handled(): Record<string, number> {
32
+ try {
33
+ return JSON.parse(readFileSync(join(this.dir, 'handled.json'), 'utf8')) as Record<string, number>
34
+ } catch {
35
+ return {}
36
+ }
37
+ }
38
+
39
+ setHandled(key: string, on: boolean, now = Date.now()): void {
40
+ const h = this.handled()
41
+ if (on) h[key] = now
42
+ else delete h[key]
43
+ mkdirSync(this.dir, { recursive: true })
44
+ writeFileSync(join(this.dir, 'handled.json'), JSON.stringify(h))
45
+ this.log.stamp++
46
+ }
47
+
48
+ /** our replies detected, by the key of the post they answer */
49
+ replied(): Record<string, Replied> {
50
+ try {
51
+ return JSON.parse(readFileSync(join(this.dir, 'replied.json'), 'utf8')) as Record<string, Replied>
52
+ } catch {
53
+ return {}
54
+ }
55
+ }
56
+
57
+ /** a reply detected: kept with its url, the post marked handled; false when that post already had one */
58
+ setReplied(key: string, r: Replied, now = Date.now()): boolean {
59
+ const all = this.replied()
60
+ if (all[key] != null) return false
61
+ all[key] = r
62
+ mkdirSync(this.dir, { recursive: true })
63
+ writeFileSync(join(this.dir, 'replied.json'), JSON.stringify(all))
64
+ if (this.handled()[key] == null) this.setHandled(key, true, now)
65
+ this.log.stamp++
66
+ return true
67
+ }
68
+
69
+ reply(key: string): Reply | null {
70
+ try {
71
+ return JSON.parse(readFileSync(join(this.repliesDir, `${fileKey(key)}.json`), 'utf8')) as Reply
72
+ } catch {
73
+ return null
74
+ }
75
+ }
76
+
77
+ writeReply(key: string, r: Reply): void {
78
+ mkdirSync(this.repliesDir, { recursive: true })
79
+ writeFileSync(join(this.repliesDir, `${fileKey(key)}.json`), JSON.stringify(r, null, 2))
80
+ this.log.stamp++
81
+ }
82
+
83
+ /** every draft, by key: one listing of the folder */
84
+ drafts(): Record<string, Reply> {
85
+ const out: Record<string, Reply> = {}
86
+ if (!existsSync(this.repliesDir)) return out
87
+ for (const f of readdirSync(this.repliesDir)) {
88
+ const m = /^([a-z]+)-(.+)\.json$/.exec(f)
89
+ const r = m ? this.reply(`${m[1]}:${m[2]}`) : null
90
+ if (m && r) out[`${m[1]}:${m[2]}`] = r
91
+ }
92
+ return out
93
+ }
94
+
95
+ /** the platforms he switched off in the rail: their columns hidden, out of the review and its rule, their log kept */
96
+ off(): Platform[] {
97
+ try {
98
+ const o = (JSON.parse(readFileSync(join(this.dir, 'platforms.json'), 'utf8')) as { off?: unknown }).off
99
+ return PLATFORMS.filter((p) => Array.isArray(o) && o.includes(p))
100
+ } catch {
101
+ return []
102
+ }
103
+ }
104
+
105
+ setOn(platform: Platform, on: boolean): void {
106
+ const off = this.off().filter((p) => p !== platform)
107
+ if (!on) off.push(platform)
108
+ mkdirSync(this.dir, { recursive: true })
109
+ writeFileSync(join(this.dir, 'platforms.json'), `${JSON.stringify({ off: PLATFORMS.filter((p) => off.includes(p)) })}\n`)
110
+ this.log.stamp++
111
+ }
112
+
113
+ /** the posts a review passed, with its one line reason */
114
+ passed(): Record<string, { why: string; at: number }> {
115
+ try {
116
+ return JSON.parse(readFileSync(join(this.dir, 'passed.json'), 'utf8')) as Record<string, { why: string; at: number }>
117
+ } catch {
118
+ return {}
119
+ }
120
+ }
121
+
122
+ pass(key: string, why: string, now = Date.now()): void {
123
+ const p = this.passed()
124
+ p[key] = { why, at: now }
125
+ mkdirSync(this.dir, { recursive: true })
126
+ writeFileSync(join(this.dir, 'passed.json'), JSON.stringify(p))
127
+ this.log.stamp++
128
+ }
129
+
130
+ watch(): Watch {
131
+ return watch(this.watchFile)
132
+ }
133
+
134
+ /** the posts ranked by worth, best first: in the window, on the platform, kept by the watch list as it stands
135
+ * (the identity's, unless the query names one), our own accounts left out */
136
+ feed(q: FeedQuery = {}): FeedRow[] {
137
+ const now = q.now ?? Date.now()
138
+ const w = q.watch ?? this.watch()
139
+ const rules = w.rules
140
+ const handled = this.handled()
141
+ const drafts = this.drafts()
142
+ const passed = this.passed()
143
+ const replied = this.replied()
144
+ const authors = this.log.authors()
145
+ const rows: FeedRow[] = []
146
+ for (const p of this.log.posts().values()) {
147
+ if (q.platform && p.platform !== q.platform) continue
148
+ if (q.sinceMs != null && now - p.last > q.sinceMs) continue
149
+ if (q.ours?.has(ourKey(p.platform, p.author))) continue
150
+ const key = keyOf(p)
151
+ const followers = authors[`${p.platform}:${p.author.toLowerCase()}`]?.followers ?? p.followers
152
+ const post = { ...p, place: p.place ?? '', followers }
153
+ if (!kept(post, w)) continue
154
+ const tags = matches(post, w)
155
+ const x = parts(post, tags.length, now, rules)
156
+ const worth = worthOf(x)
157
+ const group = groupOf(worth, handled[key] != null || passed[key] != null, rules)
158
+ if (!q.all && group === 'done') continue
159
+ rows.push({ ...post, key, worth, parts: x, group, handled: handled[key] != null, passed: passed[key]?.why ?? null, reply: drafts[key] ?? null, replied: replied[key] ?? null, asked: q.asks?.[key] ?? null, tags })
160
+ }
161
+ rows.sort((a, b) => b.worth - a.worth || b.last - a.last)
162
+ return q.top != null ? rows.slice(0, q.top) : rows
163
+ }
164
+ }
165
+
166
+ /** 1234 → 1.2k */
167
+ export const short = (n: number | null): string => (n == null ? '-' : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e4 ? `${Math.round(n / 1e3)}k` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n))
168
+
169
+ export const age = (ms: number): string => (ms < 3600_000 ? `${Math.max(1, Math.round(ms / 60_000))}m` : ms < 48 * 3600_000 ? `${Math.round(ms / 3600_000)}h` : `${Math.round(ms / 86_400_000)}d`)
170
+
171
+ /** one compact line a post, what an agent reads instead of the log */
172
+ export function feedLine(r: FeedRow, now = Date.now()): string {
173
+ const text = r.text.length > 100 ? `${r.text.slice(0, 99)}…` : r.text
174
+ const marks = `${r.reply ? ' [draft]' : r.asked ? ` [asked ${r.asked.id}]` : ''}${r.handled ? ' [handled]' : r.passed ? ` [passed: ${r.passed}]` : r.group === 'done' ? ' [expired]' : ''}`
175
+ return `${r.platform.padEnd(9)} @${r.author} (${short(r.followers)}) ${age(now - (r.at ?? r.first))} ♥${short(r.likes)} ↻${short(r.reposts)} 💬${short(r.replies)}${r.views != null ? ` 👁${short(r.views)}` : ''} w${r.worth}${r.place ? ` ${r.place}` : ''} « ${text} » ${r.key}${marks}`
176
+ }
177
+
178
+ /** a draft of the project as the media picker reads it: its slug, and each message's text, title and media file */
179
+ export type DraftMedia = { slug: string; posts: readonly { text: string; title: string; media: { path: string } | null }[] }
180
+
181
+ /** the media our drafts could lend a reply, repo relative: the drafts' files, the ones sharing the most words with the
182
+ * post first */
183
+ export function mediaFor(text: string, drafts: readonly DraftMedia[], root: string, top = 6): MediaPick[] {
184
+ const words = (s: string): Set<string> => new Set(s.toLowerCase().normalize('NFD').replace(/\p{M}/gu, '').split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 3))
185
+ const mine = words(text)
186
+ const seen = new Set<string>()
187
+ const out: MediaPick[] = []
188
+ for (const d of drafts)
189
+ for (const p of d.posts) {
190
+ if (p.media == null || seen.has(p.media.path)) continue
191
+ seen.add(p.media.path)
192
+ const theirs = words(`${p.title} ${p.text}`)
193
+ out.push({ path: p.media.path.startsWith(`${root}/`) ? p.media.path.slice(root.length + 1) : p.media.path, draft: d.slug, words: [...mine].filter((w) => theirs.has(w)).length })
194
+ }
195
+ // a draft's slug starts with its date: the newest first among equals
196
+ return out.sort((a, b) => b.words - a.words || b.draft.localeCompare(a.draft)).slice(0, top)
197
+ }
198
+
199
+ /** the identity's voice as a brief names it: its pages and skill, and nothing else */
200
+ const voiceLine = (voice: readonly string[], as: string): string =>
201
+ voice.length > 0 ? `Write in the voice of ${as}: read ${voice.join(', ')}. Nothing else.` : `Write in the voice of ${as}: its watch list names no ## Voice page, so keep it short, specific and warm.`
202
+
203
+ /** the brief for one reply: the post, the pages to read, the media to lend, where to write. Nothing else is loaded */
204
+ export function brief(r: FeedRow, media: readonly MediaPick[], voice: { as: string; pages: readonly string[] }, now = Date.now()): string {
205
+ return [
206
+ `# A reply to ${r.key}`,
207
+ '',
208
+ `${feedLine(r, now)}`,
209
+ `${r.url}`,
210
+ '',
211
+ '> ' + r.text.replaceAll('\n', '\n> '),
212
+ '',
213
+ voiceLine(voice.pages, voice.as),
214
+ 'No reply is better than a thin one: pass it when there is nothing specific, warm and true to say.',
215
+ '',
216
+ media.length > 0 ? 'Media our drafts could lend (the path, the draft, the words shared):' : 'No media from our drafts.',
217
+ ...media.map((m) => `- ${m.path} (${m.draft}, ${m.words})`),
218
+ '',
219
+ `Write it: sk veille reply ${r.key} --as ${voice.as} --text "<the reply>" [--media <path>]`,
220
+ `Or pass it: sk veille pass ${r.key} --as ${voice.as} --why "<one line>"`,
221
+ 'Then close this item: sk review fixed <its id> --note "<the draft, or why not>"',
222
+ '',
223
+ ].join('\n')
224
+ }
225
+
226
+ /** the brief for one review of every column: each platform's active posts as compact lines under its heading, the
227
+ * platform with the best post first, best first in each, and how to answer */
228
+ export function reviewBrief(columns: readonly { label: string; rows: readonly FeedRow[] }[], voice: { as: string; pages: readonly string[] }, now = Date.now()): string {
229
+ const shown = columns.filter((c) => c.rows.length > 0).sort((a, b) => b.rows[0]!.worth - a.rows[0]!.worth)
230
+ const n = shown.reduce((t, c) => t + c.rows.length, 0)
231
+ return [
232
+ `# One review of the Veille: ${n} active post${n > 1 ? 's' : ''} on ${shown.length} platform${shown.length > 1 ? 's' : ''}, best first`,
233
+ '',
234
+ ...shown.flatMap((c) => [`## ${c.label}: ${c.rows.length} post${c.rows.length > 1 ? 's' : ''}`, '', ...c.rows.map((r) => feedLine(r, now)), '']),
235
+ voiceLine(voice.pages, voice.as),
236
+ 'Read every line first, then pick the few posts truly worth a reply (often two or three, sometimes none).',
237
+ `Each one picked: sk veille reply <key> --as ${voice.as} for its brief, then sk veille reply <key> --as ${voice.as} --text "<the reply>".`,
238
+ `Every other line: sk veille pass <key> --as ${voice.as} --why "<the real reason, one line>".`,
239
+ 'Then close this item: sk review fixed <its id> --note "<n drafts, m passed>"',
240
+ '',
241
+ ].join('\n')
242
+ }