rvlib-shipkit 2.31.0 → 2.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (384) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/package.json +1 -1
  3. package/src/advisors/acts.ts +16 -15
  4. package/src/advisors/advice.ts +56 -102
  5. package/src/advisors/advisor-view.ts +98 -73
  6. package/src/advisors/app-graph.ts +1 -1
  7. package/src/advisors/app.ts +3 -11
  8. package/src/advisors/cf-api.ts +1 -1
  9. package/src/advisors/dir-bucket.ts +4 -3
  10. package/src/advisors/edge/api.ts +26 -198
  11. package/src/advisors/edge/bucket.ts +2 -2
  12. package/src/advisors/edge/handler.ts +13 -155
  13. package/src/advisors/edge/here.ts +5 -5
  14. package/src/advisors/edge/pages.ts +12 -9
  15. package/src/advisors/edge/shell.ts +6 -5
  16. package/src/advisors/edge/sign-in.ts +101 -36
  17. package/src/advisors/edge/status.ts +19 -6
  18. package/src/advisors/edge/types.ts +36 -60
  19. package/src/advisors/expose.ts +29 -29
  20. package/src/advisors/here.ts +12 -12
  21. package/src/advisors/invite-send.ts +79 -35
  22. package/src/advisors/invite.ts +31 -8
  23. package/src/advisors/job.ts +24 -16
  24. package/src/advisors/login.ts +40 -15
  25. package/src/advisors/owner-store.ts +46 -22
  26. package/src/advisors/photos.ts +3 -3
  27. package/src/advisors/project.ts +25 -23
  28. package/src/advisors/reach.ts +89 -0
  29. package/src/advisors/rights.ts +1 -1
  30. package/src/advisors/routes.ts +55 -74
  31. package/src/advisors/scan.ts +0 -4
  32. package/src/advisors/setup-run.ts +14 -14
  33. package/src/advisors/share-trace.ts +3 -3
  34. package/src/advisors/{door-probe.ts → sign-in-probe.ts} +7 -6
  35. package/src/advisors/speaks.ts +29 -0
  36. package/src/advisors/sync.ts +92 -182
  37. package/src/advisors/tunnel.ts +6 -5
  38. package/src/advisors/users-listen.ts +92 -0
  39. package/src/advisors/users-router.ts +257 -85
  40. package/src/advisors/users-store.ts +81 -0
  41. package/src/agent-time/blocked-scan.ts +181 -0
  42. package/src/agent-time/registry.ts +12 -5
  43. package/src/agent-time/store.ts +9 -109
  44. package/src/asks/ask-bar-fold.ts +2 -1
  45. package/src/asks/ask-close.ts +2 -1
  46. package/src/asks/ask-doc.ts +2 -1
  47. package/src/asks/ask-migrate.ts +3 -2
  48. package/src/asks/ask-steps-fold.ts +2 -1
  49. package/src/asks/ask-store.ts +4 -3
  50. package/src/check.ts +3 -43
  51. package/src/checks/SK001-package-json-shape.check.ts +4 -55
  52. package/src/checks/SK004-gitignore-policy.check.ts +24 -69
  53. package/src/checks/SK013-one-way-in-policy.check.ts +3 -7
  54. package/src/checks/SK017-vscode-hub-task.check.ts +4 -4
  55. package/src/checks/SK019-tests-run-in-units.check.ts +3 -14
  56. package/src/checks/SK020-self-spawning-check.check.ts +5 -7
  57. package/src/checks/SK035-public-clean.check.ts +1 -1
  58. package/src/checks/SK039-vscode-watch-generated.check.ts +1 -1
  59. package/src/checks/SK042-post-kinds.check.ts +5 -14
  60. package/src/checks/SK054-agent-allow-list.check.ts +5 -74
  61. package/src/checks/SK055-retired-config-keys.check.ts +45 -0
  62. package/src/cli/cmd_Advisors.ts +11 -45
  63. package/src/cli/cmd_Asks.ts +3 -10
  64. package/src/cli/cmd_Backup.ts +25 -127
  65. package/src/cli/cmd_BackupTargets.ts +1 -1
  66. package/src/cli/cmd_Checks.ts +0 -14
  67. package/src/cli/cmd_Db.ts +3 -82
  68. package/src/cli/cmd_Home.ts +4 -32
  69. package/src/cli/cmd_Hq.ts +0 -17
  70. package/src/cli/cmd_Releases.ts +57 -4
  71. package/src/cli/cmd_Review.ts +333 -354
  72. package/src/cli/cmd_SocialDrafts.ts +6 -13
  73. package/src/cli/cmd_ThreadSyncNeeds.ts +6 -2
  74. package/src/cli/cmd_Time.ts +1 -1
  75. package/src/cli/cmd_Trailer.ts +1 -1
  76. package/src/cli/inbox-hook-run.ts +5 -23
  77. package/src/cli/registry-heads.ts +5 -55
  78. package/src/cli/registry.ts +1 -5
  79. package/src/cli/review-here.ts +1 -1
  80. package/src/cli.ts +2 -2
  81. package/src/collections/collection-types.ts +1 -1
  82. package/src/collections/review.ts +5 -4
  83. package/src/core/agent-allow-policy.ts +32 -2
  84. package/src/core/agent-env.ts +8 -0
  85. package/src/core/allow-rows.ts +74 -0
  86. package/src/core/check-file-names.ts +19 -106
  87. package/src/core/footprint.ts +17 -13
  88. package/src/core/identities-root.ts +1 -4
  89. package/src/core/layout.ts +1 -2
  90. package/src/core/machine-db.ts +33 -208
  91. package/src/core/machine-layout.ts +14 -127
  92. package/src/core/mask-source.ts +60 -0
  93. package/src/core/memory-watch.ts +17 -14
  94. package/src/core/motherhome.ts +8 -35
  95. package/src/core/one-way-in-policy.ts +0 -3
  96. package/src/core/repo-walk.ts +0 -9
  97. package/src/core/retention.ts +1 -9
  98. package/src/core/retired-checks.ts +2 -0
  99. package/src/core/tmux-policy.ts +1 -1
  100. package/src/core/tree-watch.ts +2 -2
  101. package/src/core/when.ts +7 -45
  102. package/src/gate/discover-checks.ts +42 -32
  103. package/src/gate/gate-checks.ts +21 -131
  104. package/src/gate/pre-commit-discovery.ts +16 -25
  105. package/src/gate/run-check.ts +0 -4
  106. package/src/gate/run-fix.ts +5 -17
  107. package/src/gate/run-fixers.ts +6 -42
  108. package/src/home/app-sign.ts +2 -2
  109. package/src/home/backup-status.ts +52 -92
  110. package/src/home/backup-verdict.ts +2 -2
  111. package/src/home/daemon-jobs.ts +51 -95
  112. package/src/home/database-words.ts +1 -2
  113. package/src/home/databases.ts +9 -25
  114. package/src/home/home-launchd.ts +0 -6
  115. package/src/home/home-paths.ts +8 -4
  116. package/src/home/home-routes.ts +3 -10
  117. package/src/home/home-state.ts +2 -14
  118. package/src/home/inbox-shape.ts +14 -15
  119. package/src/home/inbox.ts +1 -1
  120. package/src/home/machine-repair.ts +102 -103
  121. package/src/home/resume.ts +1 -15
  122. package/src/home/run-daemon.ts +4 -11
  123. package/src/home/space-page.ts +3 -2
  124. package/src/home/supervise.ts +3 -7
  125. package/src/hooks/hook-config.ts +6 -7
  126. package/src/hooks/leak-guard.ts +1 -1
  127. package/src/hooks/run-hooks.ts +0 -5
  128. package/src/hq/daemon-db.ts +8 -8
  129. package/src/hq/door.ts +3 -16
  130. package/src/hq/hq-db.ts +4 -3
  131. package/src/hq/hq-local.ts +1 -2
  132. package/src/hq/hq-store.ts +0 -15
  133. package/src/hq/item-direct.ts +8 -10
  134. package/src/hq/item-fill.ts +37 -0
  135. package/src/hq/kinds/item-gone.ts +7 -10
  136. package/src/hq/kinds/item-msg.ts +12 -18
  137. package/src/hq/kinds/item.ts +13 -19
  138. package/src/hq/kinds/report.ts +3 -4
  139. package/src/hq/owner-switch.ts +3 -3
  140. package/src/hq/report.ts +5 -9
  141. package/src/hq/switch.ts +2 -11
  142. package/src/hq/thread-sync.ts +5 -17
  143. package/src/hq/{shapes-words.ts → threads-words.ts} +2 -12
  144. package/src/http/owner-word.ts +1 -1
  145. package/src/identities/machine.ts +16 -0
  146. package/src/init-repo.ts +0 -1
  147. package/src/ledger/check-stats.ts +6 -5
  148. package/src/ledger/db.ts +2 -4
  149. package/src/ledger/record-kept.ts +117 -48
  150. package/src/ledger/run-log.ts +21 -2
  151. package/src/ledger/slow-tests.ts +96 -0
  152. package/src/ledger/store.ts +3 -86
  153. package/src/ledger/suite-log.ts +8 -2
  154. package/src/media-store/backup/facts.ts +3 -37
  155. package/src/media-store/backup/keys.ts +1 -8
  156. package/src/media-store/backup/manifest.ts +6 -67
  157. package/src/media-store/backup/restore.ts +4 -13
  158. package/src/media-store/backup/retention.ts +13 -1
  159. package/src/media-store/backup/run.ts +6 -267
  160. package/src/media-store/backup/snapshot.ts +2 -38
  161. package/src/media-store/backup/sources.ts +3 -113
  162. package/src/media-store/backup/target-send.ts +5 -29
  163. package/src/media-store/db.ts +8 -7
  164. package/src/media-store/forget-one.ts +1 -1
  165. package/src/media-store/forget.ts +1 -80
  166. package/src/orchestrator/guards.ts +0 -1
  167. package/src/orchestrator/presence.ts +2 -2
  168. package/src/orchestrator/routes.ts +1 -1
  169. package/src/orchestrator/started.ts +0 -9
  170. package/src/orchestrator/talk-key.ts +3 -4
  171. package/src/orchestrator/unheard.ts +1 -1
  172. package/src/recordings/edit.ts +3 -3
  173. package/src/recordings/marks-draw.ts +17 -6
  174. package/src/recordings/marks.ts +120 -9
  175. package/src/reflections/reflections-queue.ts +3 -10
  176. package/src/release/notes.ts +1 -1
  177. package/src/release/public-clean.ts +66 -6
  178. package/src/release/run-bump.ts +11 -0
  179. package/src/release/run-release.ts +4 -0
  180. package/src/releases/from-thread.ts +3 -3
  181. package/src/releases/model.ts +186 -36
  182. package/src/releases/store.ts +13 -3
  183. package/src/releases/validate.ts +83 -0
  184. package/src/repo-config.ts +29 -64
  185. package/src/review/answer-kinds.ts +61 -4
  186. package/src/review/blocked-guard.ts +11 -0
  187. package/src/review/blocked-object.ts +298 -0
  188. package/src/review/cells.ts +116 -229
  189. package/src/review/close.ts +39 -1
  190. package/src/review/doc-save.ts +3 -2
  191. package/src/review/draft-item.ts +1 -1
  192. package/src/review/events.ts +3 -7
  193. package/src/review/expect.ts +23 -39
  194. package/src/review/format.ts +79 -46
  195. package/src/review/glyphs.ts +1 -0
  196. package/src/review/hand-over.ts +3 -3
  197. package/src/review/heard.ts +1 -1
  198. package/src/review/holds-sync.ts +2 -1
  199. package/src/review/inbox-hook.ts +2 -2
  200. package/src/review/inbox-read.ts +39 -33
  201. package/src/review/instruction-guards.ts +12 -0
  202. package/src/review/instructions.ts +0 -1
  203. package/src/review/item-db.ts +13 -43
  204. package/src/review/item-hq.ts +2 -2
  205. package/src/review/item-rows.ts +3 -14
  206. package/src/review/kind-catalog.ts +3 -1
  207. package/src/review/kinds.ts +18 -8
  208. package/src/review/live-view.ts +3 -0
  209. package/src/review/media-kind.ts +1 -1
  210. package/src/review/mentions.ts +1 -2
  211. package/src/review/model.ts +158 -114
  212. package/src/review/move.ts +149 -0
  213. package/src/review/need-threads.ts +3 -2
  214. package/src/review/object-card.ts +11 -0
  215. package/src/review/object-read.ts +6 -1
  216. package/src/review/one-block.ts +1 -1
  217. package/src/review/owner-read.ts +1 -1
  218. package/src/review/phone-push.ts +10 -9
  219. package/src/review/previews.ts +32 -4
  220. package/src/review/push.ts +2 -2
  221. package/src/review/recap.ts +129 -0
  222. package/src/review/referring.ts +6 -3
  223. package/src/review/reflection-object.ts +4 -3
  224. package/src/review/routes.ts +49 -19
  225. package/src/review/secret-route.ts +3 -2
  226. package/src/review/settle.ts +0 -6
  227. package/src/review/snooze.ts +5 -3
  228. package/src/review/speaker.ts +68 -0
  229. package/src/review/start-title.ts +19 -0
  230. package/src/review/store.ts +86 -59
  231. package/src/review/{wakes.ts → thread-events.ts} +92 -7
  232. package/src/review/thread-md.ts +35 -14
  233. package/src/review/thread-state.ts +798 -0
  234. package/src/review/threads.ts +29 -347
  235. package/src/review/traces.ts +104 -7
  236. package/src/review/trailer-item.ts +1 -1
  237. package/src/review/unit.ts +7 -9
  238. package/src/review/verdict-items.ts +12 -10
  239. package/src/review/view-layout.ts +25 -1
  240. package/src/review/watch-feed.ts +1 -2
  241. package/src/review/working-guards.ts +2 -3
  242. package/src/rules/untrack-generated.ts +1 -15
  243. package/src/secrets/lapse.ts +2 -1
  244. package/src/serve/hub-app/advisor-app.tsx +4 -4
  245. package/src/serve/hub-app/advisor-face.tsx +9 -3
  246. package/src/serve/hub-app/advisor-host.ts +27 -27
  247. package/src/serve/hub-app/advisors-model.ts +17 -8
  248. package/src/serve/hub-app/advisors-rights.tsx +1 -1
  249. package/src/serve/hub-app/advisors-st.ts +15 -14
  250. package/src/serve/hub-app/advisors-view.tsx +13 -11
  251. package/src/serve/hub-app/app-bridge.ts +23 -3
  252. package/src/serve/hub-app/asks-page.tsx +1 -1
  253. package/src/serve/hub-app/auto-text.tsx +71 -16
  254. package/src/serve/hub-app/check-view.tsx +0 -8
  255. package/src/serve/hub-app/controls.css +14 -3
  256. package/src/serve/hub-app/database-view.tsx +1 -2
  257. package/src/serve/hub-app/git-view.tsx +3 -1
  258. package/src/serve/hub-app/hub.css +12 -5
  259. package/src/serve/hub-app/icons.tsx +1 -1
  260. package/src/serve/hub-app/inbox-view.tsx +1 -2
  261. package/src/serve/hub-app/live-sources.ts +2 -2
  262. package/src/serve/hub-app/main-panel.tsx +2 -1
  263. package/src/serve/hub-app/panel-repo.ts +0 -9
  264. package/src/serve/hub-app/pic.tsx +29 -12
  265. package/src/serve/hub-app/polled.ts +16 -2
  266. package/src/serve/hub-app/recordings-st.ts +23 -2
  267. package/src/serve/hub-app/recordings-view.tsx +68 -10
  268. package/src/serve/hub-app/ref-pill.ts +1 -1
  269. package/src/serve/hub-app/repo-st.ts +1 -2
  270. package/src/serve/hub-app/review/advisor-add.tsx +1 -1
  271. package/src/serve/hub-app/review/advisor-invite.tsx +1 -1
  272. package/src/serve/hub-app/review/draft-body.tsx +2 -2
  273. package/src/serve/hub-app/review/heard-line.tsx +1 -1
  274. package/src/serve/hub-app/review/instructions-view.tsx +1 -8
  275. package/src/serve/hub-app/review/kind-states.tsx +14 -9
  276. package/src/serve/hub-app/review/kit.tsx +4 -11
  277. package/src/serve/hub-app/review/lane-bar.tsx +3 -3
  278. package/src/serve/hub-app/review/lightbox.tsx +15 -11
  279. package/src/serve/hub-app/review/line-window.ts +4 -1
  280. package/src/serve/hub-app/review/live-bar-st.ts +2 -2
  281. package/src/serve/hub-app/review/live-view.tsx +57 -1
  282. package/src/serve/hub-app/review/object-panel.tsx +20 -8
  283. package/src/serve/hub-app/review/question-views.tsx +181 -54
  284. package/src/serve/hub-app/review/recap-bar.tsx +40 -0
  285. package/src/serve/hub-app/review/request-cell.tsx +48 -0
  286. package/src/serve/hub-app/review/review-cells.tsx +154 -96
  287. package/src/serve/hub-app/review/review-host.ts +2 -2
  288. package/src/serve/hub-app/review/review-kit.ts +17 -11
  289. package/src/serve/hub-app/review/review-list.tsx +23 -31
  290. package/src/serve/hub-app/review/review-st.ts +30 -40
  291. package/src/serve/hub-app/review/review-thread.tsx +139 -85
  292. package/src/serve/hub-app/review/review-views.tsx +124 -68
  293. package/src/serve/hub-app/review/share-lines.tsx +4 -4
  294. package/src/serve/hub-app/review/start-st.ts +2 -5
  295. package/src/serve/hub-app/review/superseded-runs.ts +4 -3
  296. package/src/serve/hub-app/review/thread-close.tsx +10 -7
  297. package/src/serve/hub-app/review/thread-st.ts +372 -201
  298. package/src/serve/hub-app/review/tone-bar.tsx +126 -0
  299. package/src/serve/hub-app/review/tones.ts +35 -0
  300. package/src/serve/hub-app/review/trailer-body.tsx +2 -2
  301. package/src/serve/hub-app/review/trailer-st.ts +3 -2
  302. package/src/serve/hub-app/review/trailer-voices-st.ts +3 -2
  303. package/src/serve/hub-app/review.css +180 -106
  304. package/src/serve/hub-app/search-view.tsx +1 -1
  305. package/src/serve/hub-app/social/social-model.ts +0 -4
  306. package/src/serve/hub-app/source-acts.ts +2 -1
  307. package/src/serve/hub-app/stores/stores-page.tsx +2 -2
  308. package/src/serve/hub-app/terminal-sources.tsx +2 -1
  309. package/src/serve/hub-app/thread-row.tsx +3 -4
  310. package/src/serve/hub-app/tree-build.ts +0 -4
  311. package/src/serve/hub-app/urls-view.tsx +2 -1
  312. package/src/serve/hub-app/view-layout.css +13 -3
  313. package/src/serve/hub-app/wikis-view.tsx +5 -2
  314. package/src/serve/hub-runtime.ts +7 -37
  315. package/src/serve/project-gutter-route.ts +6 -2
  316. package/src/serve/read-thread.ts +20 -2
  317. package/src/serve/read-worker.ts +9 -1
  318. package/src/serve/record-pages.ts +46 -0
  319. package/src/serve/serve-hub.ts +2 -2
  320. package/src/serve/terminal-host.ts +1 -1
  321. package/src/serve/terminal-route.ts +1 -3
  322. package/src/serve/tracked-watch.ts +1 -3
  323. package/src/setup-house.ts +2 -2
  324. package/src/shipkit-files.ts +1 -1
  325. package/src/shipkit.ts +1 -6
  326. package/src/shot/film-box.ts +0 -20
  327. package/src/social/drafts.ts +1 -1
  328. package/src/social/kinds.ts +6 -29
  329. package/src/social/load.ts +2 -2
  330. package/src/social/post-object.ts +3 -2
  331. package/src/social/release-stage.ts +1 -1
  332. package/src/social/stage.ts +2 -2
  333. package/src/stores/model.ts +4 -0
  334. package/src/stores/routes.ts +11 -3
  335. package/src/suite/judge-suites.ts +58 -0
  336. package/src/suite/red-alone.ts +54 -18
  337. package/src/suite/runner-shapes.ts +2 -2
  338. package/src/suite/suite-cli.ts +67 -14
  339. package/src/suite/test-units.ts +2 -1
  340. package/src/urls/fill.ts +1 -1
  341. package/src/urls/places.ts +1 -2
  342. package/src/vault/vault-config.ts +2 -2
  343. package/src/vault/vault-init.ts +1 -5
  344. package/src/wiki/graph-page.ts +14 -2
  345. package/src/advisors/copy-truth.ts +0 -49
  346. package/src/advisors/door-child.ts +0 -112
  347. package/src/advisors/door-serve.ts +0 -52
  348. package/src/advisors/door.ts +0 -118
  349. package/src/checks/SK016-legacy-check-shapes.check.ts +0 -189
  350. package/src/checks/SK029-explicit-check-files.check.ts +0 -112
  351. package/src/checks/SK048-one-local-file.check.ts +0 -36
  352. package/src/core/config-rewrite.ts +0 -111
  353. package/src/core/daemon-port.ts +0 -10
  354. package/src/core/legacy-shapes.ts +0 -263
  355. package/src/core/migrate-layout.ts +0 -638
  356. package/src/core/port-check-cli.ts +0 -52
  357. package/src/core/port-check-file.ts +0 -295
  358. package/src/core/port-check-files.ts +0 -31
  359. package/src/gate/discover-legacy-checks.ts +0 -26
  360. package/src/home/home-move.ts +0 -527
  361. package/src/home/machine-fold.ts +0 -810
  362. package/src/hq/item-shapes.ts +0 -54
  363. package/src/hq/kinds/items-read.ts +0 -4
  364. package/src/media-store/backup/daemon.ts +0 -220
  365. package/src/media-store/backup/kept.ts +0 -241
  366. package/src/media-store/backup/prune.ts +0 -359
  367. package/src/media-store/backup/secret.ts +0 -88
  368. package/src/media-store/backup/ssh-space.ts +0 -202
  369. package/src/media-store/backup/watch.ts +0 -117
  370. package/src/review/band.ts +0 -182
  371. package/src/review/folders.ts +0 -216
  372. package/src/review/hook-ask.ts +0 -58
  373. package/src/review/role.ts +0 -48
  374. package/src/review/thread-fold.ts +0 -64
  375. package/src/review/wait.ts +0 -91
  376. package/src/rules/rule.ts +0 -43
  377. package/src/serve/hook-thread.ts +0 -37
  378. package/src/serve/hook-work.ts +0 -92
  379. package/src/serve/hook-worker.ts +0 -57
  380. package/src/serve/hub-app/review/dock.tsx +0 -147
  381. package/src/serve/hub-app/review/faces.tsx +0 -18
  382. package/src/serve/hub-app/review/item-verdict.tsx +0 -112
  383. package/src/serve/hub-app/review/review-board.tsx +0 -48
  384. /package/src/{scaffold → core}/jsonc-spans.ts +0 -0
@@ -1,638 +0,0 @@
1
- // layout-sweep: skip
2
- // Carry a repo from the old root layout to `.shipkit/` (core/layout.ts), and
3
- // repair a contract folder typed under a wrong name, in ONE pass and ONE commit.
4
- //
5
- // Nothing here is a decision, so no human is asked: `.rv-<x>/` became
6
- // `.shipkit/<x>/`, `asks/`, `hooks/` and the `tmp/` scratch moved in (its dated
7
- // plans into `.shipkit/plans/`), the generated files moved out of the root. A typo (`rv-reflections`, `.rv-reflection`) is the same
8
- // move, because a folder under a name no scanner reads is silence.
9
- //
10
- // The invariant a reader breaks first: A MOVE NEVER CHANGES WHAT GIT TRACKS.
11
- // A tracked file stays tracked under its new name (added with -f, because
12
- // `.shipkit/*` is ignored and only some children are re-included), an
13
- // untracked file moves on disk and stays untracked. The one exception is a
14
- // typo folder, whose files git only tracked because the missing dot kept the
15
- // ignore rule from matching: those leave the index when the target is ignored.
16
- //
17
- // A file carrying the SWEEP_SKIP marker is never rewritten: it names the old
18
- // layout on purpose (this module, its tests, the legacy lines of SK004).
19
- //
20
- // Refusals, every one retried by the next run and printed by the caller:
21
- // a target that already holds files (merging decides which file wins), a
22
- // tracked path to move or rewrite that carries uncommitted edits (the commit
23
- // would take them along), a merge or rebase in progress, a nested repo.
24
- import { accessSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'
25
- import { homedir } from 'os'
26
- import { dirname, join, posix } from 'path'
27
- import type { RepoConfig } from '../repo-config.ts'
28
- import { gitBin } from './git-bin.ts'
29
- import { probeGitRoot } from './git-root.ts'
30
- import { ASK_FILES_DIR, LAYOUT, MACHINE_PRIVATE, PLAN_FILE, SHIPKIT_DIR } from './layout.ts'
31
- import { machineCommit } from './machine-commit.ts'
32
- import { nestedIn } from './nesting.ts'
33
-
34
- /** the prefix every contract folder carried before `.shipkit/` */
35
- export const LEGACY_CONTRACT_PREFIX = '.rv-'
36
-
37
- const CONFIG_FILE = 'repo.config.ts'
38
-
39
- /** what one pass did, in words: the folders it moved and the root files it
40
- * dropped. Empty when it did neither, so no caller prints a sentence with a
41
- * hole where the list should be */
42
- export function layoutSummary(r: { moved: LayoutMove[]; removed: string[] }): string {
43
- const list = (xs: string[]): string => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs.at(-1)}`)
44
- const folders = r.moved.filter((m) => m.kind !== 'cache' && m.kind !== 'plan').map((m) => `${m.from}/`)
45
- const plans = r.moved.filter((m) => m.kind === 'plan').length
46
- const parts = [
47
- ...(folders.length > 0 ? [`move ${list(folders)} under ${SHIPKIT_DIR}/`] : []),
48
- ...(plans > 0 ? [`file ${plans} plan${plans === 1 ? '' : 's'} under ${LAYOUT.plans}/`] : []),
49
- ...(r.removed.length > 0 ? [`drop the root ${list(r.removed)}, which shipkit writes under ${SHIPKIT_DIR}/`] : []),
50
- ]
51
- return parts.join(', and ')
52
- }
53
-
54
- /** the contract names a typo is matched against */
55
- const KNOWN = ['identity', 'assets', 'comfy', 'private', 'reflections', 'social', 'journal', 'domain', 'itch', 'steam', 'discord', 'chrome-web-store'] as const
56
-
57
- /** root files shipkit used to generate on every run */
58
- export const LEGACY_GENERATED = ['STATUS.md', 'STATUS.md.lock', 'STATUS.full.md', 'STATUS.full.md.lock'] as const
59
-
60
- /** the root scratch folder, `.shipkit/tmp/` now */
61
- export const LEGACY_TMP = 'tmp'
62
-
63
- const LEGACY_CACHE = `${LEGACY_TMP}/.shipkit`
64
-
65
- /** a lease a killed run left in the old scratch: never worth a refusal, the
66
- * one at the target is the live one */
67
- const STALE_LEASE = /^shipkit-[^/]+\.lock$/
68
-
69
- /** what the old policy block kept out of git, rendered by SK004 while a repo
70
- * still holds `.rv-*` folders so none of them is exposed before it moves */
71
- export const LEGACY_VENUES = ['.rv-itch/', '.rv-steam/', '.rv-discord/']
72
- export const LEGACY_IGNORED = ['.rv-private/', '.rv-reflections/', '.rv-social/', '.rv-journal/', '.rv-domain/', '.rv-assets/out/', ...LEGACY_VENUES]
73
-
74
- /** the shape of a name, ignoring the leading dots, the separators, the case and
75
- * a trailing plural. `rv-reflections`, `rv_reflection` and `RV-Reflections`
76
- * are the same intent, `reflections` and `docs` are not */
77
- const shapeOf = (s: string): string => s.toLowerCase().replace(/^\.+/, '').replace(/[-_.]/g, '').replace(/s$/, '')
78
-
79
- const LEGACY_NAME = /^\.rv-([a-z0-9][a-z0-9-]*)$/
80
-
81
- /** 'plan' moves one FILE, every other kind a folder */
82
- export type MoveKind = 'contract' | 'typo' | 'asks' | 'hooks' | 'cache' | 'tmp' | 'plan'
83
- /** a move onto a folder that already exists, whose files collide nowhere.
84
- * `drop`: stale leases left behind rather than moved over the live ones */
85
- export type MergeMove = LayoutMove & { merge: true; drop?: string[] }
86
- export type LayoutMove = { from: string; to: string; kind: MoveKind }
87
- export type LayoutRefusal = { from: string; to: string; reason: string }
88
- export type LayoutPlan = { moves: LayoutMove[]; refusals: LayoutRefusal[] }
89
-
90
- export type PlanInput = {
91
- /** directory names at the repo root */
92
- rootDirs: string[]
93
- /** names already under `.shipkit/` */
94
- shipkitEntries?: string[]
95
- /** core.hooksPath points at `hooks/` and its pre-commit is shipkit's */
96
- hooksOurs?: boolean
97
- /** `tmp/.shipkit` exists */
98
- legacyCache?: boolean
99
- /** a clone or a worktree sits somewhere under `tmp/` */
100
- tmpHoldsRepo?: boolean
101
- /** file names at the top of `tmp/` */
102
- tmpFiles?: string[]
103
- /** names already under `.shipkit/plans/` */
104
- planEntries?: string[]
105
- }
106
-
107
- /** a `.git` anywhere under a folder: a clone or a linked worktree, whose
108
- * registration names its path, so moving it breaks it */
109
- export function holdsRepo(dir: string): boolean {
110
- try {
111
- for (const e of readdirSync(dir, { withFileTypes: true })) {
112
- if (e.name === '.git') return true
113
- if (e.isDirectory() && e.name !== 'node_modules' && holdsRepo(join(dir, e.name))) return true
114
- }
115
- } catch { /* unreadable: the move itself reports it */ }
116
- return false
117
- }
118
-
119
- /** PURE: what to move, given what sits in a repo root */
120
- export function planLayoutMigration(i: PlanInput): LayoutPlan {
121
- const taken = new Set((i.shipkitEntries ?? []).map((e) => `${SHIPKIT_DIR}/${e}`))
122
- const moves: LayoutMove[] = []
123
- const refusals: LayoutRefusal[] = []
124
- const add = (from: string, to: string, kind: MoveKind): void => {
125
- const twin = moves.find((m) => m.to === to)
126
- if (taken.has(to)) {
127
- refusals.push({ from, to, reason: `${twin != null ? `${twin.from}/ moves there too` : 'the target already exists'}, and merging them decides which file wins` })
128
- return
129
- }
130
- taken.add(to)
131
- moves.push({ from, to, kind })
132
- }
133
- // exact legacy names first, so a typo beside its correct twin is the one refused
134
- const dirs = [...i.rootDirs].sort((a, b) => Number(!LEGACY_NAME.test(a)) - Number(!LEGACY_NAME.test(b)) || a.localeCompare(b))
135
- for (const d of dirs) {
136
- const m = LEGACY_NAME.exec(d)
137
- // a legacy name one plural or separator off a known one lands on the known one
138
- if (m != null) { add(d, `${SHIPKIT_DIR}/${KNOWN.find((k) => shapeOf(k) === shapeOf(m[1]!)) ?? m[1]}`, 'contract'); continue }
139
- if (d === SHIPKIT_DIR) continue
140
- const typo = KNOWN.find((k) => shapeOf(d) === shapeOf(`rv${k}`))
141
- if (typo != null) add(d, `${SHIPKIT_DIR}/${typo}`, 'typo')
142
- }
143
- // an old queue of ask files goes where `sk asks migrate` reads it into the thread store
144
- if (i.rootDirs.includes('asks')) add('asks', ASK_FILES_DIR, 'asks')
145
- if (i.rootDirs.includes('hooks') && i.hooksOurs === true) add('hooks', LAYOUT.hooks, 'hooks')
146
- // a cache is never worth a refusal: a warm one at the target wins. It
147
- // leaves the scratch before the scratch itself moves
148
- if (i.legacyCache === true) {
149
- if (taken.has(LAYOUT.cache)) moves.push({ from: LEGACY_CACHE, to: LAYOUT.cache, kind: 'cache' })
150
- else add(LEGACY_CACHE, LAYOUT.cache, 'cache')
151
- }
152
- // every repo's scratch, shipkit's own logs and the repo's plans alike
153
- if (i.rootDirs.includes(LEGACY_TMP)) {
154
- if (i.tmpHoldsRepo === true) refusals.push({ from: LEGACY_TMP, to: LAYOUT.tmp, reason: 'a git checkout sits under it, and a moved worktree loses its registration' })
155
- else {
156
- // a dated plan is live state, so it lands where plans live, never in
157
- // the scratch any agent may empty. A name already taken there stays
158
- // with the scratch rather than overwrite a plan
159
- const taken = new Set(i.planEntries ?? [])
160
- for (const f of (i.tmpFiles ?? []).filter((f) => PLAN_FILE.test(f) && !taken.has(f)).sort())
161
- moves.push({ from: `${LEGACY_TMP}/${f}`, to: `${LAYOUT.plans}/${f}`, kind: 'plan' })
162
- add(LEGACY_TMP, LAYOUT.tmp, 'tmp')
163
- }
164
- }
165
- return { moves, refusals }
166
- }
167
-
168
- /** the text rewrite a contract move implies: `.rv-<x>` → its target
169
- * (`.shipkit/<x>` unless `targets` says otherwise), never a machine-global
170
- * `~/.rv-<x>`, never a longer name that merely starts the same.
171
- *
172
- * `at` is the file's own path before and after the move. A relative path
173
- * (`../.rv-identity/brand.ts`) that resolved to a moved folder is recomputed
174
- * from the file's new place, so two folders that moved together still find
175
- * each other (`../identity/brand.ts`). */
176
- export function sweepText(text: string, targets: Record<string, string> | 'all', at?: { from: string; to: string }): string {
177
- const names = targets === 'all' ? null : Object.keys(targets)
178
- if (names != null && names.length === 0) return text
179
- const alt = names == null ? '[a-z0-9][a-z0-9-]*' : names.map((n) => n.slice(LEGACY_CONTRACT_PREFIX.length).replace(/[-]/g, '\\-')).join('|')
180
- const re = new RegExp(`(?<!~/)(?<![\\w.-])((?:\\.\\.?/)*)\\.rv-(${alt})(?![\\w-])`, 'g')
181
- return text.replace(re, (_m, prefix: string, x: string) => {
182
- const legacy = `${LEGACY_CONTRACT_PREFIX}${x}`
183
- const target = (targets === 'all' ? undefined : targets[legacy]) ?? `${SHIPKIT_DIR}/${x}`
184
- if (prefix === '' || at == null || posix.normalize(posix.join(posix.dirname(at.from), prefix + legacy)) !== legacy) return prefix + target
185
- return relativeFrom(at.to, target)
186
- })
187
- }
188
-
189
- /** a relative specifier from one repo path to another, always starting with `./` or `../` */
190
- const relativeFrom = (file: string, target: string): string => {
191
- const rel = posix.relative(posix.dirname(file), target)
192
- return rel.startsWith('../') ? rel : `./${rel}`
193
- }
194
-
195
- /** the same for a path built at run time from the file's own folder:
196
- * `join(import.meta.dir, '..', 'public/x.png')` resolved to the repo root from
197
- * `.rv-identity/`, and must climb one more level from `.shipkit/identity/`.
198
- * Only the leading `'.'` and `'..'` arguments are rewritten */
199
- function rebaseDirJoins(text: string, at: { from: string; to: string }, moves: LayoutMove[]): string {
200
- return text.replace(/\b(join|resolve)\((\s*)(import\.meta\.dirname|import\.meta\.dir|__dirname)((?:\s*,\s*(['"])\.\.?\5)+)/g, (m, fn: string, sp: string, base: string, segs: string) => {
201
- const q = /['"]/.exec(segs)![0]
202
- const parts = [...segs.matchAll(/(['"])(\.\.?)\1/g)].map((x) => x[2]!)
203
- const target = movedTo(moves, posix.normalize(posix.join(posix.dirname(at.from), ...parts)))
204
- if (target.startsWith('../')) return m
205
- const rel = posix.relative(posix.dirname(at.to), target)
206
- const next = rel === '' ? [] : rel.split('/')
207
- if (next.some((x) => x !== '..') || next.join('/') === parts.filter((x) => x !== '.').join('/')) return m
208
- return `${fn}(${sp}${base}${next.map((x) => `, ${q}${x}${q}`).join('')}`
209
- })
210
- }
211
-
212
- /** PURE: a file that moved keeps pointing at what it pointed at. Only what is
213
- * a path by its SHAPE is touched: an import or require specifier, a markdown
214
- * link, and `join(import.meta.dir, '..')`. Any other string is left alone,
215
- * because `'../'` in `p.replace('../', '')` is not a path. Each path is
216
- * resolved from where the file WAS, carried through the moves, and written
217
- * from where it IS; one that still resolves the same way stays byte for byte */
218
- export function rebaseRelative(text: string, at: { from: string; to: string }, moves: LayoutMove[]): string {
219
- if (at.from === at.to) return text
220
- const rebase = (spec: string): string => {
221
- const target = movedTo(moves, posix.normalize(posix.join(posix.dirname(at.from), spec)))
222
- if (target.startsWith('../')) return spec
223
- return posix.normalize(posix.join(posix.dirname(at.to), spec)) === target ? spec : relativeFrom(at.to, target)
224
- }
225
- return rebaseDirJoins(text, at, moves)
226
- .replace(/(\bfrom\s+|\bimport\s+|\bimport\s*\(\s*|\brequire\s*\(\s*)(['"])(\.\.?\/[^'"\s]+)\2/g, (_m, lead: string, q: string, spec: string) => `${lead}${q}${rebase(spec)}${q}`)
227
- .replace(/(\]\()(\.\.?\/[^)\s#]+)/g, (_m, lead: string, spec: string) => `${lead}${rebase(spec)}`)
228
- }
229
-
230
- /** one repo.config.ts value that names a moved folder, as a path: the folder
231
- * then a slash, behind an optional `!`, `/` or `./`. A word, a bare folder
232
- * name and a longer name that merely starts the same stay as they are */
233
- function rebasePathValue(v: string, moves: LayoutMove[]): string {
234
- const m = /^(!?(?:\/|\.\/)?)(.*)$/s.exec(v)!
235
- const rest = m[2]!
236
- const hit = moves.find((x) => rest.startsWith(`${x.from}/`))
237
- return hit == null ? v : `${m[1]}${hit.to}${rest.slice(hit.from.length)}`
238
- }
239
-
240
- /** PURE: repo.config.ts source with every quoted path that names a moved
241
- * folder rewritten (`leakAllow` paths, `blockedPaths`, `gitignore` lines, a
242
- * prose include, any other value): each of them is a repo path by contract */
243
- export function sweepConfigSource(text: string, moves: LayoutMove[]): string {
244
- if (moves.length === 0) return text
245
- return text.replace(/(['"`])((?:\\.|(?!\1)[^\\\n])*)\1/g, (lit, q: string, body: string) => {
246
- if (q === '`' && body.includes('${')) return lit
247
- const next = rebasePathValue(body, moves)
248
- return next === body ? lit : `${q}${next}${q}`
249
- })
250
- }
251
-
252
- /** PURE: the loaded config with the same rewrite, so what this pass renders
253
- * from it (the ignore block) reads the values the file now holds. Only plain
254
- * objects and arrays are copied; functions and class instances are kept */
255
- export function rebaseConfigPaths<T>(v: T, moves: LayoutMove[]): T {
256
- if (typeof v === 'string') return rebasePathValue(v, moves) as T
257
- if (Array.isArray(v)) return v.map((x) => rebaseConfigPaths(x, moves)) as T
258
- if (v != null && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype)
259
- return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, rebaseConfigPaths(x, moves)])) as T
260
- return v
261
- }
262
-
263
- /** PURE: the .gitignore after the move. Old names turn into new ones, except
264
- * the folders still on disk (`keep`), whose lines keep guarding them. A
265
- * negation of one FILE inside a folder (`!.shipkit/social/README.md`) is dead
266
- * under `.shipkit/*`, because git never looks inside an excluded folder, so
267
- * the folder is re-included and re-ignored first, and the file comes back */
268
- export function sweepGitignore(text: string, keep: string[] = []): string {
269
- const out: string[] = []
270
- const have = new Set(text.split('\n'))
271
- for (const line of text.split('\n')) {
272
- const kept = keep.some((k) => new RegExp(`(?<![\\w-])${k.replace(/[.]/g, '\\.')}(?![\\w-])`).test(line))
273
- const next = kept ? line : sweepText(line, 'all')
274
- const deep = /^!\.shipkit\/([^/]+)\/(.+)$/.exec(next)
275
- if (!kept && next !== line && deep != null) {
276
- for (const pre of [`!${SHIPKIT_DIR}/${deep[1]}/`, `${SHIPKIT_DIR}/${deep[1]}/*`])
277
- if (!have.has(pre)) { out.push(pre); have.add(pre) }
278
- }
279
- out.push(next)
280
- }
281
- return out.join('\n')
282
- }
283
-
284
- /** the relative file paths under a folder */
285
- const filesUnder = (dir: string, pre = ''): string[] => {
286
- const out: string[] = []
287
- for (const e of readdirSync(join(dir, pre), { withFileTypes: true })) {
288
- const rel = pre === '' ? e.name : `${pre}/${e.name}`
289
- if (e.isDirectory()) out.push(...filesUnder(dir, rel))
290
- else out.push(rel)
291
- }
292
- return out
293
- }
294
-
295
- /** a target that already exists is the normal case in a checkout that pulled
296
- * the move: the tracked files arrived, the untracked ones (drafts, private
297
- * notes) stayed behind in the old folder. When no file name exists on both
298
- * sides, merging decides nothing, so it moves. A real collision stays refused */
299
- function mergeWhereNothingCollides(root: string, plan: LayoutPlan): LayoutPlan {
300
- const moves: LayoutMove[] = [...plan.moves]
301
- const refusals: LayoutRefusal[] = []
302
- for (const r of plan.refusals) {
303
- const from = join(root, r.from)
304
- const to = join(root, r.to)
305
- const twin = moves.some((m) => m.to === r.to)
306
- const scratch = r.from === LEGACY_TMP
307
- let clash = true
308
- let drop: string[] = []
309
- try {
310
- // a plan leaves the scratch before it moves, so it collides nowhere
311
- const filed = new Set(moves.filter((m) => m.kind === 'plan').map((m) => m.from.slice(r.from.length + 1)))
312
- const both = twin || !isDir(from) || !isDir(to) ? null : filesUnder(from).filter((f) => !filed.has(f) && existsSync(join(to, f)))
313
- drop = scratch && both != null ? both.filter((f) => STALE_LEASE.test(f)) : []
314
- clash = both == null || both.length > drop.length
315
- } catch { clash = true }
316
- if (clash) refusals.push(r)
317
- else moves.push({ from: r.from, to: r.to, kind: scratch ? 'tmp' : LEGACY_NAME.test(r.from) ? 'contract' : 'typo', merge: true, ...(drop.length > 0 ? { drop } : {}) } as MergeMove)
318
- }
319
- return { moves, refusals }
320
- }
321
-
322
- /** move every entry of one folder into another that holds none of the same names */
323
- function mergeInto(from: string, to: string): void {
324
- for (const e of readdirSync(from, { withFileTypes: true })) {
325
- const src = join(from, e.name)
326
- const dst = join(to, e.name)
327
- if (e.isDirectory() && isDir(dst)) mergeInto(src, dst)
328
- else renameSync(src, dst)
329
- }
330
- rmSync(from, { recursive: true, force: true })
331
- }
332
-
333
- /** where a repo-relative path sat before the moves */
334
- const movedFrom = (moves: LayoutMove[], rel: string): string => {
335
- const m = moves.find((x) => rel === x.to || rel.startsWith(`${x.to}/`))
336
- return m == null ? rel : m.from + rel.slice(m.to.length)
337
- }
338
-
339
- const canWrite = (p: string): boolean => { try { accessSync(p, constants.W_OK); return true } catch { return false } }
340
-
341
- /** where a repo-relative path sits once the moves are made */
342
- const movedTo = (moves: LayoutMove[], rel: string): string => {
343
- const m = moves.find((x) => rel === x.from || rel.startsWith(`${x.from}/`))
344
- return m == null ? rel : m.to + rel.slice(m.from.length)
345
- }
346
-
347
- const isChangelog = (rel: string): boolean => /(^|\/)changelog\.md$/i.test(rel)
348
-
349
- /** a file that names the old layout on purpose carries this, and the sweep leaves it alone */
350
- export const SWEEP_SKIP = 'layout-sweep: skip'
351
-
352
- export type LayoutResult = {
353
- moved: LayoutMove[]
354
- refusals: LayoutRefusal[]
355
- /** tracked files whose text the sweep rewrote */
356
- swept: string[]
357
- /** legacy generated files removed from the root */
358
- removed: string[]
359
- /** why nothing happened, when nothing could */
360
- deferred?: string
361
- /** the commit, when one landed */
362
- commit?: string
363
- /** moved, and the commit did not land: the dirt is this run's */
364
- uncommitted?: true
365
- /** the paths the commit would have carried, for the one who lands it by hand */
366
- pending?: string[]
367
- }
368
-
369
- const git = (root: string, args: string[]): { code: number; out: string } => {
370
- const r = Bun.spawnSync([gitBin(), ...args], { cwd: root })
371
- return { code: r.exitCode, out: `${r.stdout.toString()}${r.stderr.toString()}` }
372
- }
373
-
374
- const dirsIn = (root: string): string[] => {
375
- try { return readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name) } catch { return [] }
376
- }
377
-
378
- const isDir = (p: string): boolean => { try { return statSync(p).isDirectory() } catch { return false } }
379
-
380
- const filesIn = (dir: string): string[] => {
381
- try { return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name) } catch { return [] }
382
- }
383
-
384
- /** does core.hooksPath point at the legacy `hooks/`, holding a shipkit pre-commit */
385
- export function legacyHooksOurs(root: string): boolean {
386
- const r = git(root, ['config', 'core.hooksPath'])
387
- const v = r.out.trim().replace(/\/+$/, '')
388
- if (v !== 'hooks' && v !== join(root, 'hooks')) return false
389
- try { return readFileSync(join(root, 'hooks', 'pre-commit'), 'utf8').includes('shipkit') } catch { return false }
390
- }
391
-
392
- /** a checkout that received the move through a merge, not through this pass,
393
- * still has core.hooksPath on the vanished `hooks/`, and git runs no hook
394
- * from a folder that is not there: the commit gates go dark in silence */
395
- function repointStaleHooks(root: string): void {
396
- // the disk decides first: git is asked only when the move has happened
397
- if (existsSync(join(root, 'hooks')) || !existsSync(join(root, LAYOUT.hooks, 'pre-commit'))) return
398
- const v = git(root, ['config', 'core.hooksPath']).out.trim().replace(/\/+$/, '')
399
- if (v !== 'hooks' && v !== join(root, 'hooks')) return
400
- git(root, ['config', 'core.hooksPath', LAYOUT.hooks])
401
- }
402
-
403
- /** the machine-global private folder moves the same way, once per machine.
404
- * The old path stays as a symlink to the new one, so a repo still on an
405
- * older shipkit keeps reading its keyword list. The link goes once
406
- * `shipkit fleet` shows no repo on a version that reads it */
407
- export function moveMachinePrivate(home: string): void {
408
- if (home === '') return
409
- const old = join(home, '.rv-private')
410
- const next = join(home, MACHINE_PRIVATE)
411
- try {
412
- if (!lstatSync(old).isDirectory() || existsSync(next)) return
413
- mkdirSync(dirname(next), { recursive: true })
414
- renameSync(old, next)
415
- symlinkSync(posix.relative(home, next), old)
416
- } catch { /* absent, or a link already: nothing to move */ }
417
- }
418
-
419
- /** what the planner reads off disk */
420
- export function readPlanInput(root: string): PlanInput {
421
- return {
422
- rootDirs: dirsIn(root),
423
- shipkitEntries: isDir(join(root, SHIPKIT_DIR)) ? readdirSync(join(root, SHIPKIT_DIR)) : [],
424
- hooksOurs: existsSync(join(root, 'hooks')) && legacyHooksOurs(root),
425
- legacyCache: isDir(join(root, LEGACY_CACHE)),
426
- tmpHoldsRepo: isDir(join(root, LEGACY_TMP)) && holdsRepo(join(root, LEGACY_TMP)),
427
- tmpFiles: filesIn(join(root, LEGACY_TMP)),
428
- planEntries: isDir(join(root, LAYOUT.plans)) ? readdirSync(join(root, LAYOUT.plans)) : [],
429
- }
430
- }
431
-
432
- /** a repo still carrying the old layout: the names a check reports */
433
- export function legacyLayoutLeft(root: string): string[] {
434
- const plan = planLayoutMigration(readPlanInput(root))
435
- return [...plan.moves.filter((m) => m.kind !== 'cache' && m.kind !== 'plan').map((m) => `${m.from}/`), ...plan.refusals.map((r) => `${r.from}/`)]
436
- }
437
-
438
- const lsFiles = (root: string, paths: string[]): string[] => {
439
- if (paths.length === 0) return []
440
- const r = git(root, ['ls-files', '-z', '--', ...paths])
441
- return r.code === 0 ? r.out.split('\0').filter((l) => l !== '') : []
442
- }
443
-
444
- /** tracked text files naming a legacy folder, CHANGELOG files left as history */
445
- function sweepTargets(root: string, legacyNames: string[]): string[] {
446
- if (legacyNames.length === 0) return []
447
- const r = git(root, ['grep', '-lIz', '-F', ...legacyNames.flatMap((n) => ['-e', n])])
448
- if (r.code !== 0) return []
449
- return r.out.split('\0').filter((l) => l !== '' && !isChangelog(l) && l !== '.gitignore')
450
- }
451
-
452
- /** tracked paths among these with staged or unstaged edits */
453
- function dirtyAmong(root: string, paths: string[]): string[] {
454
- if (paths.length === 0) return []
455
- const r = git(root, ['status', '--porcelain', '-z', '--untracked-files=no', '--', ...paths])
456
- return r.out.split('\0').filter((l) => l.length > 3).map((l) => l.slice(3))
457
- }
458
-
459
- function inProgress(root: string): string | null {
460
- const g = probeGitRoot(root).root
461
- if (g == null) return null
462
- for (const f of ['MERGE_HEAD', 'REBASE_HEAD', 'CHERRY_PICK_HEAD', 'rebase-merge', 'rebase-apply'])
463
- if (existsSync(join(g.gitDir, f))) return `a ${f.toLowerCase().replace(/_head$/, '').replace(/-.*/, '')} is in progress`
464
- if (git(root, ['symbolic-ref', '--quiet', 'HEAD']).code !== 0) return 'HEAD is detached'
465
- return null
466
- }
467
-
468
- export type MigrateOpts = {
469
- config?: RepoConfig
470
- /** re-render the SK004 block into this .gitignore text (SK004 owns the
471
- * block). `legacy`: an old folder is still on disk, so its name stays
472
- * ignored. `config`: the repo config with its paths already moved, which
473
- * is what the block must be rendered from */
474
- renderGitignore?: (text: string, legacy: boolean, config?: RepoConfig) => string
475
- }
476
-
477
- /** tracked symlinks, with where each points */
478
- function trackedLinks(root: string): { rel: string; target: string }[] {
479
- const r = git(root, ['ls-files', '-s', '-z'])
480
- if (r.code !== 0) return []
481
- const out: { rel: string; target: string }[] = []
482
- for (const row of r.out.split('\0')) {
483
- if (!row.startsWith('120000 ')) continue
484
- const rel = row.slice(row.indexOf('\t') + 1)
485
- try { out.push({ rel, target: readlinkSync(join(root, rel)) }) } catch { /* gone from disk: nothing to relink */ }
486
- }
487
- return out
488
- }
489
-
490
- /**
491
- * Apply the plan. Returns what moved, what the sweep rewrote and whether the
492
- * commit landed. Never throws: a permission error or a race leaves the repo
493
- * where it was, and the next run tries again.
494
- */
495
- export function migrateLayout(root: string, o: MigrateOpts = {}): LayoutResult {
496
- repointStaleHooks(root)
497
- moveMachinePrivate(homedir())
498
- const input = readPlanInput(root)
499
- const plan = mergeWhereNothingCollides(root, planLayoutMigration(input))
500
- const legacyStatus = LEGACY_GENERATED.filter((f) => existsSync(join(root, f)))
501
- const out: LayoutResult = { moved: [], refusals: plan.refusals, swept: [], removed: [] }
502
- if (plan.moves.length === 0 && legacyStatus.length === 0) return out
503
-
504
- const inGit = probeGitRoot(root).root != null
505
- if (inGit) {
506
- if (nestedIn(root) != null) return { ...out, deferred: 'this repo is a folder of a larger git repo, whose index is not shipkit\'s to rewrite' }
507
- const busy = inProgress(root)
508
- if (busy != null) return { ...out, deferred: busy }
509
- }
510
-
511
- const contractNames = plan.moves.filter((m) => m.kind === 'contract').map((m) => m.from)
512
- const targets = Object.fromEntries(plan.moves.filter((m) => m.kind === 'contract').map((m) => [m.from, m.to]))
513
- const sources = plan.moves.filter((m) => m.kind !== 'cache').map((m) => m.from)
514
- const tracked = inGit ? lsFiles(root, [...sources, ...legacyStatus]) : []
515
- // a moved file is rebased whether or not it names an old folder, and
516
- // repo.config.ts whenever one of its values names one
517
- const configNames = inGit && lsFiles(root, [CONFIG_FILE]).length > 0 && sweepConfigSource(readFileSync(join(root, CONFIG_FILE), 'utf8'), plan.moves) !== readFileSync(join(root, CONFIG_FILE), 'utf8') ? [CONFIG_FILE] : []
518
- // a legacy generated file is dropped, never rewritten: a rewrite would
519
- // write it back after the drop, and the commit would keep it
520
- const dropped = new Set<string>(legacyStatus)
521
- const swept = inGit ? [...new Set([...sweepTargets(root, contractNames), ...tracked.filter((t) => /\.(m?[jt]sx?|json|md)$/.test(t)), ...configNames])].filter((f) => !dropped.has(f)) : []
522
- const links = inGit ? trackedLinks(root) : []
523
- // commit the ignore file when git tracks it, or when this pass creates it:
524
- // it is what keeps the moved private folders out. An existing untracked
525
- // one is the repo's choice, and naming it in the pathspec refuses the commit
526
- const giExisted = existsSync(join(root, '.gitignore'))
527
- const giTracked = inGit && lsFiles(root, ['.gitignore']).length > 0
528
- if (inGit) {
529
- const dirty = dirtyAmong(root, [...tracked, ...swept, ...links.map((l) => l.rel), '.gitignore'])
530
- if (dirty.length > 0) return { ...out, deferred: `${dirty.slice(0, 3).join(', ')}${dirty.length > 3 ? ` +${dirty.length - 3}` : ''} carries uncommitted edits, and the move commit would take them along` }
531
- }
532
-
533
- // every rewrite is computed, and every write is checked, BEFORE anything
534
- // moves: a move that stops part way leaves no old folder for the next run
535
- // to find, so there is no resuming it, only not starting it
536
- const moves = plan.moves.filter((m) => m.kind !== 'cache' || !existsSync(join(root, m.to)))
537
- const writes: { now: string; text: string }[] = []
538
- for (const rel of swept) {
539
- const text = readFileSync(join(root, rel), 'utf8')
540
- if (text.includes(SWEEP_SKIP)) continue
541
- const now = movedTo(moves, rel)
542
- const paths = rel === CONFIG_FILE ? sweepConfigSource(text, moves) : text
543
- const next = sweepText(rebaseRelative(paths, { from: rel, to: now }, moves), targets, { from: rel, to: now })
544
- if (next !== text) writes.push({ now, text: next })
545
- }
546
- const relinks: { now: string; target: string }[] = []
547
- for (const l of links) {
548
- const now = movedTo(moves, l.rel)
549
- if (l.target.startsWith('/')) continue
550
- const was = posix.normalize(posix.join(posix.dirname(l.rel), l.target))
551
- const target = movedTo(moves, was)
552
- if (target === was && now === l.rel) continue
553
- const next = posix.relative(posix.dirname(now), target)
554
- if (next !== l.target) relinks.push({ now, target: next })
555
- }
556
- const unwritable = [
557
- ...writes.map((w) => join(root, movedFrom(moves, w.now))),
558
- ...moves.flatMap((m) => [join(root, m.from), dirname(join(root, m.from))]),
559
- join(root, '.gitignore'),
560
- ].filter((p) => existsSync(p) && !canWrite(p))
561
- if (unwritable.length > 0) return { ...out, deferred: `${unwritable.slice(0, 3).map((p) => p.slice(root.length + 1) || '.').join(', ')} is not writable, so the move would stop part way` }
562
-
563
- const gi = join(root, '.gitignore')
564
- const giOriginal = existsSync(gi) ? readFileSync(gi, 'utf8') : ''
565
- const config = o.config == null ? undefined : rebaseConfigPaths(o.config, moves)
566
- const render = (text: string, legacy: boolean): string => (o.renderGitignore != null ? o.renderGitignore(text, legacy, config) : text)
567
- const stillOld = (): string[] => dirsIn(root).filter((d) => d.startsWith(LEGACY_CONTRACT_PREFIX))
568
- try {
569
- // 1. both layouts ignored while any folder is in flight
570
- const giBoth = render(sweepGitignore(giOriginal, dirsIn(root).filter((d) => d.startsWith(LEGACY_CONTRACT_PREFIX))), true)
571
- if (giBoth !== giOriginal) writeFileSync(gi, giBoth)
572
-
573
- // 2. the folders
574
- mkdirSync(join(root, SHIPKIT_DIR), { recursive: true })
575
- for (const m of plan.moves) {
576
- const from = join(root, m.from)
577
- const to = join(root, m.to)
578
- if (m.kind === 'cache' && existsSync(to)) { rmSync(from, { recursive: true, force: true }); continue }
579
- mkdirSync(dirname(to), { recursive: true })
580
- if ('merge' in m) {
581
- for (const f of (m as MergeMove).drop ?? []) rmSync(join(from, f), { force: true })
582
- mergeInto(from, to)
583
- }
584
- else renameSync(from, to)
585
- out.moved.push(m)
586
- }
587
- for (const f of legacyStatus) { rmSync(join(root, f), { force: true }); out.removed.push(f) }
588
-
589
- // 3. the text and the links that named the old folders
590
- for (const w of writes) { writeFileSync(join(root, w.now), w.text); out.swept.push(w.now) }
591
- for (const l of relinks) { rmSync(join(root, l.now), { force: true }); symlinkSync(l.target, join(root, l.now)); out.swept.push(l.now) }
592
-
593
- // 4. the old names leave the ignore file only with their folders
594
- const left = stillOld()
595
- const giFinal = render(sweepGitignore(giOriginal, left), left.length > 0)
596
- if (giFinal !== readFileSync(gi, 'utf8')) writeFileSync(gi, giFinal)
597
- } catch (e) {
598
- // whatever moved is under .shipkit/, whatever did not is still old:
599
- // both stay ignored, and nothing pretends a later run finishes it
600
- try { writeFileSync(gi, render(sweepGitignore(giOriginal, stillOld()), true)) } catch { /* the message below says what to check */ }
601
- return { ...out, deferred: `the move stopped part way (${(e as Error).message.slice(0, 120)}). What moved is under ${SHIPKIT_DIR}/ and both layouts stay ignored: finish the rest by hand, then commit` }
602
- }
603
-
604
- const hooksMoved = out.moved.some((m) => m.kind === 'hooks')
605
- if (hooksMoved && inGit) git(root, ['config', 'core.hooksPath', LAYOUT.hooks])
606
- if (!inGit) return out
607
-
608
- // 4. the index: every tracked file keeps its tracking under the new name
609
- const renamed = (rel: string): string | null => {
610
- for (const m of out.moved) if (rel === m.from || rel.startsWith(`${m.from}/`)) return m.kind === 'typo' ? null : m.to + rel.slice(m.from.length)
611
- return null
612
- }
613
- const typoTracked = tracked.filter((rel) => out.moved.some((m) => m.kind === 'typo' && rel.startsWith(`${m.from}/`)))
614
- const typoKept = typoTracked
615
- .map((rel) => { const m = out.moved.find((x) => rel.startsWith(`${x.from}/`))!; return m.to + rel.slice(m.from.length) })
616
- .filter((to) => git(root, ['check-ignore', '-q', '--no-index', to]).code !== 0)
617
- const added = [...tracked.map(renamed).filter((p): p is string => p != null), ...typoKept]
618
- if (tracked.length > 0) git(root, ['rm', '-r', '-q', '--cached', '--ignore-unmatch', '--', ...tracked])
619
- if (added.length > 0) git(root, ['add', '-f', '--', ...added])
620
- const giNew = !giExisted && existsSync(join(root, '.gitignore'))
621
- if (giNew) git(root, ['add', '--', '.gitignore'])
622
- // a swept file inside a moved folder is committed only when it stayed tracked
623
- const inMoved = (p: string): boolean => out.moved.some((m) => p.startsWith(`${m.to}/`))
624
- const sweptTracked = out.swept.filter((p) => !inMoved(p) || added.includes(p))
625
- // the ignore file rides only when this pass changed it: a second move of a
626
- // recreated tmp/ changes nothing git tracks, and an empty commit is no failure
627
- const giChanged = giNew || (giTracked && readFileSync(join(root, '.gitignore'), 'utf8') !== giOriginal)
628
- const touched = [...new Set([...tracked, ...added, ...sweptTracked, ...(giChanged ? ['.gitignore'] : [])])]
629
- if (touched.length === 0) return out
630
- // the title names what this commit carries; a pass that did neither has
631
- // nothing tracked to land and returned above
632
- const what = layoutSummary(out)
633
- if (what === '') return out
634
- const landed = machineCommit({ anchor: root, message: `chore(machine): ${what}`, paths: touched.map((p) => join(root, p)) })
635
- if (!landed) return { ...out, uncommitted: true, pending: touched }
636
- out.commit = git(root, ['rev-parse', '--short', 'HEAD']).out.trim()
637
- return out
638
- }