@smoothbricks/nx-plugin 0.4.26 → 0.4.28

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