@smoothbricks/nx-plugin 0.4.25 → 0.4.27

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 (348) hide show
  1. package/README.md +1078 -98
  2. package/dist/bin/smoo-nx-bound-failures.d.ts +3 -0
  3. package/dist/bin/smoo-nx-bound-failures.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-bound-failures.js +31 -0
  5. package/dist/bin/smoo-nx-cargo-hash.js +28 -3
  6. package/dist/bin/smoo-nx-exec.js +16 -85
  7. package/dist/bin/smoo-nx-failures.d.ts +3 -0
  8. package/dist/bin/smoo-nx-failures.d.ts.map +1 -0
  9. package/dist/bin/smoo-nx-failures.js +3 -0
  10. package/dist/bin/smoo-nx-nextest-extract.js +3 -2
  11. package/dist/bin/smoo-nx-test-walks.d.ts +3 -0
  12. package/dist/bin/smoo-nx-test-walks.d.ts.map +1 -0
  13. package/dist/bin/smoo-nx-test-walks.js +34 -0
  14. package/dist/bounded-test-policy.d.ts +7 -1
  15. package/dist/bounded-test-policy.d.ts.map +1 -1
  16. package/dist/bounded-test-policy.js +101 -40
  17. package/dist/build-state-output-policy.d.ts +25 -0
  18. package/dist/build-state-output-policy.d.ts.map +1 -0
  19. package/dist/build-state-output-policy.js +64 -0
  20. package/dist/cargo-closure-input.d.ts +16 -17
  21. package/dist/cargo-closure-input.d.ts.map +1 -1
  22. package/dist/cargo-closure-input.js +37 -44
  23. package/dist/cargo-dev-profile.d.ts +37 -0
  24. package/dist/cargo-dev-profile.d.ts.map +1 -0
  25. package/dist/cargo-dev-profile.js +108 -0
  26. package/dist/cargo-source-hash.d.ts +50 -8
  27. package/dist/cargo-source-hash.d.ts.map +1 -1
  28. package/dist/cargo-source-hash.js +691 -71
  29. package/dist/cargo-toolchain-policy.d.ts +4 -0
  30. package/dist/cargo-toolchain-policy.d.ts.map +1 -1
  31. package/dist/cargo-toolchain-policy.js +5 -0
  32. package/dist/cargo-workspace.d.ts +108 -12
  33. package/dist/cargo-workspace.d.ts.map +1 -1
  34. package/dist/cargo-workspace.js +299 -18
  35. package/dist/cross-check-policy.d.ts +21 -3
  36. package/dist/cross-check-policy.d.ts.map +1 -1
  37. package/dist/cross-check-policy.js +24 -6
  38. package/dist/disk-command-policy.d.ts +7 -0
  39. package/dist/disk-command-policy.d.ts.map +1 -0
  40. package/dist/disk-command-policy.js +98 -0
  41. package/dist/ensure-built-receipt.d.ts +25 -0
  42. package/dist/ensure-built-receipt.d.ts.map +1 -0
  43. package/dist/ensure-built-receipt.js +261 -0
  44. package/dist/ensure-built-witness.d.ts +57 -0
  45. package/dist/ensure-built-witness.d.ts.map +1 -0
  46. package/dist/ensure-built-witness.js +412 -0
  47. package/dist/ensure-built.d.ts +213 -12
  48. package/dist/ensure-built.d.ts.map +1 -1
  49. package/dist/ensure-built.js +624 -177
  50. package/dist/eslint-file-set.d.ts +7 -0
  51. package/dist/eslint-file-set.d.ts.map +1 -0
  52. package/dist/eslint-file-set.js +12 -0
  53. package/dist/executors/bounded-exec/cpu-pool.d.ts +63 -0
  54. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -0
  55. package/dist/executors/bounded-exec/cpu-pool.js +379 -0
  56. package/dist/executors/bounded-exec/cpu-tokens.d.ts +82 -0
  57. package/dist/executors/bounded-exec/cpu-tokens.d.ts.map +1 -0
  58. package/dist/executors/bounded-exec/cpu-tokens.js +114 -0
  59. package/dist/executors/bounded-exec/disk-lease.d.ts +61 -0
  60. package/dist/executors/bounded-exec/disk-lease.d.ts.map +1 -0
  61. package/dist/executors/bounded-exec/disk-lease.js +91 -0
  62. package/dist/executors/bounded-exec/executor.d.ts +45 -2
  63. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  64. package/dist/executors/bounded-exec/executor.js +447 -52
  65. package/dist/executors/bounded-exec/gateway-lease.d.ts +52 -0
  66. package/dist/executors/bounded-exec/gateway-lease.d.ts.map +1 -0
  67. package/dist/executors/bounded-exec/gateway-lease.js +143 -0
  68. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +35 -0
  69. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -0
  70. package/dist/executors/bounded-exec/hang-diagnostics.js +231 -0
  71. package/dist/executors/bounded-exec/progress.d.ts +35 -0
  72. package/dist/executors/bounded-exec/progress.d.ts.map +1 -0
  73. package/dist/executors/bounded-exec/progress.js +79 -0
  74. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts +3 -0
  75. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts.map +1 -0
  76. package/dist/executors/bounded-exec/ram-temp-fixtures.js +12 -0
  77. package/dist/executors/bounded-exec/ram-temp-held.d.ts +91 -0
  78. package/dist/executors/bounded-exec/ram-temp-held.d.ts.map +1 -0
  79. package/dist/executors/bounded-exec/ram-temp-held.js +152 -0
  80. package/dist/executors/bounded-exec/ram-temp.d.ts +223 -0
  81. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -0
  82. package/dist/executors/bounded-exec/ram-temp.js +1528 -0
  83. package/dist/executors/bounded-exec/schema.d.ts +29 -11
  84. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  85. package/dist/executors/bounded-exec/verdict.d.ts +162 -0
  86. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -0
  87. package/dist/executors/bounded-exec/verdict.js +318 -0
  88. package/dist/executors/shard-timings/executor.d.ts +14 -0
  89. package/dist/executors/shard-timings/executor.d.ts.map +1 -0
  90. package/dist/executors/shard-timings/executor.js +25 -0
  91. package/dist/executors/shard-timings/schema.d.ts +4 -0
  92. package/dist/executors/shard-timings/schema.d.ts.map +1 -0
  93. package/dist/executors/shard-timings/schema.js +1 -0
  94. package/dist/failure-summary.d.ts +5 -0
  95. package/dist/failure-summary.d.ts.map +1 -0
  96. package/dist/failure-summary.js +118 -0
  97. package/dist/generators/create-package/generator.d.ts.map +1 -1
  98. package/dist/generators/create-package/generator.js +6 -2
  99. package/dist/index.d.ts +14 -2
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +435 -230
  102. package/dist/managed-assets.d.ts +6 -0
  103. package/dist/managed-assets.d.ts.map +1 -1
  104. package/dist/managed-files/ci-workflow.d.ts +13 -0
  105. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  106. package/dist/managed-files/ci-workflow.js +44 -13
  107. package/dist/managed-files/files.d.ts +7 -1
  108. package/dist/managed-files/files.d.ts.map +1 -1
  109. package/dist/managed-files/files.js +62 -8
  110. package/dist/managed-files/json-edit.d.ts +21 -0
  111. package/dist/managed-files/json-edit.d.ts.map +1 -0
  112. package/dist/managed-files/json-edit.js +295 -0
  113. package/dist/managed-files/managed-format.d.ts +33 -1
  114. package/dist/managed-files/managed-format.d.ts.map +1 -1
  115. package/dist/managed-files/managed-format.js +82 -2
  116. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts +7 -0
  117. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts.map +1 -1
  118. package/dist/managed-files/pr-preview-cleanup-workflow.js +68 -4
  119. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  120. package/dist/managed-files/publish-workflow.js +231 -48
  121. package/dist/managed-files/tree.d.ts +5 -0
  122. package/dist/managed-files/tree.d.ts.map +1 -1
  123. package/dist/managed-files/tree.js +5 -3
  124. package/dist/manifest-hash.js +3 -2
  125. package/dist/nextest-code-bound.d.ts +62 -0
  126. package/dist/nextest-code-bound.d.ts.map +1 -0
  127. package/dist/nextest-code-bound.js +154 -0
  128. package/dist/nextest-extraction.d.ts +24 -8
  129. package/dist/nextest-extraction.d.ts.map +1 -1
  130. package/dist/nextest-extraction.js +42 -7
  131. package/dist/package-target-policy.d.ts.map +1 -1
  132. package/dist/package-target-policy.js +3 -5
  133. package/dist/release-config-policy.d.ts.map +1 -1
  134. package/dist/release-config-policy.js +3 -5
  135. package/dist/runtime-input.d.ts +14 -0
  136. package/dist/runtime-input.d.ts.map +1 -0
  137. package/dist/runtime-input.js +15 -0
  138. package/dist/rust-tokens.d.ts +11 -0
  139. package/dist/rust-tokens.d.ts.map +1 -0
  140. package/dist/rust-tokens.js +81 -0
  141. package/dist/task-results.d.ts +6 -0
  142. package/dist/task-results.d.ts.map +1 -0
  143. package/dist/task-results.js +61 -0
  144. package/dist/test-program.d.ts +54 -0
  145. package/dist/test-program.d.ts.map +1 -0
  146. package/dist/test-program.js +292 -0
  147. package/dist/test-timings.d.ts +71 -0
  148. package/dist/test-timings.d.ts.map +1 -0
  149. package/dist/test-timings.js +393 -0
  150. package/dist/test-walk-policy.d.ts +103 -0
  151. package/dist/test-walk-policy.d.ts.map +1 -0
  152. package/dist/test-walk-policy.js +657 -0
  153. package/dist/testing.d.ts +177 -0
  154. package/dist/testing.d.ts.map +1 -0
  155. package/dist/testing.js +824 -0
  156. package/dist/type-guards.d.ts +3 -0
  157. package/dist/type-guards.d.ts.map +1 -0
  158. package/dist/type-guards.js +4 -0
  159. package/dist/typecheck-test-policy.d.ts +8 -5
  160. package/dist/typecheck-test-policy.d.ts.map +1 -1
  161. package/dist/typecheck-test-policy.js +113 -100
  162. package/dist/workspace-config-policy.d.ts +8 -0
  163. package/dist/workspace-config-policy.d.ts.map +1 -1
  164. package/dist/workspace-config-policy.js +175 -63
  165. package/dist/workspace-index.d.ts +12 -0
  166. package/dist/workspace-index.d.ts.map +1 -0
  167. package/dist/workspace-index.js +17 -0
  168. package/dist/workspace-manifest.d.ts +37 -1
  169. package/dist/workspace-manifest.d.ts.map +1 -1
  170. package/executors.json +5 -0
  171. package/loader.js +13 -11
  172. package/managed/raw/envrc +33 -62
  173. package/managed/raw/git-format-staged.yml +30 -35
  174. package/managed/raw/patches/nx@23.2.1.patch +3484 -0
  175. package/managed/raw/tooling/direnv/apple-developer.sh +83 -0
  176. package/managed/raw/tooling/direnv/developer-links.ts +607 -17
  177. package/managed/raw/tooling/direnv/devenv.smoo.nix +314 -92
  178. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +20 -11
  179. package/managed/raw/tooling/direnv/linked-snapshots.ts +845 -0
  180. package/managed/raw/tooling/direnv/nx-socket-dir.sh +82 -0
  181. package/managed/raw/tooling/direnv/repo-path +14 -2
  182. package/managed/raw/tooling/direnv/setup-environment.ts +1009 -118
  183. package/managed/raw/tooling/direnv/toolchain-stamp.ts +45 -3
  184. package/managed/raw/tooling/direnv/ttsc-env.sh +39 -0
  185. package/managed/raw/tooling/git-hooks/commit-msg.sh +5 -6
  186. package/managed/raw/tooling/git-hooks/pre-commit.sh +7 -6
  187. package/managed/raw/tooling/git-hooks/pre-push.sh +20 -15
  188. package/managed/templates/github/actions/cache-nix-devenv/action.yml +6 -6
  189. package/managed/templates/github/actions/cache-node-modules/action.yml +6 -4
  190. package/managed/templates/github/actions/cache-nx/action.yml +1 -1
  191. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +1 -1
  192. package/managed/templates/github/actions/forgejo-artifact.cjs +99 -0
  193. package/managed/templates/github/actions/forgejo-download-artifact/action.yml +49 -0
  194. package/managed/templates/github/actions/forgejo-download-artifact/index.cjs +7 -0
  195. package/managed/templates/github/actions/forgejo-upload-artifact/action.yml +65 -0
  196. package/managed/templates/github/actions/forgejo-upload-artifact/index.cjs +7 -0
  197. package/managed/templates/github/actions/setup-devenv/action.yml +21 -3
  198. package/managed/templates/github/workflows/managed-files.yml +1 -2
  199. package/nextest.toml +8 -75
  200. package/package.json +75 -13
  201. package/runtime-input.sh +81 -0
  202. package/src/__tests__/counted-cargo-process.ts +286 -0
  203. package/src/__tests__/counted-cargo.ts +730 -0
  204. package/src/__tests__/fixture-cargo-home.ts +36 -0
  205. package/src/__tests__/fixture-nx-env.ts +157 -2
  206. package/src/__tests__/progress-clock.ts +43 -0
  207. package/src/__tests__/runtime-input.ts +23 -0
  208. package/src/bin/smoo-nx-bound-failures.test.ts +127 -0
  209. package/src/bin/smoo-nx-bound-failures.ts +33 -0
  210. package/src/bin/smoo-nx-cargo-hash.ts +28 -3
  211. package/src/bin/smoo-nx-exec.ts +17 -86
  212. package/src/bin/smoo-nx-failures.ts +4 -0
  213. package/src/bin/smoo-nx-nextest-extract.ts +3 -2
  214. package/src/bin/smoo-nx-test-walks.ts +42 -0
  215. package/src/bounded-test-policy.test.ts +268 -22
  216. package/src/bounded-test-policy.ts +114 -42
  217. package/src/build-state-output-policy.test.ts +115 -0
  218. package/src/build-state-output-policy.ts +90 -0
  219. package/src/bun-bootstrap.test.ts +57 -3
  220. package/src/bun-file-packages.test.ts +47 -0
  221. package/src/cargo-closure-input.test.ts +432 -62
  222. package/src/cargo-closure-input.ts +51 -57
  223. package/src/cargo-dev-profile.ts +137 -0
  224. package/src/cargo-resolve-cache.test.ts +1044 -0
  225. package/src/cargo-source-hash.test.ts +203 -93
  226. package/src/cargo-source-hash.ts +762 -75
  227. package/src/cargo-toolchain-policy.ts +6 -0
  228. package/src/cargo-workspace.test.ts +320 -0
  229. package/src/cargo-workspace.ts +344 -18
  230. package/src/cross-check-policy.test.ts +59 -1
  231. package/src/cross-check-policy.ts +25 -6
  232. package/src/disk-command-policy.test.ts +61 -0
  233. package/src/disk-command-policy.ts +107 -0
  234. package/src/ensure-built-receipt.test.ts +184 -0
  235. package/src/ensure-built-receipt.ts +263 -0
  236. package/src/ensure-built-witness.test.ts +344 -0
  237. package/src/ensure-built-witness.ts +252 -0
  238. package/src/ensure-built.test.ts +1043 -483
  239. package/src/ensure-built.ts +870 -197
  240. package/src/eslint-file-set.ts +9 -0
  241. package/src/executors/bounded-exec/cpu-pool.test.ts +454 -0
  242. package/src/executors/bounded-exec/cpu-pool.ts +417 -0
  243. package/src/executors/bounded-exec/cpu-tokens.test.ts +269 -0
  244. package/src/executors/bounded-exec/cpu-tokens.ts +177 -0
  245. package/src/executors/bounded-exec/disk-lease.test.ts +185 -0
  246. package/src/executors/bounded-exec/disk-lease.ts +139 -0
  247. package/src/executors/bounded-exec/executor-host.test.ts +778 -0
  248. package/src/executors/bounded-exec/executor.test.ts +1116 -63
  249. package/src/executors/bounded-exec/executor.ts +565 -67
  250. package/src/executors/bounded-exec/gateway-lease.ts +176 -0
  251. package/src/executors/bounded-exec/hang-diagnostics.test.ts +285 -0
  252. package/src/executors/bounded-exec/hang-diagnostics.ts +283 -0
  253. package/src/executors/bounded-exec/progress.test.ts +79 -0
  254. package/src/executors/bounded-exec/progress.ts +118 -0
  255. package/src/executors/bounded-exec/ram-temp-fixtures.ts +12 -0
  256. package/src/executors/bounded-exec/ram-temp-held.test.ts +264 -0
  257. package/src/executors/bounded-exec/ram-temp-held.ts +242 -0
  258. package/src/executors/bounded-exec/ram-temp-host.test.ts +605 -0
  259. package/src/executors/bounded-exec/ram-temp.test.ts +674 -0
  260. package/src/executors/bounded-exec/ram-temp.ts +1918 -0
  261. package/src/executors/bounded-exec/schema.json +11 -5
  262. package/src/executors/bounded-exec/schema.ts +27 -11
  263. package/src/executors/bounded-exec/verdict.test.ts +440 -0
  264. package/src/executors/bounded-exec/verdict.ts +433 -0
  265. package/src/executors/shard-timings/executor.ts +36 -0
  266. package/src/executors/shard-timings/schema.json +21 -0
  267. package/src/executors/shard-timings/schema.ts +4 -0
  268. package/src/failure-summary.ts +119 -0
  269. package/src/generators/bounded-test-targets/generator.test.ts +4 -4
  270. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  271. package/src/generators/create-package/generator.test.ts +6 -0
  272. package/src/generators/create-package/generator.ts +6 -2
  273. package/src/host-controller-wiring.test.ts +31 -0
  274. package/src/index.test.ts +1070 -360
  275. package/src/index.ts +524 -255
  276. package/src/linked-snapshots.nx.test.ts +172 -0
  277. package/src/managed-assets.ts +12 -0
  278. package/src/managed-files/ci-workflow.ts +54 -13
  279. package/src/managed-files/files.ts +65 -9
  280. package/src/managed-files/forgejo-artifact.test.ts +395 -0
  281. package/src/managed-files/generator.test.ts +60 -1
  282. package/src/managed-files/json-edit.test.ts +216 -0
  283. package/src/managed-files/json-edit.ts +290 -0
  284. package/src/managed-files/managed-format-json.test.ts +308 -0
  285. package/src/managed-files/managed-format.ts +90 -2
  286. package/src/managed-files/pr-preview-cleanup-workflow.ts +69 -3
  287. package/src/managed-files/publish-workflow.ts +285 -67
  288. package/src/managed-files/repo-path.test.ts +129 -0
  289. package/src/managed-files/trace-db-artifact.test.ts +7 -0
  290. package/src/managed-files/tree.ts +11 -3
  291. package/src/manifest-hash.ts +3 -2
  292. package/src/nextest-code-bound.test.ts +155 -0
  293. package/src/nextest-code-bound.ts +195 -0
  294. package/src/nextest-extraction.test.ts +37 -5
  295. package/src/nextest-extraction.ts +51 -9
  296. package/src/nextest-partitions.test.ts +495 -0
  297. package/src/nx-cache-bound.test.ts +109 -0
  298. package/src/nx-cache-restore-mtime.test.ts +170 -0
  299. package/src/nx-daemon-claim.test.ts +277 -0
  300. package/src/nx-daemon-idle-cpu.test.ts +81 -0
  301. package/src/nx-daemon-idle-policy.test.ts +51 -0
  302. package/src/nx-daemon-ignore-files.test.ts +210 -0
  303. package/src/nx-daemon-root-normalization.test.ts +105 -0
  304. package/src/nx-daemon-validity.test.ts +925 -0
  305. package/src/nx-dot-input-policy.test.ts +353 -0
  306. package/src/nx-failure-life-cycles.test.ts +207 -0
  307. package/src/nx-files-archive-racy.test.ts +97 -0
  308. package/src/nx-foreign-workspace-env.test.ts +329 -0
  309. package/src/nx-incomplete-run-summary.test.ts +70 -0
  310. package/src/nx-plugin-load-errors.test.ts +120 -0
  311. package/src/nx-project-resolution-cache.test.ts +176 -0
  312. package/src/nx-raw-inputs.test.ts +166 -0
  313. package/src/nx-resident-graph-workers.test.ts +112 -0
  314. package/src/nx-run-information.test.ts +118 -0
  315. package/src/nx-skipped-task-exit.test.ts +180 -0
  316. package/src/nx-state-location.test.ts +63 -0
  317. package/src/nx-store-resolution.test.ts +99 -0
  318. package/src/nx-task-graph-cycles.test.ts +148 -0
  319. package/src/nx-task-output-lease.test.ts +414 -0
  320. package/src/nx-use-local.test.ts +103 -0
  321. package/src/package-target-policy.ts +3 -6
  322. package/src/release-config-policy.ts +3 -6
  323. package/src/runtime-input.test.ts +215 -0
  324. package/src/runtime-input.ts +17 -0
  325. package/src/rust-tokens.ts +78 -0
  326. package/src/serial-group-wiring.test.ts +326 -0
  327. package/src/task-history-namespace.test.ts +181 -0
  328. package/src/task-results.test.ts +226 -0
  329. package/src/task-results.ts +75 -0
  330. package/src/test-program.test.ts +303 -0
  331. package/src/test-program.ts +341 -0
  332. package/src/test-timings.test.ts +240 -0
  333. package/src/test-timings.ts +311 -0
  334. package/src/test-walk-policy.test.ts +585 -0
  335. package/src/test-walk-policy.ts +731 -0
  336. package/src/testing.test.ts +509 -0
  337. package/src/testing.ts +922 -0
  338. package/src/type-guards.ts +4 -0
  339. package/src/typecheck-test-policy.test.ts +496 -11
  340. package/src/typecheck-test-policy.ts +137 -103
  341. package/src/workspace-config-policy.test.ts +212 -13
  342. package/src/workspace-config-policy.ts +101 -73
  343. package/src/workspace-index.ts +18 -0
  344. package/src/workspace-manifest.ts +41 -1
  345. package/test-timings.json +85 -28
  346. package/managed/raw/tooling/direnv/inherited-devenv.ts +0 -615
  347. package/managed/raw/tooling/direnv/shared-caches.sh +0 -53
  348. package/src/__tests__/in-process-nx-index.ts +0 -9
@@ -1,25 +1,38 @@
1
1
  #!/usr/bin/env bun
2
- import { dlopen, FFIType } from 'bun:ffi';
2
+ import { dlopen, FFIType, read as ffiRead } from 'bun:ffi';
3
3
  import {
4
4
  chmodSync,
5
5
  closeSync,
6
+ cpSync,
7
+ type Dirent,
6
8
  existsSync,
9
+ lstatSync,
7
10
  mkdirSync,
11
+ mkdtempSync,
8
12
  openSync,
9
13
  readdirSync,
10
14
  readFileSync,
11
15
  readlinkSync,
12
16
  realpathSync,
17
+ renameSync,
13
18
  rmSync,
14
19
  statSync,
15
20
  symlinkSync,
16
21
  writeFileSync,
17
22
  } from 'node:fs';
18
23
  import { createRequire } from 'node:module';
24
+ import { homedir } from 'node:os';
19
25
  import path from 'node:path';
20
- import { parseArgs } from 'node:util';
26
+ import { getSystemErrorName, parseArgs } from 'node:util';
21
27
  import { $ } from 'bun';
22
- import { keepDeveloperLinks, reportDeveloperLinks } from './developer-links.ts';
28
+ import {
29
+ applyDeclaredLinks,
30
+ hasStaleDeveloperLinks,
31
+ keepDeveloperLinks,
32
+ planDeclaredLinks,
33
+ reportDeveloperLinks,
34
+ reportUnavailableDeclaredLinks,
35
+ } from './developer-links.ts';
23
36
  import {
24
37
  type DeferredSecret,
25
38
  dependentGroups,
@@ -28,11 +41,8 @@ import {
28
41
  SHELL_GROUP,
29
42
  } from './secret-references.ts';
30
43
 
31
- // DEVENV_ROOT is set by the devenv shell, which is how this script normally
32
- // runs. CI jobs that install dependencies without building that shell (the
33
- // publishing job installs Bun and Node directly) have no such variable, so fall
34
- // back to the git top level rather than resolving "undefined/../.." two levels
35
- // above the repository and failing with "could not find a package.json".
44
+ // DEVENV_ROOT is set by the devenv shell. It is only checked against the checkout this script runs
45
+ // in, never trusted to select the root: see resolveProjectRoot.
36
46
  const devenvRoot = process.env.DEVENV_ROOT;
37
47
 
38
48
  /** What a setup command printed, as captured. */
@@ -52,6 +62,28 @@ class CapturedCommandError extends Error {
52
62
  }
53
63
  }
54
64
 
65
+ type BunInstallIntegrityOperation =
66
+ | 'inspect isolated store'
67
+ | 'resolve installed path'
68
+ | 'list installed package aliases'
69
+ | 'read installed package manifest';
70
+
71
+ class BunInstallIntegrityError extends Error {
72
+ readonly code = 'BUN_INSTALL_INTEGRITY';
73
+
74
+ constructor(
75
+ public readonly operation: BunInstallIntegrityOperation,
76
+ public readonly actualPath: string,
77
+ public readonly expectedTarget: string,
78
+ cause: unknown,
79
+ ) {
80
+ super(
81
+ `Bun install integrity: ${operation} failed for ${actualPath}; expected target ${expectedTarget}: ${cause instanceof Error ? cause.message : String(cause)}`,
82
+ { cause },
83
+ );
84
+ }
85
+ }
86
+
55
87
  // Every value resolved out of smoo.secrets below. The install inherits them,
56
88
  // so whatever a failing child echoed is redacted before its captured output
57
89
  // is replayed. Declared above the first replay site (resolveProjectRoot's own
@@ -69,26 +101,68 @@ const resolvedSecretValues: string[] = [];
69
101
  // and a 401 is one of the things it might have been.
70
102
  const deferredSecrets: DeferredSecret[] = [];
71
103
 
72
- async function resolveProjectRoot(): Promise<string> {
73
- if (devenvRoot) {
74
- return path.resolve(`${devenvRoot}/../..`);
75
- }
104
+ type ProjectRootResult =
105
+ | { readonly kind: 'ready'; readonly root: string }
106
+ | { readonly kind: 'unavailable'; readonly reason: string; readonly hint: string }
107
+ | { readonly kind: 'rootMismatch'; readonly owned: string; readonly declared: string; readonly hint: string };
76
108
 
77
- const result = await $`git rev-parse --show-toplevel`.quiet().nothrow();
78
- if (result.exitCode !== 0) {
79
- const error = new CapturedCommandError(
80
- 'git rev-parse --show-toplevel',
81
- result.exitCode,
82
- result.stdout,
83
- result.stderr,
84
- );
85
- replayCapturedOutput(error);
86
- throw error;
109
+ // The root is the checkout's own git top level, derived from the working directory, or from this
110
+ // script's directory when the working directory is not a repository. DEVENV_ROOT never selects
111
+ // the root: a value naming another root is refused with a finding, not followed silently.
112
+ async function resolveProjectRoot(): Promise<ProjectRootResult> {
113
+ const fromCwd = await $`git rev-parse --show-toplevel`.quiet().nothrow();
114
+ let owned: string | null = null;
115
+ if (fromCwd.exitCode === 0) {
116
+ owned = new TextDecoder().decode(fromCwd.stdout).trim();
117
+ } else {
118
+ const fromScript = await $`git -C ${path.dirname(new URL(import.meta.url).pathname)} rev-parse --show-toplevel`
119
+ .quiet()
120
+ .nothrow();
121
+ if (fromScript.exitCode === 0) {
122
+ owned = new TextDecoder().decode(fromScript.stdout).trim();
123
+ }
87
124
  }
88
- return new TextDecoder().decode(result.stdout).trim();
125
+ if (owned === null) {
126
+ return {
127
+ kind: 'unavailable',
128
+ reason: 'this directory is not inside a git repository',
129
+ hint: 'run the shell entry from inside the repository checkout',
130
+ };
131
+ }
132
+ if (devenvRoot !== undefined && devenvRoot !== '') {
133
+ const declared = path.resolve(`${devenvRoot}/../..`);
134
+ // Compare canonical paths only when both exist: a missing foreign path is still a mismatch,
135
+ // reported by its lexical name, never an ENOENT.
136
+ const same = existsSync(declared) && realpathSync(declared) === realpathSync(owned);
137
+ if (!same) {
138
+ return {
139
+ kind: 'rootMismatch',
140
+ owned,
141
+ declared,
142
+ hint: 'unset DEVENV_ROOT or re-enter the shell from this checkout',
143
+ };
144
+ }
145
+ }
146
+ if (!existsSync(path.join(owned, 'package.json'))) {
147
+ return {
148
+ kind: 'unavailable',
149
+ reason: `${owned} has no package.json`,
150
+ hint: 'run the shell entry from a checkout that contains the repository manifest',
151
+ };
152
+ }
153
+ return { kind: 'ready', root: owned };
89
154
  }
90
155
 
91
- const projectRoot = await resolveProjectRoot();
156
+ const rootResult = await resolveProjectRoot();
157
+ if (rootResult.kind !== 'ready') {
158
+ const message =
159
+ rootResult.kind === 'unavailable'
160
+ ? `setup-environment: cannot locate the project root: ${rootResult.reason}`
161
+ : `setup-environment: DEVENV_ROOT names ${rootResult.declared} but this checkout's root is ${rootResult.owned}`;
162
+ console.error(`${message}\n hint: ${rootResult.hint}`);
163
+ process.exit(1);
164
+ }
165
+ const projectRoot = rootResult.root;
92
166
 
93
167
  // Unscoped require("typescript") must expose the TS6 compiler API for Nx.
94
168
  // @typescript/native installs another package also named "typescript" (TS7). Bun's
@@ -124,23 +198,89 @@ const POST_COMMIT_BLOCK = [
124
198
  // The managed devenv module passes `--python <interpreter>` for a uv project:
125
199
  // the interpreter devenv's languages.python would use, as a store path, so the
126
200
  // environment uv builds does not name this checkout's profile as its home.
201
+ // `--cargo` runs the Cargo fetches instead of the installs: they are devenv's
202
+ // smoo:cargo-fetch task, whose `status` is `--cargo --check` (exit 0 when
203
+ // CARGO_HOME already holds every workspace's locked packages). Their stamps
204
+ // (cargoFetcher) live in smoo's user cache and count only while CARGO_HOME
205
+ // names the directory they were fetched into, which no checkout-relative
206
+ // change detection can see.
207
+ // `--links` repairs stale install links (including external Nx aliases), then
208
+ // points the packages `smoo.developerLinks` declares at their local checkouts.
209
+ // devenv's smoo:developer-links task uses `--links --check` as its status:
210
+ // links can change without any smoo:install input changing.
127
211
  // Declared above the bootstrap block for the same hoisting reason as above.
128
- const { values: flags } = parseArgs({ options: { python: { type: 'string' } } });
212
+ const { values: flags } = parseArgs({
213
+ options: {
214
+ python: { type: 'string' },
215
+ cargo: { type: 'boolean' },
216
+ links: { type: 'boolean' },
217
+ check: { type: 'boolean' },
218
+ 'repair-missing-payload': { type: 'string' },
219
+ },
220
+ });
221
+ const cargoMode = flags.cargo === true;
222
+
223
+ // The Nx plugin's test for a Cargo workspace root manifest (CARGO_WORKSPACE_PATTERN), which
224
+ // cargoWorkspaces applies during the bootstrap block; declared above it for the same reason.
225
+ const CARGO_WORKSPACE = /^\s*\[workspace\]/m;
129
226
 
130
227
  // Go to project root
131
228
  process.chdir(projectRoot);
132
229
 
133
230
  try {
231
+ const requestedPayload = flags['repair-missing-payload'];
232
+ if (requestedPayload !== undefined) {
233
+ if (flags.links === true || flags.check === true || cargoMode || flags.python !== undefined) {
234
+ reportSetupFailure(new Error('--repair-missing-payload is an explicit standalone installer transaction'));
235
+ }
236
+ const error = await withInstallLock(() => repairMissingPayload(requestedPayload));
237
+ if (error !== undefined) reportSetupFailure(error);
238
+ process.exit(0);
239
+ }
240
+ if (flags.links === true) {
241
+ // CI builds against the published packages its lockfile names; it never links them.
242
+ if (process.env.GITHUB_ACTIONS === 'true') {
243
+ process.exit(0);
244
+ }
245
+ if (flags.check === true) {
246
+ const plan = await planDeclaredLinks(projectRoot);
247
+ // A refused or unclaimed snapshot is current only when said: the exec that follows names its cause.
248
+ const current =
249
+ plan.changes.length === 0 && plan.unavailable.every((unavailable) => unavailable.kind === 'absent');
250
+ process.exit(current && !hasStaleDeveloperLinks(projectRoot, ['nx']) ? 0 : 1);
251
+ }
252
+ await withInstallLock(async () => {
253
+ // Recheck under the install lock: another shell may already have repaired
254
+ // the aliases. Use the same installer as smoo:install, never a second linker.
255
+ if (hasStaleDeveloperLinks(projectRoot, ['nx'])) {
256
+ const error = await installLocalDependencies([bunInstaller(bunInstallInputs())]);
257
+ if (error !== undefined) reportSetupFailure(error);
258
+ ensureTypeScriptApiPackage(projectRoot);
259
+ }
260
+ applyDeclaredLinks(projectRoot, await planDeclaredLinks(projectRoot));
261
+ });
262
+ process.exit(0);
263
+ }
134
264
  // Bootstrap only: install deps + wire local git hooks/config.
135
265
  // Do not import workspace packages here — this script is what installs them,
136
266
  // and package resolution/Typia transforms are not available yet.
137
267
  const bunInputs = bunInstallInputs();
138
- const uvInputs = uvSyncInputs();
139
- recordInstallInputs([...bunInputs, ...uvInputs]);
268
+ const cargoFetches = cargoMode ? cargoWorkspaces(bunInputs).map(cargoFetcher) : [];
269
+ if (flags.check === true) {
270
+ process.exit(cargoFetches.every((fetch) => fetch.isCurrent()) ? 0 : 1);
271
+ }
272
+ const uvInputs = cargoMode ? [] : uvSyncInputs();
140
273
  // A CI runner is GitHub Actions or Forgejo Actions, which mirrors every FORGEJO_*
141
274
  // variable as GITHUB_*. Not `CI`: agent harnesses set CI=true on every command
142
275
  // they run, and this branch installs unconditionally.
143
- if (process.env.GITHUB_ACTIONS === 'true') {
276
+ if (process.env.GITHUB_ACTIONS === 'true' && cargoMode) {
277
+ await withInstallLock(async () => {
278
+ for (const fetch of cargoFetches) {
279
+ const error = await fetch.install({ quiet: false });
280
+ if (error !== undefined) reportSetupFailure(error);
281
+ }
282
+ });
283
+ } else if (process.env.GITHUB_ACTIONS === 'true') {
144
284
  const uv = uvInstaller(uvInputs, { locked: true });
145
285
  await resolveSecrets();
146
286
  // Failures are captured and reported below. Exiting in the catch would
@@ -149,20 +289,26 @@ try {
149
289
  await withInstallLock(async () => {
150
290
  let frozenError: unknown;
151
291
  let fallbackError: unknown;
152
- await keepDeveloperLinks(projectRoot, async () => {
292
+ try {
293
+ await keepDeveloperLinks(
294
+ projectRoot,
295
+ () => runSetupCommand('bun install --frozen-lockfile', $`bun install --frozen-lockfile`, { quiet: false }),
296
+ { relink: ['nx'] },
297
+ );
298
+ } catch (error) {
299
+ frozenError = error;
300
+ console.error('! Failed to install dependencies with frozen lockfile');
301
+ replayCapturedOutput(error);
153
302
  try {
154
- await runSetupCommand('bun install --frozen-lockfile', $`bun install --frozen-lockfile`, { quiet: false });
155
- } catch (error) {
156
- frozenError = error;
157
- console.error('! Failed to install dependencies with frozen lockfile');
158
- replayCapturedOutput(error);
159
- try {
160
- await runSetupCommand('bun install', $`bun install`, { quiet: false });
161
- } catch (fallback) {
162
- fallbackError = fallback;
163
- }
303
+ await keepDeveloperLinks(
304
+ projectRoot,
305
+ () => runSetupCommand('bun install', $`bun install`, { quiet: false }),
306
+ { relink: ['nx'] },
307
+ );
308
+ } catch (fallback) {
309
+ fallbackError = fallback;
164
310
  }
165
- });
311
+ }
166
312
  if (fallbackError !== undefined) {
167
313
  reportSetupFailure(fallbackError);
168
314
  }
@@ -181,10 +327,26 @@ try {
181
327
  }
182
328
  process.exit(1);
183
329
  }
330
+ // devenv's smoo:install task skips this script while the digests of its inputs match the ones it
331
+ // recorded, and a runner's .devenv outlives its checkout (a host runner keeps it on a shared bind, an
332
+ // ephemeral one restores it from the Actions cache). node_modules/.smoo-install is the one input that
333
+ // goes with node_modules: without it a fresh checkout of the same lockfile found the task current,
334
+ // installed nothing, and the shell's `ttsc` was not there.
335
+ const integrityError = bunInstallStamp(bunInputs).record();
336
+ if (integrityError !== undefined) reportSetupFailure(integrityError);
184
337
  if (uv !== null) {
185
- await uv.install({ quiet: false });
338
+ const error = await uv.install({ quiet: false });
339
+ if (error !== undefined) reportSetupFailure(error);
186
340
  }
187
341
  });
342
+ } else if (cargoMode) {
343
+ // A failed fetch loads the shell like a failed install; the graph then names Cargo's refusal.
344
+ const fetchError = await withInstallLock(() =>
345
+ installLocalDependencies(cargoFetches.filter((fetch) => !fetch.isCurrent())),
346
+ );
347
+ if (fetchError !== undefined) {
348
+ reportDegradedSetup(fetchError);
349
+ }
188
350
  } else {
189
351
  // A local secret-resolution or install failure (a provider that is not
190
352
  // signed in, an unpublished private package, a missing registry
@@ -196,7 +358,7 @@ try {
196
358
  const uv = uvInstaller(uvInputs, { locked: false });
197
359
  const bun = bunInstaller(bunInputs);
198
360
  const installError = await withInstallLock(async () => {
199
- const pending = (uv === null ? [bun] : [bun, uv]).filter((installer) => !installer.isCurrent());
361
+ const pending = [bun, ...(uv === null ? [] : [uv])].filter((installer) => !installer.isCurrent());
200
362
  const error = await installLocalDependencies(pending);
201
363
  if (!pending.includes(bun)) {
202
364
  reportDeveloperLinks(projectRoot);
@@ -265,7 +427,8 @@ async function installLocalDependencies(pending: readonly Installer[]): Promise<
265
427
  }
266
428
  for (const installer of pending) {
267
429
  try {
268
- await installer.install({ quiet: true });
430
+ const error = await installer.install({ quiet: true });
431
+ if (error !== undefined) return error;
269
432
  } catch (error) {
270
433
  return error;
271
434
  }
@@ -287,6 +450,10 @@ async function installLocalDependencies(pending: readonly Installer[]): Promise<
287
450
  * shell entry cannot leave a lock behind for the next one to wait out. Bun
288
451
  * has no flock binding, so it comes from libc; LOCK_EX and LOCK_NB have the
289
452
  * same values on Darwin and Linux. The waiting entry says why it is waiting.
453
+ *
454
+ * flock needs no write access, so an existing lock file is opened read-only:
455
+ * an entry whose installs are current then writes nothing in the checkout,
456
+ * and enters a read-only view of it (a read-only sandboxed job) as well.
290
457
  */
291
458
  async function withInstallLock<T>(run: () => Promise<T>): Promise<T> {
292
459
  const LOCK_EX = 2;
@@ -295,8 +462,7 @@ async function withInstallLock<T>(run: () => Promise<T>): Promise<T> {
295
462
  flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
296
463
  });
297
464
  const lockPath = path.join(projectRoot, 'node_modules', '.smoo-install.lock');
298
- mkdirSync(path.dirname(lockPath), { recursive: true });
299
- const fd = openSync(lockPath, 'a');
465
+ const fd = openInstallLock(lockPath);
300
466
  try {
301
467
  if (libc.symbols.flock(fd, LOCK_EX | LOCK_NB) !== 0) {
302
468
  console.error(`setup-environment: waiting for another shell entry's install in ${projectRoot}`);
@@ -311,6 +477,366 @@ async function withInstallLock<T>(run: () => Promise<T>): Promise<T> {
311
477
  }
312
478
  }
313
479
 
480
+ function openInstallLock(lockPath: string): number {
481
+ try {
482
+ return openSync(lockPath, 'r');
483
+ } catch (error) {
484
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error;
485
+ }
486
+ mkdirSync(path.dirname(lockPath), { recursive: true });
487
+ return openSync(lockPath, 'a');
488
+ }
489
+
490
+ /** Explicit, locked missing-payload restoration; normal shell entry never scans payload. */
491
+ async function repairMissingPayload(requested: string): Promise<Error | undefined> {
492
+ let staging: string | undefined;
493
+ let installed: string | undefined;
494
+ let replacement: string | undefined;
495
+ let exchanged = false;
496
+ let committed = false;
497
+ const perform = async (): Promise<Error | undefined> => {
498
+ const request = path.resolve(projectRoot, requested);
499
+ const relativeRequest = path.relative(projectRoot, request);
500
+ if (relativeRequest === '..' || relativeRequest.startsWith(`..${path.sep}`) || path.isAbsolute(relativeRequest)) {
501
+ return new Error(`Missing-payload request is outside this checkout: ${request}`);
502
+ }
503
+ let alias = request;
504
+ while (alias !== projectRoot && !existsSync(path.join(alias, 'package.json'))) alias = path.dirname(alias);
505
+ if (alias === projectRoot || !path.relative(projectRoot, alias).split(path.sep).includes('node_modules')) {
506
+ return new Error(`Missing-payload request must name this checkout's installed package alias: ${request}`);
507
+ }
508
+ installed = realpathSync(alias);
509
+ const owned = path.relative(realpathSync(projectRoot), installed);
510
+ if (owned === '' || owned === '..' || owned.startsWith(`..${path.sep}`) || path.isAbsolute(owned)) {
511
+ return new Error(`Installed package is not owned by this checkout: ${alias} -> ${installed}`);
512
+ }
513
+ const manifest: unknown = JSON.parse(readFileSync(path.join(installed, 'package.json'), 'utf8'));
514
+ if (!payloadObject(manifest) || typeof manifest.name !== 'string' || typeof manifest.version !== 'string') {
515
+ return new Error(`Installed package has no name/version: ${alias}`);
516
+ }
517
+ const identity = `${manifest.name}@${manifest.version}`;
518
+ const locked = new Map<string, Buffer>();
519
+ for (const name of ['bun.lock', 'bun.lockb']) {
520
+ const bytes = readFileIfPresent(path.join(projectRoot, name));
521
+ if (bytes !== null) locked.set(name, bytes);
522
+ }
523
+ const witnessPath = path.join(projectRoot, 'node_modules', '.smoo-install');
524
+ const witnessBytes = readFileIfPresent(witnessPath);
525
+ const witness = readInstallStamp(witnessPath);
526
+ if (
527
+ witnessBytes === null ||
528
+ witness === null ||
529
+ witness.lockfiles === undefined ||
530
+ !/^[0-9a-f]{64}$/.test(witness.inputs)
531
+ ) {
532
+ return new Error(
533
+ 'Missing-payload repair requires a valid prior successful installation witness; use the canonical installer',
534
+ );
535
+ }
536
+ const witnessedLocks = witness.lockfiles;
537
+ if (Object.keys(witnessedLocks).length !== locked.size) {
538
+ return new Error('Prior successful installation witness does not bind the present lockfiles');
539
+ }
540
+ for (const [name, bytes] of locked) {
541
+ if (witnessedLocks[name] !== new Bun.CryptoHasher('sha256').update(bytes).digest('hex')) {
542
+ return new Error(`Prior successful installation witness does not match ${name}`);
543
+ }
544
+ }
545
+ const lock: unknown = Bun.JSONC.parse(readFileSync(path.join(projectRoot, 'bun.lock'), 'utf8'));
546
+ if (!payloadObject(lock) || !payloadObject(lock.packages)) return new Error('bun.lock has no package records');
547
+ const integrities = new Set<string>();
548
+ for (const entry of Object.values(lock.packages)) {
549
+ if (Array.isArray(entry) && entry[0] === identity && typeof entry[3] === 'string') integrities.add(entry[3]);
550
+ }
551
+ if (integrities.size !== 1) return new Error(`bun.lock does not uniquely bind registry integrity for ${identity}`);
552
+ const integrity = integrities.values().next().value;
553
+ if (integrity === undefined) return new Error(`bun.lock omitted registry integrity for ${identity}`);
554
+ const unchangedLocks = (): Error | undefined => {
555
+ const currentWitness = readFileIfPresent(witnessPath);
556
+ if (currentWitness === null || !currentWitness.equals(witnessBytes)) {
557
+ return new Error('Prior successful installation witness changed during missing-payload repair');
558
+ }
559
+ for (const [name, bytes] of locked) {
560
+ const current = readFileIfPresent(path.join(projectRoot, name));
561
+ if (current === null || !current.equals(bytes))
562
+ return new Error(`Missing-payload repair refused changed ${name}`);
563
+ }
564
+ for (const name of ['bun.lock', 'bun.lockb']) {
565
+ if (!locked.has(name) && existsSync(path.join(projectRoot, name))) {
566
+ return new Error(`Missing-payload repair refused newly created ${name}`);
567
+ }
568
+ }
569
+ return undefined;
570
+ };
571
+ const admissionError = verifyInstalledBunLinks(projectRoot);
572
+ if (admissionError !== undefined) return admissionError;
573
+ // Let Bun resolve the registry using the checkout's existing npm/bun configuration.
574
+ const metadata = await runSetupCommand(`bun info ${identity} dist --json`, $`bun info ${identity} dist --json`, {
575
+ quiet: true,
576
+ });
577
+ const dist: unknown = JSON.parse(metadata.stdout);
578
+ if (
579
+ !payloadObject(dist) ||
580
+ typeof dist.tarball !== 'string' ||
581
+ typeof dist.integrity !== 'string' ||
582
+ !dist.integrity.split(/\s+/).includes(integrity)
583
+ ) {
584
+ return new Error(`Registry dist metadata does not match locked integrity for ${identity}`);
585
+ }
586
+ const response = await fetch(dist.tarball);
587
+ if (!response.ok)
588
+ return new Error(`Cannot read locked tarball for ${identity}: HTTP ${response.status} ${dist.tarball}`);
589
+ const bytes = new Uint8Array(await response.arrayBuffer());
590
+ const integrityError = verifyPayloadIntegrity(bytes, integrity);
591
+ if (integrityError !== undefined) return integrityError;
592
+ const stage = mkdtempSync(path.join(path.dirname(installed), '.smoo-payload-'));
593
+ staging = stage;
594
+ const publication = path.join(stage, 'published');
595
+ await new Bun.Archive(bytes).extract(publication);
596
+ const roots = readdirSync(publication);
597
+ if (roots.length !== 1 || roots[0] !== 'package' || !lstatSync(path.join(publication, 'package')).isDirectory()) {
598
+ return new Error(`Locked registry tarball has no single package directory: ${identity}`);
599
+ }
600
+ const published = path.join(publication, 'package');
601
+ const publishedManifest: unknown = JSON.parse(readFileSync(path.join(published, 'package.json'), 'utf8'));
602
+ if (
603
+ !payloadObject(publishedManifest) ||
604
+ publishedManifest.name !== manifest.name ||
605
+ publishedManifest.version !== manifest.version
606
+ ) {
607
+ return new Error(`Locked tarball package identity differs from installed ${identity}`);
608
+ }
609
+ const publishedRequest = path.join(published, path.relative(alias, request));
610
+ if (lstatSync(publishedRequest, { throwIfNoEntry: false }) === undefined) {
611
+ return new Error(`Requested path is not in the locked published package: ${request}`);
612
+ }
613
+ const comparison = comparePublishedPayload(published, installed);
614
+ if (comparison instanceof Error) return comparison;
615
+ if (comparison.missing.length > 0 && statSync(request, { throwIfNoEntry: false }) !== undefined) {
616
+ return new Error(`Repair request is not physically missing: ${request}`);
617
+ }
618
+ const original = snapshotPayload(installed);
619
+ if (original instanceof Error) return original;
620
+ if (comparison.missing.length > 0) {
621
+ replacement = path.join(stage, 'replacement');
622
+ mkdirSync(replacement, { mode: 0o700 });
623
+ for (const relative of comparison.missing) {
624
+ const destination = path.join(replacement, relative);
625
+ mkdirSync(path.dirname(destination), { recursive: true });
626
+ cpSync(path.join(published, relative), destination, {
627
+ recursive: true,
628
+ preserveTimestamps: true,
629
+ verbatimSymlinks: true,
630
+ dereference: false,
631
+ errorOnExist: true,
632
+ force: false,
633
+ });
634
+ }
635
+ // Copy existing payload once, last: cp -a retains its links and metadata, including parent directory times.
636
+ await runSetupCommand(
637
+ 'preserve installed package in repair staging',
638
+ $`cp -a ${`${installed}/.`} ${`${replacement}/`}`,
639
+ { quiet: true },
640
+ );
641
+ const preserved = verifyPayloadSnapshot(replacement, original) ?? verifyPayloadSnapshot(installed, original);
642
+ if (preserved !== undefined) return preserved;
643
+ const staged = comparePublishedPayload(published, replacement);
644
+ if (staged instanceof Error) return staged;
645
+ if (staged.missing.length !== 0) return new Error(`Repair staging is not published-complete for ${identity}`);
646
+ const lockError = unchangedLocks();
647
+ if (lockError !== undefined) return lockError;
648
+ const swapError = exchangePayloadDirectories(installed, replacement);
649
+ if (swapError !== undefined) return swapError;
650
+ exchanged = true;
651
+ }
652
+ // Keep the original directory until both postconditions and the existing install receipt succeed.
653
+ const complete = comparePublishedPayload(published, installed);
654
+ if (complete instanceof Error) return complete;
655
+ if (complete.missing.length !== 0) return new Error(`Published payload remains incomplete for ${identity}`);
656
+ const preserved = verifyPayloadSnapshot(installed, original);
657
+ if (preserved !== undefined) return preserved;
658
+ const lockError = unchangedLocks();
659
+ if (lockError !== undefined) return lockError;
660
+ // This mode proves one package, never a new whole-install input set. Preserve the prior witness exactly.
661
+ if (comparison.missingFiles > 0) {
662
+ const stagedWitness = path.join(stage, 'install-witness');
663
+ writeFileSync(stagedWitness, witnessBytes, { mode: lstatSync(witnessPath).mode & 0o777 });
664
+ renameSync(stagedWitness, witnessPath);
665
+ }
666
+ committed = true;
667
+ console.log(
668
+ JSON.stringify({
669
+ operation: 'repair-missing-payload',
670
+ package: identity,
671
+ requestedPath: request,
672
+ publishedFiles: complete.files,
673
+ restoredFiles: comparison.missingFiles,
674
+ publishedComplete: true,
675
+ lockedHashesUnchanged: true,
676
+ }),
677
+ );
678
+ return undefined;
679
+ };
680
+ let failure: Error | undefined;
681
+ try {
682
+ failure = await perform();
683
+ } catch (cause) {
684
+ failure = cause instanceof Error ? cause : new Error(String(cause));
685
+ }
686
+ if (exchanged && !committed && installed !== undefined && replacement !== undefined) {
687
+ const rollback = exchangePayloadDirectories(installed, replacement);
688
+ if (rollback !== undefined) {
689
+ return new AggregateError(
690
+ [failure, rollback],
691
+ `Missing-payload repair rollback failed; retained staging path ${staging}`,
692
+ );
693
+ }
694
+ }
695
+ if (staging !== undefined) {
696
+ try {
697
+ rmSync(staging, { recursive: true });
698
+ } catch (cause) {
699
+ const message = committed
700
+ ? `repair committed; retained staging path ${staging}`
701
+ : `Repair refused; retained staging path ${staging}`;
702
+ return new AggregateError(failure === undefined ? [cause] : [failure, cause], message);
703
+ }
704
+ }
705
+ return failure;
706
+ }
707
+
708
+ function payloadObject(value: unknown): value is Record<string, unknown> {
709
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
710
+ }
711
+
712
+ function verifyPayloadIntegrity(bytes: Uint8Array, integrity: string): Error | undefined {
713
+ const [algorithm, digest, extra] = integrity.split('-');
714
+ if (digest === undefined || extra !== undefined) return new Error(`Invalid locked registry integrity: ${integrity}`);
715
+ switch (algorithm) {
716
+ case 'sha1':
717
+ case 'sha256':
718
+ case 'sha384':
719
+ case 'sha512':
720
+ if (new Bun.CryptoHasher(algorithm).update(bytes).digest('base64') === digest) return undefined;
721
+ return new Error(`Locked registry tarball integrity mismatch (${algorithm})`);
722
+ default:
723
+ return new Error(`Unsupported locked registry integrity algorithm: ${algorithm}`);
724
+ }
725
+ }
726
+
727
+ /** Compare only published nodes; installed extra files remain owned metadata, never removal candidates. */
728
+ function comparePublishedPayload(
729
+ published: string,
730
+ installed: string,
731
+ ): { missing: string[]; files: number; missingFiles: number } | Error {
732
+ const missingEntries: string[] = [];
733
+ const result = { missing: missingEntries, files: 0, missingFiles: 0 };
734
+ const visit = (relative: string, missingParent: boolean): Error | undefined => {
735
+ const expected = path.join(published, relative);
736
+ const target = path.join(installed, relative);
737
+ const source = lstatSync(expected);
738
+ const actual = missingParent ? undefined : lstatSync(target, { throwIfNoEntry: false });
739
+ const missing = actual === undefined;
740
+ if (missing && !missingParent) result.missing.push(relative);
741
+ if (source.isDirectory()) {
742
+ if (actual !== undefined && !actual.isDirectory())
743
+ return new Error(`Existing published payload kind mismatch: ${target}`);
744
+ for (const child of readdirSync(expected)) {
745
+ const error = visit(path.join(relative, child), missing);
746
+ if (error !== undefined) return error;
747
+ }
748
+ } else if (source.isFile() || source.isSymbolicLink()) {
749
+ result.files += 1;
750
+ if (missing) result.missingFiles += 1;
751
+ else if (
752
+ source.isFile()
753
+ ? !actual.isFile() || !readFileSync(expected).equals(readFileSync(target))
754
+ : !actual.isSymbolicLink() || readlinkSync(expected) !== readlinkSync(target)
755
+ ) {
756
+ return new Error(`Existing published payload mismatch: ${target}`);
757
+ }
758
+ } else return new Error(`Unsupported published payload kind: ${expected}`);
759
+ return undefined;
760
+ };
761
+ return visit('', false) ?? result;
762
+ }
763
+
764
+ function payloadNodeIdentity(file: string): string | Error {
765
+ const state = lstatSync(file, { bigint: true, throwIfNoEntry: false });
766
+ if (state === undefined) return new Error(`Existing package entry disappeared: ${file}`);
767
+ let value: string;
768
+ if (state.isDirectory()) value = 'directory';
769
+ else if (state.isSymbolicLink()) value = `symlink:${readlinkSync(file)}`;
770
+ else if (state.isFile()) value = `file:${new Bun.CryptoHasher('sha256').update(readFileSync(file)).digest('hex')}`;
771
+ else return new Error(`Unsupported existing package entry: ${file}`);
772
+ return JSON.stringify([value, String(state.mode), String(state.uid), String(state.gid), String(state.mtimeNs)]);
773
+ }
774
+
775
+ function snapshotPayload(root: string): Map<string, string> | Error {
776
+ const entries = new Map<string, string>();
777
+ const visit = (relative: string): Error | undefined => {
778
+ const file = path.join(root, relative);
779
+ const identity = payloadNodeIdentity(file);
780
+ if (identity instanceof Error) return identity;
781
+ entries.set(relative, identity);
782
+ if (lstatSync(file).isDirectory()) {
783
+ for (const child of readdirSync(file)) {
784
+ const error = visit(path.join(relative, child));
785
+ if (error !== undefined) return error;
786
+ }
787
+ }
788
+ return undefined;
789
+ };
790
+ return visit('') ?? entries;
791
+ }
792
+
793
+ function verifyPayloadSnapshot(root: string, entries: ReadonlyMap<string, string>): Error | undefined {
794
+ for (const [relative, expected] of entries) {
795
+ const file = path.join(root, relative);
796
+ const actual = payloadNodeIdentity(file);
797
+ if (actual instanceof Error) return actual;
798
+ if (actual !== expected) return new Error(`Existing package bytes, links or metadata changed: ${file}`);
799
+ }
800
+ return undefined;
801
+ }
802
+
803
+ /** Same native exchange as cowshed-os fsio::rename_exchange; failure changes neither directory entry. */
804
+ function exchangePayloadDirectories(source: string, destination: string): Error | undefined {
805
+ const from = Buffer.from(`${source}\0`);
806
+ const to = Buffer.from(`${destination}\0`);
807
+ if (process.platform === 'darwin') {
808
+ const native = dlopen('/usr/lib/libSystem.B.dylib', {
809
+ renameatx_np: { args: [FFIType.i32, FFIType.ptr, FFIType.i32, FFIType.ptr, FFIType.u32], returns: FFIType.i32 },
810
+ __error: { args: [], returns: FFIType.ptr },
811
+ });
812
+ try {
813
+ if (native.symbols.renameatx_np(-2, from, -2, to, 2) === 0) return undefined;
814
+ const pointer = native.symbols.__error();
815
+ return new Error(
816
+ `Atomic package exchange failed: ${pointer === null ? 'errno unavailable' : getSystemErrorName(-ffiRead.i32(pointer))}; ${source} <-> ${destination}`,
817
+ );
818
+ } finally {
819
+ native.close();
820
+ }
821
+ }
822
+ if (process.platform === 'linux') {
823
+ const native = dlopen('libc.so.6', {
824
+ renameat2: { args: [FFIType.i32, FFIType.ptr, FFIType.i32, FFIType.ptr, FFIType.u32], returns: FFIType.i32 },
825
+ __errno_location: { args: [], returns: FFIType.ptr },
826
+ });
827
+ try {
828
+ if (native.symbols.renameat2(-100, from, -100, to, 2) === 0) return undefined;
829
+ const pointer = native.symbols.__errno_location();
830
+ return new Error(
831
+ `Atomic package exchange failed: ${pointer === null ? 'errno unavailable' : getSystemErrorName(-ffiRead.i32(pointer))}; ${source} <-> ${destination}`,
832
+ );
833
+ } finally {
834
+ native.close();
835
+ }
836
+ }
837
+ return new Error(`Atomic package exchange is unsupported on ${process.platform}`);
838
+ }
839
+
314
840
  /**
315
841
  * One dependency installer shell entry drives. Shell entry runs on every
316
842
  * direnv reload, and an installer whose inputs did not change would only
@@ -323,12 +849,279 @@ async function withInstallLock<T>(run: () => Promise<T>): Promise<T> {
323
849
  */
324
850
  interface Installer {
325
851
  isCurrent(): boolean;
326
- install(options: { quiet: boolean }): Promise<void>;
852
+ install(options: { quiet: boolean }): Promise<void | BunInstallIntegrityError>;
327
853
  }
328
854
 
329
855
  interface InstallStamp {
330
856
  /** sha256 over the installer's identity and the bytes of every input file. */
331
857
  readonly inputs: string;
858
+ /** The successful Bun install's lock bytes; doctor checks these without running Bun. */
859
+ readonly lockfiles?: Readonly<Record<string, string>>;
860
+ }
861
+
862
+ /**
863
+ * What every successful install of node_modules leaves in it, a CI runner's frozen install as well as a
864
+ * developer's: the digest of what it ran on, in `node_modules/.smoo-install`. A developer entry skips the install
865
+ * while the stamp matches and no developer link is stale (bunInstaller), and devenv's smoo:install task lists the file
866
+ * among its inputs, so a checkout without node_modules reads as changed there.
867
+ */
868
+ function bunInstallStamp(inputs: readonly string[]): {
869
+ isCurrent(): boolean;
870
+ record(): BunInstallIntegrityError | undefined;
871
+ } {
872
+ const stampPath = path.join(projectRoot, 'node_modules', '.smoo-install');
873
+ const identity = ['bun install', Bun.version, Bun.revision];
874
+ const lockDigests = (): Readonly<Record<string, string>> => {
875
+ const lockfiles: Record<string, string> = {};
876
+ for (const name of ['bun.lock', 'bun.lockb']) {
877
+ const bytes = readFileIfPresent(path.join(projectRoot, name));
878
+ if (bytes !== null) {
879
+ lockfiles[name] = new Bun.CryptoHasher('sha256').update(bytes).digest('hex');
880
+ }
881
+ }
882
+ return lockfiles;
883
+ };
884
+ return {
885
+ isCurrent: () => {
886
+ const stamp = readInstallStamp(stampPath);
887
+ if (stamp?.inputs !== inputsDigest(identity, inputs) || stamp.lockfiles === undefined) return false;
888
+ const locks = lockDigests();
889
+ return (
890
+ Object.keys(stamp.lockfiles).length === Object.keys(locks).length &&
891
+ Object.entries(locks).every(([name, digest]) => stamp.lockfiles?.[name] === digest)
892
+ );
893
+ },
894
+ record: () => {
895
+ const error = verifyInstalledBunLinks(projectRoot);
896
+ if (error !== undefined) return error;
897
+ writeInstallStamp(stampPath, { inputs: inputsDigest(identity, inputs), lockfiles: lockDigests() });
898
+ return undefined;
899
+ },
900
+ };
901
+ }
902
+
903
+ /** Link/manifest admission only, once before an install writes its success receipt. */
904
+ function verifyInstalledBunLinks(root: string): BunInstallIntegrityError | undefined {
905
+ const store = path.join(root, 'node_modules', '.bun');
906
+ let actualPath = store;
907
+ let expectedTarget = store;
908
+ let operation: BunInstallIntegrityOperation = 'inspect isolated store';
909
+
910
+ const select = (candidate: string, symbolicLink: boolean): void => {
911
+ actualPath = candidate;
912
+ expectedTarget = candidate;
913
+ operation = 'resolve installed path';
914
+ if (symbolicLink) {
915
+ const target = readlinkSync(candidate);
916
+ expectedTarget = path.resolve(path.dirname(candidate), target);
917
+ expectedTarget = path.resolve(realpathSync(path.dirname(candidate)), target);
918
+ }
919
+ realpathSync(candidate);
920
+ };
921
+ const manifest = (candidate: string, symbolicLink: boolean): void => {
922
+ select(candidate, symbolicLink);
923
+ operation = 'read installed package manifest';
924
+ JSON.parse(readFileSync(path.join(candidate, 'package.json'), 'utf8'));
925
+ };
926
+ const aliases = (tree: string, symbolicLink = false): void => {
927
+ select(tree, symbolicLink);
928
+ operation = 'list installed package aliases';
929
+ for (const entry of readdirSync(tree, { withFileTypes: true })) {
930
+ if (entry.name.startsWith('.')) continue;
931
+ const candidate = path.join(tree, entry.name);
932
+ if (entry.name.startsWith('@')) {
933
+ select(candidate, entry.isSymbolicLink());
934
+ operation = 'list installed package aliases';
935
+ for (const scoped of readdirSync(candidate, { withFileTypes: true })) {
936
+ if (!scoped.name.startsWith('.')) manifest(path.join(candidate, scoped.name), scoped.isSymbolicLink());
937
+ }
938
+ } else {
939
+ manifest(candidate, entry.isSymbolicLink());
940
+ }
941
+ }
942
+ };
943
+
944
+ // Admission walks the live closure, not every directory in the store. A restored store can
945
+ // carry superseded peer variants of packages the install also wrote under other variants:
946
+ // their links point into the install cache of the machine that wrote them and dangle here,
947
+ // and their own dependency aliases dangle with them. Nothing the install produced references
948
+ // those variants, so they are not broken live links. An entry is walked strictly when a link
949
+ // in the live tree resolves into it, or when it is the only variant of its package and
950
+ // version — a sole dangling variant still refuses, because there is no replacement to point
951
+ // at. Same package and version alone is never reachability proof.
952
+ const identityOf = (name: string): string | null => /^(.+@\d[^+]*)(\+.*)?$/.exec(name)?.[1] ?? null;
953
+ try {
954
+ const state = lstatSync(store, { throwIfNoEntry: false });
955
+ // A hoisted install has no isolated store to admit.
956
+ if (state === undefined) return undefined;
957
+ select(store, state.isSymbolicLink());
958
+ operation = 'inspect isolated store';
959
+ const entries = readdirSync(store, { withFileTypes: true }).filter((entry) => !entry.name.startsWith('.'));
960
+ const identityCounts = new Map<string, number>();
961
+ for (const entry of entries) {
962
+ if (entry.name === 'node_modules' || !(entry.isDirectory() || entry.isSymbolicLink())) continue;
963
+ const identity = identityOf(entry.name) ?? entry.name;
964
+ identityCounts.set(identity, (identityCounts.get(identity) ?? 0) + 1);
965
+ }
966
+ // Every link in the installed tree that resolves into a store entry makes that entry live.
967
+ const referenced = new Set<string>();
968
+ const knownEntries = new Set(entries.filter((entry) => entry.name !== 'node_modules').map((entry) => entry.name));
969
+ // Where each store entry actually lives: a link can reach an entry through its install
970
+ // cache target (whose basename carries a cache suffix the entry name does not), so live
971
+ // reachability is also containment inside an entry's real directory, not name matching.
972
+ const entryReals = new Map<string, string>();
973
+ for (const entry of entries) {
974
+ if (entry.name === 'node_modules' || !(entry.isDirectory() || entry.isSymbolicLink())) continue;
975
+ try {
976
+ entryReals.set(entry.name, realpathSync(path.join(store, entry.name)));
977
+ } catch {
978
+ // A dangling entry has no real directory for a live alias to land inside.
979
+ }
980
+ }
981
+ const scanLinks = (dir: string, owner: string | null): void => {
982
+ let children: Dirent[];
983
+ try {
984
+ children = readdirSync(dir, { withFileTypes: true });
985
+ } catch {
986
+ return;
987
+ }
988
+ for (const child of children) {
989
+ if (child.name.startsWith('.')) continue;
990
+ const childPath = path.join(dir, child.name);
991
+ if (child.name.startsWith('@')) {
992
+ // A scope is a namespace, symlinked or not: traverse it, never treat it as a package.
993
+ let isDirectory = false;
994
+ try {
995
+ isDirectory = statSync(childPath).isDirectory();
996
+ } catch {
997
+ isDirectory = false;
998
+ }
999
+ if (isDirectory) {
1000
+ scanLinks(childPath, owner);
1001
+ continue;
1002
+ }
1003
+ }
1004
+ if (!child.isSymbolicLink()) continue;
1005
+ let target: string;
1006
+ try {
1007
+ target = readlinkSync(childPath);
1008
+ } catch {
1009
+ continue;
1010
+ }
1011
+ // The alias's canonical endpoint is what it actually reaches — through intermediate
1012
+ // symlinks as well as its literal target — and is what select() already witnesses.
1013
+ // A dangling alias has no endpoint; fall back to resolving its literal target
1014
+ // against the physical parent, so a live reference to a broken entry still marks
1015
+ // that entry referenced.
1016
+ let physicalDir = path.dirname(childPath);
1017
+ try {
1018
+ physicalDir = realpathSync(physicalDir);
1019
+ } catch {
1020
+ // Keep the lexical parent; the segment mark below still applies.
1021
+ }
1022
+ let endpoint: string | null = null;
1023
+ try {
1024
+ endpoint = realpathSync(childPath);
1025
+ } catch {
1026
+ endpoint = null;
1027
+ }
1028
+ const resolved = endpoint ?? path.resolve(physicalDir, target);
1029
+ if (endpoint !== null) {
1030
+ // The canonical endpoint is authoritative: the entry whose real directory
1031
+ // contains it is the live target, whatever any path segment happens to name.
1032
+ for (const [name, real] of entryReals) {
1033
+ if (name !== owner && (endpoint === real || endpoint.startsWith(`${real}${path.sep}`))) {
1034
+ referenced.add(name);
1035
+ break;
1036
+ }
1037
+ }
1038
+ } else {
1039
+ for (const segment of resolved.split(path.sep)) {
1040
+ if (knownEntries.has(segment) && segment !== owner) {
1041
+ referenced.add(segment);
1042
+ break;
1043
+ }
1044
+ }
1045
+ }
1046
+ }
1047
+ };
1048
+ scanLinks(path.join(root, 'node_modules'), null);
1049
+ scanLinks(path.join(store, 'node_modules'), null);
1050
+ // Workspace members keep their own node_modules beside their manifests; links there are
1051
+ // as live as root links, so the closure starts from them too. The enumeration is the one
1052
+ // bunInstallInputs owns: both workspace forms, full glob patterns, exclusions.
1053
+ const rootManifest = parseOrUndefined(() => JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')));
1054
+ const workspaces = field(rootManifest, 'workspaces');
1055
+ const memberPatterns = Array.isArray(workspaces)
1056
+ ? stringList(workspaces)
1057
+ : stringList(field(workspaces, 'packages'));
1058
+ for (const manifestPath of workspaceFiles(memberPatterns, 'package.json')) {
1059
+ scanLinks(path.join(root, path.dirname(manifestPath), 'node_modules'), null);
1060
+ }
1061
+ let grew = true;
1062
+ while (grew) {
1063
+ grew = false;
1064
+ for (const entry of entries) {
1065
+ if (entry.name === 'node_modules' || !(entry.isDirectory() || entry.isSymbolicLink())) continue;
1066
+ if (!referenced.has(entry.name)) continue;
1067
+ const before = referenced.size;
1068
+ scanLinks(path.join(store, entry.name, 'node_modules'), entry.name);
1069
+ if (referenced.size > before) grew = true;
1070
+ }
1071
+ }
1072
+ // Package aliases are what every consumer actually resolves: each package they name must
1073
+ // resolve to a readable manifest, wherever it points — into the store, into the install
1074
+ // cache, or at a workspace member. The same strict walk applies at the root and in every
1075
+ // workspace member's node_modules; member links seeded the closure above, and seeding is
1076
+ // not validation. No identity waiver applies: an alias whose target does not exist is a
1077
+ // broken import, however intact a same-version sibling is.
1078
+ const checkPackage = (candidate: string, symbolicLink: boolean): void => {
1079
+ try {
1080
+ // Only a plain metadata file is skipped; a package alias that resolves to a regular
1081
+ // file is a broken package and manifest() refuses it below.
1082
+ if (!symbolicLink && !statSync(candidate).isDirectory()) return;
1083
+ } catch {
1084
+ // Dangling: manifest() refuses it with the path named.
1085
+ }
1086
+ manifest(candidate, symbolicLink);
1087
+ };
1088
+ const walkPackageAliases = (modules: string): void => {
1089
+ for (const child of readdirSync(modules, { withFileTypes: true })) {
1090
+ if (child.name.startsWith('.')) continue;
1091
+ const childPath = path.join(modules, child.name);
1092
+ if (child.name.startsWith('@')) {
1093
+ // A scope is a namespace, symlinked or not: the same strict alias walk as the store's.
1094
+ aliases(childPath, child.isSymbolicLink());
1095
+ } else {
1096
+ checkPackage(childPath, child.isSymbolicLink());
1097
+ }
1098
+ }
1099
+ };
1100
+ walkPackageAliases(path.join(root, 'node_modules'));
1101
+ for (const manifestPath of workspaceFiles(memberPatterns, 'package.json')) {
1102
+ const memberModules = path.join(root, path.dirname(manifestPath), 'node_modules');
1103
+ // A member with nothing installed has no aliases to validate; a present directory is
1104
+ // walked with the root's strictness.
1105
+ if (existsSync(memberModules)) walkPackageAliases(memberModules);
1106
+ }
1107
+ for (const entry of entries) {
1108
+ const candidate = path.join(store, entry.name);
1109
+ if (entry.name === 'node_modules') {
1110
+ aliases(candidate, entry.isSymbolicLink());
1111
+ } else if (entry.isDirectory() || entry.isSymbolicLink()) {
1112
+ const identity = identityOf(entry.name) ?? entry.name;
1113
+ // An unreferenced variant beside others of its package and version is superseded
1114
+ // garbage the install left behind; nothing live resolves through it, so it is not
1115
+ // walked. A sole variant is walked: there is no replacement to point at.
1116
+ if (!referenced.has(entry.name) && (identityCounts.get(identity) ?? 0) > 1) continue;
1117
+ select(candidate, entry.isSymbolicLink());
1118
+ aliases(path.join(candidate, 'node_modules'));
1119
+ }
1120
+ }
1121
+ return undefined;
1122
+ } catch (cause) {
1123
+ return new BunInstallIntegrityError(operation, actualPath, expectedTarget, cause);
1124
+ }
332
1125
  }
333
1126
 
334
1127
  /**
@@ -338,20 +1131,39 @@ interface InstallStamp {
338
1131
  * copy-on-write clone — is installed exactly when this one is. Besides the
339
1132
  * stamp, the TypeScript API package must still resolve through its link, the
340
1133
  * one package every managed repository installs, which catches a cache that
341
- * was pruned out from under node_modules.
1134
+ * was pruned out from under node_modules. The native compiler binary ttsc
1135
+ * runs is witnessed the same way when the manifest declares it: a pruned
1136
+ * restore that kept the stamp and the API package but lost that binary
1137
+ * otherwise reads as current and no install ever repairs it. A dangling developer target, or a live link to Nx, also invalidates a
1138
+ *
1139
+ * Frozen: shell entry installs what bun.lock records and never rewrites it. An unfrozen install migrated a
1140
+ * repository's lockfile format and re-resolved its ranges, a lockfile diff nobody asked for. A manifest that needs a
1141
+ * lockfile change fails the entry with Bun's reason; `bun install` run on purpose writes that change. A checkout with
1142
+ * no bun.lock yet has nothing to rewrite, and its first install writes it.
342
1143
  */
343
1144
  function bunInstaller(inputs: readonly string[]): Installer {
344
- const stampPath = path.join(projectRoot, 'node_modules', '.smoo-install');
345
- const identity = ['bun install', Bun.version, Bun.revision];
1145
+ const stamp = bunInstallStamp(inputs);
346
1146
  return {
347
1147
  isCurrent: () =>
348
- readInstallStamp(stampPath)?.inputs === inputsDigest(identity, inputs) &&
349
- findInstalledTypeScriptApiPackage(projectRoot) !== null,
1148
+ stamp.isCurrent() &&
1149
+ findInstalledTypeScriptApiPackage(projectRoot) !== null &&
1150
+ (!declaresNativeTypeScript(projectRoot) ||
1151
+ existsSync(path.join(projectRoot, 'node_modules', '@typescript', 'native', 'bin', 'tsc'))) &&
1152
+ !hasStaleDeveloperLinks(projectRoot, ['nx']),
350
1153
  install: async ({ quiet }) => {
351
- await keepDeveloperLinks(projectRoot, () =>
352
- runSetupCommand('bun install --no-summary', $`bun install --no-summary`, { quiet }),
1154
+ await keepDeveloperLinks(
1155
+ projectRoot,
1156
+ () =>
1157
+ existsSync(path.join(projectRoot, 'bun.lock'))
1158
+ ? runSetupCommand(
1159
+ 'bun install --frozen-lockfile --no-summary',
1160
+ $`bun install --frozen-lockfile --no-summary`,
1161
+ { quiet },
1162
+ )
1163
+ : runSetupCommand('bun install --no-summary', $`bun install --no-summary`, { quiet }),
1164
+ { relink: ['nx'] },
353
1165
  );
354
- writeInstallStamp(stampPath, { inputs: inputsDigest(identity, inputs) });
1166
+ return stamp.record();
355
1167
  },
356
1168
  };
357
1169
  }
@@ -433,6 +1245,66 @@ function uvInstaller(inputs: readonly string[], options: { locked: boolean }): I
433
1245
  };
434
1246
  }
435
1247
 
1248
+ /**
1249
+ * `cargo fetch --locked` for one Cargo workspace. The Nx plugin infers every
1250
+ * project's Cargo closure from locked, offline `cargo metadata`, which Cargo
1251
+ * can answer only when the packages Cargo.lock pins are already in
1252
+ * CARGO_HOME; without them the project graph refuses, and the graph's own
1253
+ * `cargo-fetch` target can never run. This establishes that precondition the
1254
+ * way `bun install` establishes node_modules.
1255
+ *
1256
+ * What it installs lives in CARGO_HOME, but the stamp cannot: a sandboxed
1257
+ * shell may write only Cargo's own paths there (its state files and the
1258
+ * `registry` and `git` caches), so a stamp directory fails the entry with
1259
+ * EPERM. It lives in smoo's user cache instead — `$XDG_CACHE_HOME/smoo`, or
1260
+ * `~/.cache/smoo` when the variable is unset, empty or not absolute, as the XDG
1261
+ * base directory rule has it; a cowshed sandbox owns XDG_CACHE_HOME — named by
1262
+ * the digest of the Cargo binary, the CARGO_HOME path, and the workspace's
1263
+ * Cargo.lock, manifest and Cargo configuration.
1264
+ *
1265
+ * A stamp outside CARGO_HOME no longer dies with it, and a stamp that outlived
1266
+ * its packages would promise ones that are gone. So it also records which
1267
+ * directory CARGO_HOME named when the fetch finished — device, inode and
1268
+ * creation time, so a directory deleted and created again at the same path is
1269
+ * another one — and counts only while CARGO_HOME names that directory: a
1270
+ * recreated CARGO_HOME, or another one, fetches again. A copy-on-write clone of
1271
+ * this checkout sharing that CARGO_HOME enters fetched. `--locked` makes a
1272
+ * stale Cargo.lock fail here, in Cargo's words, rather than fetch a graph the
1273
+ * lockfile does not name.
1274
+ */
1275
+ function cargoFetcher(workspace: string): Installer {
1276
+ const manifest = path.posix.join(workspace, 'Cargo.toml');
1277
+ const cargo = Bun.which('cargo');
1278
+ const cargoHome = path.resolve(process.env.CARGO_HOME ?? path.join(homedir(), '.cargo'));
1279
+ const identity = ['cargo fetch --locked', cargo === null ? 'cargo not on PATH' : realpathSync(cargo), cargoHome];
1280
+ const digest = inputsDigest(identity, cargoWorkspaceInputs(workspace));
1281
+ const cacheHome = process.env.XDG_CACHE_HOME;
1282
+ const stampPath = path.join(
1283
+ cacheHome !== undefined && path.isAbsolute(cacheHome) ? cacheHome : path.join(homedir(), '.cache'),
1284
+ 'smoo',
1285
+ 'cargo-fetched',
1286
+ digest,
1287
+ );
1288
+ // What a stamp promises: these inputs were fetched into the directory CARGO_HOME names now.
1289
+ // A CARGO_HOME with nothing at it is an identity of its own.
1290
+ const fetched = () => {
1291
+ const home = statSync(cargoHome, { bigint: true, throwIfNoEntry: false });
1292
+ return inputsDigest([digest, home === undefined ? 'absent' : `${home.dev}:${home.ino}:${home.birthtimeNs}`], []);
1293
+ };
1294
+ return {
1295
+ isCurrent: () => readInstallStamp(stampPath)?.inputs === fetched(),
1296
+ install: async ({ quiet }) => {
1297
+ await runSetupCommand(
1298
+ `cargo fetch --locked --manifest-path ${manifest}`,
1299
+ $`cargo fetch --locked --manifest-path ${manifest}`,
1300
+ { quiet },
1301
+ );
1302
+ // After the fetch, not before: the fetch may be what created CARGO_HOME.
1303
+ writeInstallStamp(stampPath, { inputs: fetched() });
1304
+ },
1305
+ };
1306
+ }
1307
+
436
1308
  /**
437
1309
  * Rewrite every `.pth` line in the environment's site-packages that names a
438
1310
  * directory inside this checkout as a path relative to that site-packages,
@@ -502,6 +1374,30 @@ function uvSyncInputs(): string[] {
502
1374
  return [...new Set(['pyproject.toml', 'uv.lock', ...workspaceFiles(patterns, 'pyproject.toml')])].sort();
503
1375
  }
504
1376
 
1377
+ /**
1378
+ * The Cargo workspaces the Nx plugin resolves: a project directory (the root
1379
+ * or a workspace member, found by its package.json) whose Cargo.toml declares
1380
+ * `[workspace]`.
1381
+ */
1382
+ function cargoWorkspaces(bunInputs: readonly string[]): string[] {
1383
+ const workspaces: string[] = [];
1384
+ for (const projectManifest of bunInputs.filter((input) => path.posix.basename(input) === 'package.json')) {
1385
+ const directory = path.posix.dirname(projectManifest);
1386
+ const content = readFileIfPresent(path.join(projectRoot, path.posix.join(directory, 'Cargo.toml')));
1387
+ if (content !== null && CARGO_WORKSPACE.test(content.toString('utf8'))) {
1388
+ workspaces.push(directory);
1389
+ }
1390
+ }
1391
+ return workspaces.sort();
1392
+ }
1393
+
1394
+ /** What `cargo fetch --locked` reads for the workspace at `directory`, relative to the project root. */
1395
+ function cargoWorkspaceInputs(directory: string): string[] {
1396
+ return ['Cargo.toml', 'Cargo.lock', '.cargo/config', '.cargo/config.toml'].map((file) =>
1397
+ path.posix.join(directory, file),
1398
+ );
1399
+ }
1400
+
505
1401
  /**
506
1402
  * A manifest that does not parse contributes no members, never a failure
507
1403
  * here: its bytes are still an input, so the installer runs and reports the
@@ -570,11 +1466,20 @@ function readInstallStamp(file: string): InstallStamp | null {
570
1466
  }
571
1467
  // A torn or foreign stamp proves nothing was installed, which is what an
572
1468
  // absent one says too: the installer runs and writes a fresh one.
573
- const inputs = field(
574
- parseOrUndefined(() => JSON.parse(bytes.toString('utf8'))),
575
- 'inputs',
576
- );
577
- return typeof inputs === 'string' ? { inputs } : null;
1469
+ const parsed = parseOrUndefined(() => JSON.parse(bytes.toString('utf8')));
1470
+ const inputs = field(parsed, 'inputs');
1471
+ if (typeof inputs !== 'string') return null;
1472
+ const recordedLocks = field(parsed, 'lockfiles');
1473
+ if (typeof recordedLocks !== 'object' || recordedLocks === null || Array.isArray(recordedLocks)) {
1474
+ return { inputs };
1475
+ }
1476
+ const lockfiles: Record<string, string> = {};
1477
+ for (const name of Object.keys(recordedLocks)) {
1478
+ const digest = field(recordedLocks, name);
1479
+ if (typeof digest !== 'string' || !/^[0-9a-f]{64}$/.test(digest)) return { inputs };
1480
+ lockfiles[name] = digest;
1481
+ }
1482
+ return { inputs, lockfiles };
578
1483
  }
579
1484
 
580
1485
  function writeInstallStamp(file: string, stamp: InstallStamp): void {
@@ -593,29 +1498,6 @@ function readFileIfPresent(file: string): Buffer | null {
593
1498
  }
594
1499
  }
595
1500
 
596
- /**
597
- * The files whose change must re-run shell entry's installs, one absolute
598
- * path per line in $DEVENV_STATE/install-inputs. The managed .envrc watches
599
- * each of them, so a shell direnv keeps loaded re-enters exactly when an
600
- * installer would do something. The uv half is recorded whether or not this
601
- * shell syncs one, so that adding a pyproject.toml is itself a change.
602
- */
603
- function recordInstallInputs(inputs: readonly string[]): void {
604
- const state = process.env.DEVENV_STATE;
605
- if (state === undefined) {
606
- return;
607
- }
608
- const file = path.join(state, 'install-inputs');
609
- const content = `${[...new Set(inputs)]
610
- .sort()
611
- .map((input) => path.join(projectRoot, input))
612
- .join('\n')}\n`;
613
- if (readFileIfPresent(file)?.toString('utf8') !== content) {
614
- mkdirSync(state, { recursive: true });
615
- writeFileSync(file, content);
616
- }
617
- }
618
-
619
1501
  function ensureTypeScriptApiPackage(root: string): void {
620
1502
  const apiPackageRoot = findInstalledTypeScriptApiPackage(root);
621
1503
  if (!apiPackageRoot) {
@@ -640,24 +1522,7 @@ function ensureTypeScriptApiPackage(root: string): void {
640
1522
  }
641
1523
 
642
1524
  const nativeBin = path.join(root, 'node_modules', '@typescript', 'native', 'bin', 'tsc');
643
- const rootPackageJson = path.join(root, 'package.json');
644
- const declaresNative =
645
- existsSync(rootPackageJson) &&
646
- (() => {
647
- try {
648
- const pkg = JSON.parse(readFileSync(rootPackageJson, 'utf8')) as {
649
- devDependencies?: Record<string, string>;
650
- dependencies?: Record<string, string>;
651
- };
652
- return (
653
- typeof pkg.devDependencies?.['@typescript/native'] === 'string' ||
654
- typeof pkg.dependencies?.['@typescript/native'] === 'string'
655
- );
656
- } catch {
657
- return false;
658
- }
659
- })();
660
- if (declaresNative && !existsSync(nativeBin)) {
1525
+ if (declaresNativeTypeScript(root) && !existsSync(nativeBin)) {
661
1526
  throw new Error(
662
1527
  `Missing ${nativeBin}. package.json declares @typescript/native but it is not installed. ` +
663
1528
  'Run bun install (or direnv reload). @typescript/native is the TypeScript 7 native compiler for ttsc.',
@@ -665,6 +1530,23 @@ function ensureTypeScriptApiPackage(root: string): void {
665
1530
  }
666
1531
  }
667
1532
 
1533
+ /** Whether the root manifest declares the native compiler, in either dependency field. */
1534
+ function declaresNativeTypeScript(root: string): boolean {
1535
+ const rootPackageJson = path.join(root, 'package.json');
1536
+ if (!existsSync(rootPackageJson)) return false;
1537
+ try {
1538
+ const pkg = JSON.parse(readFileSync(rootPackageJson, 'utf8')) as {
1539
+ devDependencies?: Record<string, string>;
1540
+ dependencies?: Record<string, string>;
1541
+ };
1542
+ return (
1543
+ typeof pkg.devDependencies?.['@typescript/native'] === 'string' ||
1544
+ typeof pkg.dependencies?.['@typescript/native'] === 'string'
1545
+ );
1546
+ } catch {
1547
+ return false;
1548
+ }
1549
+ }
668
1550
  function findInstalledTypeScriptApiPackage(root: string): string | null {
669
1551
  const bunStore = path.join(root, 'node_modules', '.bun');
670
1552
  if (!existsSync(bunStore)) {
@@ -730,9 +1612,7 @@ function assertTypescriptApiAt(typescriptRoot: string, expectedTarget: string):
730
1612
  * package graph exists — not the installer. Called under the install lock.
731
1613
  */
732
1614
  async function applyWorkspaceGitConfig(root: string): Promise<void> {
733
- // A workspace job inherits the installed hooks, but cannot mutate .git/config
734
- // or .git/hooks. Git wiring belongs to setup outside the job's sandbox.
735
- if (process.env.COWSHED_WORKSPACE_TOKEN) return;
1615
+ // Authority is what this process may write, not whether a workspace token exists.
736
1616
  await keepRepositoryConfig(root);
737
1617
 
738
1618
  const gitDirResult = await $`git rev-parse --git-dir`.cwd(root).quiet().nothrow();
@@ -760,13 +1640,14 @@ function linkHook(gitDir: string, tooling: string, name: string): void {
760
1640
  }
761
1641
 
762
1642
  const target = path.join(gitDir, 'hooks', name);
763
- if (readLinkOrNull(target) === source) {
1643
+ const relativeTarget = path.relative(path.dirname(target), source);
1644
+ if (readLinkOrNull(target) === relativeTarget) {
764
1645
  return;
765
1646
  }
766
1647
 
767
1648
  mkdirSync(path.dirname(target), { recursive: true });
768
1649
  rmSync(target, { force: true });
769
- symlinkSync(source, target);
1650
+ symlinkSync(relativeTarget, target);
770
1651
  }
771
1652
 
772
1653
  function installPostCommitHook(gitDir: string, tooling: string): void {
@@ -790,8 +1671,9 @@ function installPostCommitHook(gitDir: string, tooling: string): void {
790
1671
  const kept = stripPostCommitBlock(existing).replace(/\s+$/, '');
791
1672
  const next = `${kept === '' ? '#!/usr/bin/env bash' : kept}\n\n${POST_COMMIT_BLOCK}\n`;
792
1673
  if (existing === next) {
793
- // A hook that is not executable is a hook git silently skips.
794
- chmodSync(target, 0o755);
1674
+ // A hook that is not executable is a hook git silently skips. A correct hook that is
1675
+ // write-denied is left as it is, so only a missing execute bit is repaired.
1676
+ if ((statSync(target).mode & 0o111) === 0) chmodSync(target, 0o755);
795
1677
  return;
796
1678
  }
797
1679
 
@@ -864,9 +1746,10 @@ interface RepositorySetting {
864
1746
  * absolute path names the checkout that first wrote it: a copy-on-write clone
865
1747
  * copies .git/config verbatim, and git refuses to run at all — `fatal: unable
866
1748
  * to access` — when an include exists but cannot be read, which is exactly
867
- * what the original checkout is from inside a sandboxed clone. Every include
868
- * of a workspace.gitconfig is replaced; any other include the user added
869
- * stays.
1749
+ * what the original checkout is from inside a sandboxed clone. Linked worktrees
1750
+ * share their primary checkout's config, so they retain that checkout's
1751
+ * repo-relative include instead of retargeting it into the worktree. Other
1752
+ * includes the user added stay.
870
1753
  *
871
1754
  * Reads and writes therefore go through nothing of git's repository
872
1755
  * discovery: the config file is located on disk and read and edited with
@@ -874,12 +1757,13 @@ interface RepositorySetting {
874
1757
  * follows no stale include.
875
1758
  */
876
1759
  async function keepRepositoryConfig(root: string): Promise<void> {
877
- const configFile = repositoryConfigFile(root);
1760
+ const config = repositoryConfig(root);
1761
+ const configFile = config.file;
878
1762
  const outside = path.parse(configFile).root;
879
1763
  const settings: RepositorySetting[] = [
880
1764
  {
881
1765
  key: 'include.path',
882
- value: path.relative(path.dirname(configFile), path.join(root, 'tooling', 'workspace.gitconfig')),
1766
+ value: path.relative(path.dirname(configFile), path.join(config.checkout, 'tooling', 'workspace.gitconfig')),
883
1767
  replaces: '(^|/)tooling/workspace\\.gitconfig$',
884
1768
  },
885
1769
  // Keep the newer runtime version pins on any merge (nvfetcher overlay +
@@ -925,14 +1809,14 @@ async function keepRepositoryConfig(root: string): Promise<void> {
925
1809
  }
926
1810
 
927
1811
  /**
928
- * The config file git reads as this checkout's local config: `.git/config`,
929
- * or, when `.git` is a worktree's `gitdir:` pointer, the config in that
930
- * worktree's common directory.
1812
+ * The config file and checkout whose include it owns. A standalone gitdir
1813
+ * pointer keeps its checkout; a linked worktree's commondir keeps the primary
1814
+ * checkout, never the linked caller.
931
1815
  */
932
- function repositoryConfigFile(root: string): string {
1816
+ function repositoryConfig(root: string): { file: string; checkout: string } {
933
1817
  const dotGit = path.join(root, '.git');
934
1818
  if (statSync(dotGit).isDirectory()) {
935
- return path.join(dotGit, 'config');
1819
+ return { file: path.join(dotGit, 'config'), checkout: root };
936
1820
  }
937
1821
  const pointer = /^gitdir: (.+)$/m.exec(readFileSync(dotGit, 'utf8'));
938
1822
  if (pointer?.[1] === undefined) {
@@ -940,7 +1824,9 @@ function repositoryConfigFile(root: string): string {
940
1824
  }
941
1825
  const gitDir = path.resolve(root, pointer[1].trim());
942
1826
  const commonDir = readFileIfPresent(path.join(gitDir, 'commondir'));
943
- return path.join(commonDir === null ? gitDir : path.resolve(gitDir, commonDir.toString('utf8').trim()), 'config');
1827
+ if (commonDir === null) return { file: path.join(gitDir, 'config'), checkout: root };
1828
+ const common = path.resolve(gitDir, commonDir.toString('utf8').trim());
1829
+ return { file: path.join(common, 'config'), checkout: path.dirname(common) };
944
1830
  }
945
1831
 
946
1832
  function reportSetupFailure(error: unknown): never {
@@ -990,6 +1876,11 @@ function reportDeferredSecrets(): void {
990
1876
  }
991
1877
 
992
1878
  function describeFailure(level: 'ERROR' | 'WARNING', error: unknown): void {
1879
+ if (error instanceof AggregateError) {
1880
+ console.error(`--- ${level}: setup-environment.ts failed: ${error.message}`);
1881
+ for (const cause of error.errors) describeFailure(level, cause);
1882
+ return;
1883
+ }
993
1884
  if (error instanceof CapturedCommandError) {
994
1885
  console.error(`--- ${level}: setup-environment.ts failed while running: ${error.command}`);
995
1886
  console.error(`exit code: ${error.exitCode}`);