@smoothbricks/nx-plugin 0.4.25 → 0.4.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/README.md +1078 -98
  2. package/dist/bin/smoo-nx-bound-failures.d.ts +3 -0
  3. package/dist/bin/smoo-nx-bound-failures.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-bound-failures.js +31 -0
  5. package/dist/bin/smoo-nx-cargo-hash.js +28 -3
  6. package/dist/bin/smoo-nx-exec.js +16 -85
  7. package/dist/bin/smoo-nx-failures.d.ts +3 -0
  8. package/dist/bin/smoo-nx-failures.d.ts.map +1 -0
  9. package/dist/bin/smoo-nx-failures.js +3 -0
  10. package/dist/bin/smoo-nx-nextest-extract.js +3 -2
  11. package/dist/bin/smoo-nx-test-walks.d.ts +3 -0
  12. package/dist/bin/smoo-nx-test-walks.d.ts.map +1 -0
  13. package/dist/bin/smoo-nx-test-walks.js +34 -0
  14. package/dist/bounded-test-policy.d.ts +7 -1
  15. package/dist/bounded-test-policy.d.ts.map +1 -1
  16. package/dist/bounded-test-policy.js +101 -40
  17. package/dist/build-state-output-policy.d.ts +25 -0
  18. package/dist/build-state-output-policy.d.ts.map +1 -0
  19. package/dist/build-state-output-policy.js +64 -0
  20. package/dist/cargo-closure-input.d.ts +16 -17
  21. package/dist/cargo-closure-input.d.ts.map +1 -1
  22. package/dist/cargo-closure-input.js +37 -44
  23. package/dist/cargo-dev-profile.d.ts +37 -0
  24. package/dist/cargo-dev-profile.d.ts.map +1 -0
  25. package/dist/cargo-dev-profile.js +108 -0
  26. package/dist/cargo-source-hash.d.ts +50 -8
  27. package/dist/cargo-source-hash.d.ts.map +1 -1
  28. package/dist/cargo-source-hash.js +691 -71
  29. package/dist/cargo-toolchain-policy.d.ts +4 -0
  30. package/dist/cargo-toolchain-policy.d.ts.map +1 -1
  31. package/dist/cargo-toolchain-policy.js +5 -0
  32. package/dist/cargo-workspace.d.ts +108 -12
  33. package/dist/cargo-workspace.d.ts.map +1 -1
  34. package/dist/cargo-workspace.js +299 -18
  35. package/dist/cross-check-policy.d.ts +21 -3
  36. package/dist/cross-check-policy.d.ts.map +1 -1
  37. package/dist/cross-check-policy.js +24 -6
  38. package/dist/disk-command-policy.d.ts +7 -0
  39. package/dist/disk-command-policy.d.ts.map +1 -0
  40. package/dist/disk-command-policy.js +98 -0
  41. package/dist/ensure-built-receipt.d.ts +25 -0
  42. package/dist/ensure-built-receipt.d.ts.map +1 -0
  43. package/dist/ensure-built-receipt.js +261 -0
  44. package/dist/ensure-built-witness.d.ts +57 -0
  45. package/dist/ensure-built-witness.d.ts.map +1 -0
  46. package/dist/ensure-built-witness.js +412 -0
  47. package/dist/ensure-built.d.ts +213 -12
  48. package/dist/ensure-built.d.ts.map +1 -1
  49. package/dist/ensure-built.js +624 -177
  50. package/dist/eslint-file-set.d.ts +7 -0
  51. package/dist/eslint-file-set.d.ts.map +1 -0
  52. package/dist/eslint-file-set.js +12 -0
  53. package/dist/executors/bounded-exec/cpu-pool.d.ts +63 -0
  54. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -0
  55. package/dist/executors/bounded-exec/cpu-pool.js +379 -0
  56. package/dist/executors/bounded-exec/cpu-tokens.d.ts +82 -0
  57. package/dist/executors/bounded-exec/cpu-tokens.d.ts.map +1 -0
  58. package/dist/executors/bounded-exec/cpu-tokens.js +114 -0
  59. package/dist/executors/bounded-exec/disk-lease.d.ts +61 -0
  60. package/dist/executors/bounded-exec/disk-lease.d.ts.map +1 -0
  61. package/dist/executors/bounded-exec/disk-lease.js +91 -0
  62. package/dist/executors/bounded-exec/executor.d.ts +45 -2
  63. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  64. package/dist/executors/bounded-exec/executor.js +447 -52
  65. package/dist/executors/bounded-exec/gateway-lease.d.ts +52 -0
  66. package/dist/executors/bounded-exec/gateway-lease.d.ts.map +1 -0
  67. package/dist/executors/bounded-exec/gateway-lease.js +143 -0
  68. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +35 -0
  69. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -0
  70. package/dist/executors/bounded-exec/hang-diagnostics.js +231 -0
  71. package/dist/executors/bounded-exec/progress.d.ts +35 -0
  72. package/dist/executors/bounded-exec/progress.d.ts.map +1 -0
  73. package/dist/executors/bounded-exec/progress.js +79 -0
  74. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts +3 -0
  75. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts.map +1 -0
  76. package/dist/executors/bounded-exec/ram-temp-fixtures.js +12 -0
  77. package/dist/executors/bounded-exec/ram-temp-held.d.ts +91 -0
  78. package/dist/executors/bounded-exec/ram-temp-held.d.ts.map +1 -0
  79. package/dist/executors/bounded-exec/ram-temp-held.js +152 -0
  80. package/dist/executors/bounded-exec/ram-temp.d.ts +223 -0
  81. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -0
  82. package/dist/executors/bounded-exec/ram-temp.js +1528 -0
  83. package/dist/executors/bounded-exec/schema.d.ts +29 -11
  84. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  85. package/dist/executors/bounded-exec/verdict.d.ts +162 -0
  86. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -0
  87. package/dist/executors/bounded-exec/verdict.js +318 -0
  88. package/dist/executors/shard-timings/executor.d.ts +14 -0
  89. package/dist/executors/shard-timings/executor.d.ts.map +1 -0
  90. package/dist/executors/shard-timings/executor.js +25 -0
  91. package/dist/executors/shard-timings/schema.d.ts +4 -0
  92. package/dist/executors/shard-timings/schema.d.ts.map +1 -0
  93. package/dist/executors/shard-timings/schema.js +1 -0
  94. package/dist/failure-summary.d.ts +5 -0
  95. package/dist/failure-summary.d.ts.map +1 -0
  96. package/dist/failure-summary.js +118 -0
  97. package/dist/generators/create-package/generator.d.ts.map +1 -1
  98. package/dist/generators/create-package/generator.js +6 -2
  99. package/dist/index.d.ts +14 -2
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +435 -230
  102. package/dist/managed-assets.d.ts +6 -0
  103. package/dist/managed-assets.d.ts.map +1 -1
  104. package/dist/managed-files/ci-workflow.d.ts +13 -0
  105. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  106. package/dist/managed-files/ci-workflow.js +44 -13
  107. package/dist/managed-files/files.d.ts +7 -1
  108. package/dist/managed-files/files.d.ts.map +1 -1
  109. package/dist/managed-files/files.js +62 -8
  110. package/dist/managed-files/json-edit.d.ts +21 -0
  111. package/dist/managed-files/json-edit.d.ts.map +1 -0
  112. package/dist/managed-files/json-edit.js +295 -0
  113. package/dist/managed-files/managed-format.d.ts +33 -1
  114. package/dist/managed-files/managed-format.d.ts.map +1 -1
  115. package/dist/managed-files/managed-format.js +82 -2
  116. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts +7 -0
  117. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts.map +1 -1
  118. package/dist/managed-files/pr-preview-cleanup-workflow.js +68 -4
  119. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  120. package/dist/managed-files/publish-workflow.js +231 -48
  121. package/dist/managed-files/tree.d.ts +5 -0
  122. package/dist/managed-files/tree.d.ts.map +1 -1
  123. package/dist/managed-files/tree.js +5 -3
  124. package/dist/manifest-hash.js +3 -2
  125. package/dist/nextest-code-bound.d.ts +62 -0
  126. package/dist/nextest-code-bound.d.ts.map +1 -0
  127. package/dist/nextest-code-bound.js +154 -0
  128. package/dist/nextest-extraction.d.ts +24 -8
  129. package/dist/nextest-extraction.d.ts.map +1 -1
  130. package/dist/nextest-extraction.js +42 -7
  131. package/dist/package-target-policy.d.ts.map +1 -1
  132. package/dist/package-target-policy.js +3 -5
  133. package/dist/release-config-policy.d.ts.map +1 -1
  134. package/dist/release-config-policy.js +3 -5
  135. package/dist/runtime-input.d.ts +14 -0
  136. package/dist/runtime-input.d.ts.map +1 -0
  137. package/dist/runtime-input.js +15 -0
  138. package/dist/rust-tokens.d.ts +11 -0
  139. package/dist/rust-tokens.d.ts.map +1 -0
  140. package/dist/rust-tokens.js +81 -0
  141. package/dist/task-results.d.ts +6 -0
  142. package/dist/task-results.d.ts.map +1 -0
  143. package/dist/task-results.js +61 -0
  144. package/dist/test-program.d.ts +54 -0
  145. package/dist/test-program.d.ts.map +1 -0
  146. package/dist/test-program.js +292 -0
  147. package/dist/test-timings.d.ts +71 -0
  148. package/dist/test-timings.d.ts.map +1 -0
  149. package/dist/test-timings.js +393 -0
  150. package/dist/test-walk-policy.d.ts +103 -0
  151. package/dist/test-walk-policy.d.ts.map +1 -0
  152. package/dist/test-walk-policy.js +657 -0
  153. package/dist/testing.d.ts +177 -0
  154. package/dist/testing.d.ts.map +1 -0
  155. package/dist/testing.js +824 -0
  156. package/dist/type-guards.d.ts +3 -0
  157. package/dist/type-guards.d.ts.map +1 -0
  158. package/dist/type-guards.js +4 -0
  159. package/dist/typecheck-test-policy.d.ts +8 -5
  160. package/dist/typecheck-test-policy.d.ts.map +1 -1
  161. package/dist/typecheck-test-policy.js +113 -100
  162. package/dist/workspace-config-policy.d.ts +8 -0
  163. package/dist/workspace-config-policy.d.ts.map +1 -1
  164. package/dist/workspace-config-policy.js +175 -63
  165. package/dist/workspace-index.d.ts +12 -0
  166. package/dist/workspace-index.d.ts.map +1 -0
  167. package/dist/workspace-index.js +17 -0
  168. package/dist/workspace-manifest.d.ts +37 -1
  169. package/dist/workspace-manifest.d.ts.map +1 -1
  170. package/executors.json +5 -0
  171. package/loader.js +13 -11
  172. package/managed/raw/envrc +33 -62
  173. package/managed/raw/git-format-staged.yml +30 -35
  174. package/managed/raw/patches/nx@23.2.1.patch +3484 -0
  175. package/managed/raw/tooling/direnv/apple-developer.sh +83 -0
  176. package/managed/raw/tooling/direnv/developer-links.ts +607 -17
  177. package/managed/raw/tooling/direnv/devenv.smoo.nix +314 -92
  178. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +20 -11
  179. package/managed/raw/tooling/direnv/linked-snapshots.ts +845 -0
  180. package/managed/raw/tooling/direnv/nx-socket-dir.sh +82 -0
  181. package/managed/raw/tooling/direnv/repo-path +14 -2
  182. package/managed/raw/tooling/direnv/setup-environment.ts +1009 -118
  183. package/managed/raw/tooling/direnv/toolchain-stamp.ts +45 -3
  184. package/managed/raw/tooling/direnv/ttsc-env.sh +39 -0
  185. package/managed/raw/tooling/git-hooks/commit-msg.sh +5 -6
  186. package/managed/raw/tooling/git-hooks/pre-commit.sh +7 -6
  187. package/managed/raw/tooling/git-hooks/pre-push.sh +20 -15
  188. package/managed/templates/github/actions/cache-nix-devenv/action.yml +6 -6
  189. package/managed/templates/github/actions/cache-node-modules/action.yml +6 -4
  190. package/managed/templates/github/actions/cache-nx/action.yml +1 -1
  191. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +1 -1
  192. package/managed/templates/github/actions/forgejo-artifact.cjs +99 -0
  193. package/managed/templates/github/actions/forgejo-download-artifact/action.yml +49 -0
  194. package/managed/templates/github/actions/forgejo-download-artifact/index.cjs +7 -0
  195. package/managed/templates/github/actions/forgejo-upload-artifact/action.yml +65 -0
  196. package/managed/templates/github/actions/forgejo-upload-artifact/index.cjs +7 -0
  197. package/managed/templates/github/actions/setup-devenv/action.yml +21 -3
  198. package/managed/templates/github/workflows/managed-files.yml +1 -2
  199. package/nextest.toml +8 -75
  200. package/package.json +75 -13
  201. package/runtime-input.sh +81 -0
  202. package/src/__tests__/counted-cargo-process.ts +286 -0
  203. package/src/__tests__/counted-cargo.ts +730 -0
  204. package/src/__tests__/fixture-cargo-home.ts +36 -0
  205. package/src/__tests__/fixture-nx-env.ts +157 -2
  206. package/src/__tests__/progress-clock.ts +43 -0
  207. package/src/__tests__/runtime-input.ts +23 -0
  208. package/src/bin/smoo-nx-bound-failures.test.ts +127 -0
  209. package/src/bin/smoo-nx-bound-failures.ts +33 -0
  210. package/src/bin/smoo-nx-cargo-hash.ts +28 -3
  211. package/src/bin/smoo-nx-exec.ts +17 -86
  212. package/src/bin/smoo-nx-failures.ts +4 -0
  213. package/src/bin/smoo-nx-nextest-extract.ts +3 -2
  214. package/src/bin/smoo-nx-test-walks.ts +42 -0
  215. package/src/bounded-test-policy.test.ts +268 -22
  216. package/src/bounded-test-policy.ts +114 -42
  217. package/src/build-state-output-policy.test.ts +115 -0
  218. package/src/build-state-output-policy.ts +90 -0
  219. package/src/bun-bootstrap.test.ts +57 -3
  220. package/src/bun-file-packages.test.ts +47 -0
  221. package/src/cargo-closure-input.test.ts +432 -62
  222. package/src/cargo-closure-input.ts +51 -57
  223. package/src/cargo-dev-profile.ts +137 -0
  224. package/src/cargo-resolve-cache.test.ts +1044 -0
  225. package/src/cargo-source-hash.test.ts +203 -93
  226. package/src/cargo-source-hash.ts +762 -75
  227. package/src/cargo-toolchain-policy.ts +6 -0
  228. package/src/cargo-workspace.test.ts +320 -0
  229. package/src/cargo-workspace.ts +344 -18
  230. package/src/cross-check-policy.test.ts +59 -1
  231. package/src/cross-check-policy.ts +25 -6
  232. package/src/disk-command-policy.test.ts +61 -0
  233. package/src/disk-command-policy.ts +107 -0
  234. package/src/ensure-built-receipt.test.ts +184 -0
  235. package/src/ensure-built-receipt.ts +263 -0
  236. package/src/ensure-built-witness.test.ts +344 -0
  237. package/src/ensure-built-witness.ts +252 -0
  238. package/src/ensure-built.test.ts +1043 -483
  239. package/src/ensure-built.ts +870 -197
  240. package/src/eslint-file-set.ts +9 -0
  241. package/src/executors/bounded-exec/cpu-pool.test.ts +454 -0
  242. package/src/executors/bounded-exec/cpu-pool.ts +417 -0
  243. package/src/executors/bounded-exec/cpu-tokens.test.ts +269 -0
  244. package/src/executors/bounded-exec/cpu-tokens.ts +177 -0
  245. package/src/executors/bounded-exec/disk-lease.test.ts +185 -0
  246. package/src/executors/bounded-exec/disk-lease.ts +139 -0
  247. package/src/executors/bounded-exec/executor-host.test.ts +778 -0
  248. package/src/executors/bounded-exec/executor.test.ts +1116 -63
  249. package/src/executors/bounded-exec/executor.ts +565 -67
  250. package/src/executors/bounded-exec/gateway-lease.ts +176 -0
  251. package/src/executors/bounded-exec/hang-diagnostics.test.ts +285 -0
  252. package/src/executors/bounded-exec/hang-diagnostics.ts +283 -0
  253. package/src/executors/bounded-exec/progress.test.ts +79 -0
  254. package/src/executors/bounded-exec/progress.ts +118 -0
  255. package/src/executors/bounded-exec/ram-temp-fixtures.ts +12 -0
  256. package/src/executors/bounded-exec/ram-temp-held.test.ts +264 -0
  257. package/src/executors/bounded-exec/ram-temp-held.ts +242 -0
  258. package/src/executors/bounded-exec/ram-temp-host.test.ts +605 -0
  259. package/src/executors/bounded-exec/ram-temp.test.ts +674 -0
  260. package/src/executors/bounded-exec/ram-temp.ts +1918 -0
  261. package/src/executors/bounded-exec/schema.json +11 -5
  262. package/src/executors/bounded-exec/schema.ts +27 -11
  263. package/src/executors/bounded-exec/verdict.test.ts +440 -0
  264. package/src/executors/bounded-exec/verdict.ts +433 -0
  265. package/src/executors/shard-timings/executor.ts +36 -0
  266. package/src/executors/shard-timings/schema.json +21 -0
  267. package/src/executors/shard-timings/schema.ts +4 -0
  268. package/src/failure-summary.ts +119 -0
  269. package/src/generators/bounded-test-targets/generator.test.ts +4 -4
  270. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  271. package/src/generators/create-package/generator.test.ts +6 -0
  272. package/src/generators/create-package/generator.ts +6 -2
  273. package/src/host-controller-wiring.test.ts +31 -0
  274. package/src/index.test.ts +1070 -360
  275. package/src/index.ts +524 -255
  276. package/src/linked-snapshots.nx.test.ts +172 -0
  277. package/src/managed-assets.ts +12 -0
  278. package/src/managed-files/ci-workflow.ts +54 -13
  279. package/src/managed-files/files.ts +65 -9
  280. package/src/managed-files/forgejo-artifact.test.ts +395 -0
  281. package/src/managed-files/generator.test.ts +60 -1
  282. package/src/managed-files/json-edit.test.ts +216 -0
  283. package/src/managed-files/json-edit.ts +290 -0
  284. package/src/managed-files/managed-format-json.test.ts +308 -0
  285. package/src/managed-files/managed-format.ts +90 -2
  286. package/src/managed-files/pr-preview-cleanup-workflow.ts +69 -3
  287. package/src/managed-files/publish-workflow.ts +285 -67
  288. package/src/managed-files/repo-path.test.ts +129 -0
  289. package/src/managed-files/trace-db-artifact.test.ts +7 -0
  290. package/src/managed-files/tree.ts +11 -3
  291. package/src/manifest-hash.ts +3 -2
  292. package/src/nextest-code-bound.test.ts +155 -0
  293. package/src/nextest-code-bound.ts +195 -0
  294. package/src/nextest-extraction.test.ts +37 -5
  295. package/src/nextest-extraction.ts +51 -9
  296. package/src/nextest-partitions.test.ts +495 -0
  297. package/src/nx-cache-bound.test.ts +109 -0
  298. package/src/nx-cache-restore-mtime.test.ts +170 -0
  299. package/src/nx-daemon-claim.test.ts +277 -0
  300. package/src/nx-daemon-idle-cpu.test.ts +81 -0
  301. package/src/nx-daemon-idle-policy.test.ts +51 -0
  302. package/src/nx-daemon-ignore-files.test.ts +210 -0
  303. package/src/nx-daemon-root-normalization.test.ts +105 -0
  304. package/src/nx-daemon-validity.test.ts +925 -0
  305. package/src/nx-dot-input-policy.test.ts +353 -0
  306. package/src/nx-failure-life-cycles.test.ts +207 -0
  307. package/src/nx-files-archive-racy.test.ts +97 -0
  308. package/src/nx-foreign-workspace-env.test.ts +329 -0
  309. package/src/nx-incomplete-run-summary.test.ts +70 -0
  310. package/src/nx-plugin-load-errors.test.ts +120 -0
  311. package/src/nx-project-resolution-cache.test.ts +176 -0
  312. package/src/nx-raw-inputs.test.ts +166 -0
  313. package/src/nx-resident-graph-workers.test.ts +112 -0
  314. package/src/nx-run-information.test.ts +118 -0
  315. package/src/nx-skipped-task-exit.test.ts +180 -0
  316. package/src/nx-state-location.test.ts +63 -0
  317. package/src/nx-store-resolution.test.ts +99 -0
  318. package/src/nx-task-graph-cycles.test.ts +148 -0
  319. package/src/nx-task-output-lease.test.ts +414 -0
  320. package/src/nx-use-local.test.ts +103 -0
  321. package/src/package-target-policy.ts +3 -6
  322. package/src/release-config-policy.ts +3 -6
  323. package/src/runtime-input.test.ts +215 -0
  324. package/src/runtime-input.ts +17 -0
  325. package/src/rust-tokens.ts +78 -0
  326. package/src/serial-group-wiring.test.ts +326 -0
  327. package/src/task-history-namespace.test.ts +181 -0
  328. package/src/task-results.test.ts +226 -0
  329. package/src/task-results.ts +75 -0
  330. package/src/test-program.test.ts +303 -0
  331. package/src/test-program.ts +341 -0
  332. package/src/test-timings.test.ts +240 -0
  333. package/src/test-timings.ts +311 -0
  334. package/src/test-walk-policy.test.ts +585 -0
  335. package/src/test-walk-policy.ts +731 -0
  336. package/src/testing.test.ts +509 -0
  337. package/src/testing.ts +922 -0
  338. package/src/type-guards.ts +4 -0
  339. package/src/typecheck-test-policy.test.ts +496 -11
  340. package/src/typecheck-test-policy.ts +137 -103
  341. package/src/workspace-config-policy.test.ts +212 -13
  342. package/src/workspace-config-policy.ts +101 -73
  343. package/src/workspace-index.ts +18 -0
  344. package/src/workspace-manifest.ts +41 -1
  345. package/test-timings.json +85 -28
  346. package/managed/raw/tooling/direnv/inherited-devenv.ts +0 -615
  347. package/managed/raw/tooling/direnv/shared-caches.sh +0 -53
  348. package/src/__tests__/in-process-nx-index.ts +0 -9
@@ -1,16 +1,40 @@
1
- import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
2
- import { spawn } from 'node:child_process';
3
- import { chmod, mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { chmod, mkdir, mkdtemp, readdir, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
- import { dirname, join } from 'node:path';
5
+ import { dirname, isAbsolute, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { stripVTControlCharacters } from 'node:util';
8
-
7
+ import type { ProjectGraph } from 'nx/src/config/project-graph';
9
8
  import type { Task } from 'nx/src/config/task-graph';
10
-
9
+ import type { DaemonProcessJson } from 'nx/src/daemon/cache';
10
+ import { expandOutputs } from 'nx/src/native';
11
+ import { getExecutorNameForTask } from 'nx/src/tasks-runner/utils';
11
12
  import { signalToCode } from 'nx/src/utils/exit-codes';
12
-
13
- import { cliExitOutcome, describeMiss, firstCacheMiss, parseTargetSelector, unvouched } from './ensure-built.js';
13
+ import typia from 'typia';
14
+ import { nxFixtureRoot, withNxFixture } from './__tests__/fixture-nx-env.js';
15
+ import {
16
+ assignEnvironment,
17
+ callerOwnsWorkspace,
18
+ cliExitOutcome,
19
+ compareWithArtifacts,
20
+ describeError,
21
+ describeMiss,
22
+ ensureBuilt,
23
+ firstCacheMiss,
24
+ firstMovedClaim,
25
+ missBeforeProbe,
26
+ outputClaims,
27
+ parseExecArguments,
28
+ parseTargetSelector,
29
+ recordedTasks,
30
+ selectorTaskId,
31
+ unvouched,
32
+ withoutOuterTaskCacheBypass,
33
+ workspaceEnvironment,
34
+ workspaceFileChanges,
35
+ } from './ensure-built.js';
36
+ import { managedAssetsRoot } from './managed-assets.js';
37
+ import { NX_LONGEST_SOCKET_NAME, ownedSocketDirectory, pidsWorkingIn } from './testing.js';
14
38
 
15
39
  function task(overrides: Partial<Task> & Pick<Task, 'id'>): Task {
16
40
  const [project, target] = overrides.id.split(':');
@@ -46,6 +70,60 @@ describe('parseTargetSelector', () => {
46
70
  });
47
71
  });
48
72
 
73
+ describe('selectorTaskId', () => {
74
+ it('is the id Nx gives the task a selector names, configuration included', () => {
75
+ expect(selectorTaskId({ project: 'app', target: 'build', configuration: undefined })).toBe('app:build');
76
+ expect(selectorTaskId({ project: 'app', target: 'build', configuration: 'production' })).toBe(
77
+ 'app:build:production',
78
+ );
79
+ });
80
+ });
81
+
82
+ describe('parseExecArguments', () => {
83
+ function usageOf(args: readonly string[]): string {
84
+ const parsed = parseExecArguments(args);
85
+ if (parsed.ok) {
86
+ throw new Error(`${args.join(' ')} parsed as ${JSON.stringify(parsed.invocation)}`);
87
+ }
88
+ return parsed.usage;
89
+ }
90
+
91
+ it('reads the target, a workspace root in either spelling, and the binary with its arguments', () => {
92
+ expect(parseExecArguments(['app:build', '--workspace-root', '/w', '--', './cli', '--flag'])).toEqual({
93
+ ok: true,
94
+ invocation: { target: 'app:build', workspaceRoot: '/w', command: ['./cli', '--flag'] },
95
+ });
96
+ expect(parseExecArguments(['--workspace-root=/w', 'app:build:production'])).toEqual({
97
+ ok: true,
98
+ invocation: { target: 'app:build:production', workspaceRoot: '/w', command: [] },
99
+ });
100
+ });
101
+
102
+ it('rejects a malformed invocation, naming the mistake', () => {
103
+ expect(usageOf(['app:build', '--'])).toContain('no binary given');
104
+ expect(usageOf(['build', '--', './report'])).toContain('not a project:target');
105
+ expect(usageOf(['app:build', '--', 'report'])).toContain('not a name to look up on PATH');
106
+ expect(usageOf(['app:build', 'lib:build'])).toContain('more than one target');
107
+ expect(usageOf(['app:build', '--workspace-root'])).toContain('--workspace-root needs a directory');
108
+ expect(usageOf(['app:build', '--watch'])).toContain('unknown flag --watch');
109
+ expect(usageOf([])).toContain('no project:target given');
110
+ });
111
+ });
112
+
113
+ describe('describeError', () => {
114
+ it('prints the message of a plain-object Nx rejection, never [object Object]', () => {
115
+ expect(describeError({ stack: 'synthetic stack', message: 'daemon belongs to a different workspace' })).toBe(
116
+ 'daemon belongs to a different workspace',
117
+ );
118
+ });
119
+
120
+ it('prints an Error by its message, a string as itself, and anything else inspected on one line', () => {
121
+ expect(describeError(new Error('boom'))).toBe('boom');
122
+ expect(describeError('plain')).toBe('plain');
123
+ expect(describeError({ code: 7, nested: { deep: true } })).toBe('{ code: 7, nested: { deep: true } }');
124
+ });
125
+ });
126
+
49
127
  describe('firstCacheMiss', () => {
50
128
  const cached = new Map([
51
129
  ['hash-of-app:build', 0],
@@ -92,6 +170,62 @@ describe('firstCacheMiss', () => {
92
170
  });
93
171
  });
94
172
 
173
+ describe('recordedTasks', () => {
174
+ // The project graph Nx hands the probe, reduced to the executors it is asked for.
175
+ const graph: ProjectGraph = {
176
+ nodes: {
177
+ app: {
178
+ name: 'app',
179
+ type: 'app',
180
+ data: {
181
+ root: 'packages/app',
182
+ targets: {
183
+ build: { executor: 'nx:run-commands' },
184
+ // A command-less target that only names dependencies, as Nx normalizes it.
185
+ stage: { executor: 'nx:noop' },
186
+ ship: { executor: 'nx:run-commands' },
187
+ deploy: { executor: 'nx:run-commands' },
188
+ },
189
+ },
190
+ },
191
+ },
192
+ dependencies: {},
193
+ };
194
+ const executorOf = (entry: Task) => getExecutorNameForTask(entry, graph);
195
+ const records = new Map([
196
+ ['hash-of-app:build', 0],
197
+ ['hash-of-app:ship', 0],
198
+ ]);
199
+
200
+ it('needs no cache record for an uncacheable nx:noop aggregate, whose dependencies answer for it', () => {
201
+ const tasks = [task({ id: 'app:build' }), task({ id: 'app:stage', cache: false }), task({ id: 'app:ship' })];
202
+ const recorded = recordedTasks(tasks, executorOf);
203
+ expect(recorded.map(({ id }) => id)).toEqual(['app:build', 'app:ship']);
204
+ expect(firstCacheMiss(recorded, records)).toBeNull();
205
+ });
206
+
207
+ it('still holds an uncacheable task with a command to account', () => {
208
+ const tasks = [task({ id: 'app:build' }), task({ id: 'app:deploy', cache: false })];
209
+ expect(firstCacheMiss(recordedTasks(tasks, executorOf), records)).toEqual({
210
+ kind: 'uncacheable',
211
+ taskId: 'app:deploy',
212
+ });
213
+ });
214
+ });
215
+
216
+ describe('outputClaims', () => {
217
+ it('claims the declared outputs of every hashed task that declares any, under its hash', () => {
218
+ const tasks = [
219
+ task({ id: 'lib:build', outputs: ['packages/lib/dist'] }),
220
+ task({ id: 'app:stage' }),
221
+ task({ id: 'app:build', outputs: ['packages/app/dist'], hash: undefined }),
222
+ ];
223
+ expect(outputClaims(tasks)).toEqual([
224
+ { taskId: 'lib:build', outputs: ['packages/lib/dist'], hash: 'hash-of-lib:build' },
225
+ ]);
226
+ });
227
+ });
228
+
95
229
  describe('unvouched', () => {
96
230
  const tasks = [task({ id: 'lib:build', outputs: ['lib/dist'] }), task({ id: 'app:build', outputs: ['app/dist'] })];
97
231
 
@@ -109,6 +243,179 @@ describe('unvouched', () => {
109
243
  });
110
244
  });
111
245
 
246
+ describe('compareWithArtifacts', () => {
247
+ it('reuses a verified two-tree inventory without expanding or rereading artifact bytes', () => {
248
+ const path = join(root, 'verified.json');
249
+ let walks = 0;
250
+ const expand: typeof expandOutputs = (...args) => {
251
+ walks += 1;
252
+ return expandOutputs(...args);
253
+ };
254
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expand, path).kind).toBe('restorable');
255
+ expect(walks).toBeGreaterThan(0);
256
+ walks = 0;
257
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expand, path).kind).toBe('restorable');
258
+ expect(walks).toBe(0);
259
+ });
260
+
261
+ it('invalidates verified equality for output or cache mutations even with restored mtime', async () => {
262
+ const path = join(root, 'verified.json');
263
+ const artifact = artifacts().get(claim.hash);
264
+ if (artifact === undefined) throw new Error('Missing cache artifact in output-mutation fixture');
265
+ const expected = join(artifact.outputsPath, 'packages/app/dist/marker.txt');
266
+ for (const file of [marker(), expected]) {
267
+ await writeFile(marker(), 'built\nlib\n');
268
+ await writeFile(expected, 'built\nlib\n');
269
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
270
+ const { stat, utimes } = await import('node:fs/promises');
271
+ const original = await stat(file);
272
+ await writeFile(file, 'BUILT\nLIB\n');
273
+ await utimes(file, original.atime, original.mtime);
274
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path)).toEqual({
275
+ kind: 'stale-outputs',
276
+ taskId: 'app:build',
277
+ });
278
+ }
279
+ });
280
+
281
+ it('invalidates inventories for deletion, permission changes, parent symlinks and added directory members', async () => {
282
+ const path = join(root, 'verified.json');
283
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
284
+ await chmod(marker(), 0o700);
285
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('stale-outputs');
286
+ await chmod(marker(), 0o644);
287
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
288
+ await writeFile(join(workspace(), 'packages/app/dist/added'), 'added');
289
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('stale-outputs');
290
+ await rm(join(workspace(), 'packages/app/dist/added'));
291
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
292
+ await rm(marker());
293
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('stale-outputs');
294
+ await writeFile(marker(), 'built\nlib\n');
295
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
296
+ const { rename } = await import('node:fs/promises');
297
+ await rename(join(workspace(), 'packages/app'), join(workspace(), 'packages/real-app'));
298
+ await symlink('real-app', join(workspace(), 'packages/app'));
299
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('stale-outputs');
300
+ });
301
+
302
+ it('falls back to real comparison for missing/unreadable witness and a changed cache binding', async () => {
303
+ const path = join(root, 'verified.json');
304
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
305
+ await chmod(path, 0);
306
+ try {
307
+ expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
308
+ } finally {
309
+ await chmod(path, 0o600);
310
+ }
311
+ const renamed = join(root, 'cache', 'other', 'outputs');
312
+ await mkdir(join(renamed, 'packages/app/dist'), { recursive: true });
313
+ await writeFile(join(renamed, 'packages/app/dist/marker.txt'), 'other');
314
+ expect(
315
+ compareWithArtifacts(workspace(), [claim], new Map([[claim.hash, { outputsPath: renamed }]]), expandOutputs, path)
316
+ .kind,
317
+ ).toBe('stale-outputs');
318
+ });
319
+ // A working tree and the artifact Nx's local cache holds for the claim's
320
+ // hash, laid out as Nx stores one: the outputs under their workspace paths.
321
+ let root = '';
322
+ const claim = { taskId: 'app:build', outputs: ['packages/app/dist'], hash: 'app-hash' };
323
+ const workspace = () => join(root, 'workspace');
324
+ const marker = () => join(workspace(), 'packages', 'app', 'dist', 'marker.txt');
325
+ const artifacts = () => new Map([[claim.hash, { outputsPath: join(root, 'cache', claim.hash, 'outputs') }]]);
326
+ const compare = () => compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs);
327
+
328
+ beforeEach(async () => {
329
+ root = await realpath(await mkdtemp(join(tmpdir(), 'ensure-built-artifact-')));
330
+ for (const base of [workspace(), join(root, 'cache', claim.hash, 'outputs')]) {
331
+ await mkdir(join(base, 'packages', 'app', 'dist'), { recursive: true });
332
+ await writeFile(join(base, 'packages', 'app', 'dist', 'marker.txt'), 'built\nlib\n');
333
+ }
334
+ });
335
+
336
+ afterEach(async () => {
337
+ await rm(root, { recursive: true, force: true });
338
+ });
339
+
340
+ it('vouches for a working tree that restoring the artifact would leave unchanged', () => {
341
+ expect(compare().kind).toBe('restorable');
342
+ });
343
+
344
+ it('never vouches for rewritten output bytes', async () => {
345
+ // Same length, different bytes: only a content comparison can tell.
346
+ await writeFile(marker(), 'BUILT\nLIB\n');
347
+ expect(compare()).toEqual({ kind: 'stale-outputs', taskId: 'app:build' });
348
+ });
349
+
350
+ it('runs again once a recorded output is gone from the working tree', async () => {
351
+ await rm(marker());
352
+ expect(compare()).toEqual({ kind: 'stale-outputs', taskId: 'app:build' });
353
+ });
354
+
355
+ it('runs again when the cache holds no artifact for the hash', () => {
356
+ expect(compareWithArtifacts(workspace(), [claim], new Map(), expandOutputs)).toEqual({
357
+ kind: 'stale-outputs',
358
+ taskId: 'app:build',
359
+ });
360
+ });
361
+
362
+ it('notices an output written after it was compared', async () => {
363
+ const verdict = compare();
364
+ if (verdict.kind !== 'restorable') {
365
+ throw new Error(`expected a restorable tree, got ${JSON.stringify(verdict)}`);
366
+ }
367
+ expect(firstMovedClaim(verdict.observed)).toBeNull();
368
+ await writeFile(marker(), 'built\nlib\nlater\n');
369
+ expect(firstMovedClaim(verdict.observed)).toBe('app:build');
370
+ });
371
+ });
372
+
373
+ describe('workspaceFileChanges', () => {
374
+ it("splits the disk's file table from the daemon's into created, updated and deleted files", () => {
375
+ const daemon = [
376
+ { file: 'packages/lib/source.txt', hash: 'lib' },
377
+ { file: 'packages/lib/added.txt', hash: 'added' },
378
+ { file: 'packages/app/source.txt', hash: 'app' },
379
+ ];
380
+ const disk = [
381
+ { file: 'packages/lib/source.txt', hash: 'lib changed' },
382
+ { file: 'packages/app/source.txt', hash: 'app' },
383
+ { file: 'packages/lib/new.txt', hash: 'new' },
384
+ ];
385
+ expect(workspaceFileChanges(daemon, disk)).toEqual({
386
+ created: ['packages/lib/new.txt'],
387
+ updated: ['packages/lib/source.txt'],
388
+ deleted: ['packages/lib/added.txt'],
389
+ });
390
+ });
391
+ });
392
+
393
+ describe('missBeforeProbe', () => {
394
+ it("drops an outer Nx task's cache bypass, which describes that task rather than the nested target", () => {
395
+ const outer = {
396
+ NX_TASK_TARGET_PROJECT: 'nx-plugin',
397
+ NX_TASK_TARGET_TARGET: 'test',
398
+ NX_SKIP_NX_CACHE: 'true',
399
+ NX_DISABLE_NX_CACHE: 'true',
400
+ };
401
+ const nested = withoutOuterTaskCacheBypass(outer);
402
+ expect(nested).toEqual({ NX_TASK_TARGET_PROJECT: 'nx-plugin', NX_TASK_TARGET_TARGET: 'test' });
403
+ expect(missBeforeProbe(nested, 'app:build')).toBeNull();
404
+ });
405
+
406
+ it('honors a cache bypass the caller asked for outside an Nx task child', () => {
407
+ for (const env of [{ NX_SKIP_NX_CACHE: 'true' }, { NX_DISABLE_NX_CACHE: 'true' }]) {
408
+ const caller = withoutOuterTaskCacheBypass(env);
409
+ expect(caller).toEqual(env);
410
+ expect(missBeforeProbe(caller, 'app:build')).toEqual({ kind: 'cache-disabled', taskId: 'app:build' });
411
+ }
412
+ });
413
+
414
+ it('leaves current input and artifact evaluation to the probe', () => {
415
+ expect(missBeforeProbe({}, 'app:build')).toBeNull();
416
+ });
417
+ });
418
+
112
419
  describe('describeMiss', () => {
113
420
  it('names the task in every reason', () => {
114
421
  const reasons = [
@@ -117,7 +424,6 @@ describe('describeMiss', () => {
117
424
  describeMiss({ kind: 'not-cached', taskId: 'app:build' }),
118
425
  describeMiss({ kind: 'cached-failure', taskId: 'app:build', code: 7 }),
119
426
  describeMiss({ kind: 'stale-outputs', taskId: 'app:build' }),
120
- describeMiss({ kind: 'stale-inputs', taskId: 'app:build' }),
121
427
  describeMiss({ kind: 'cache-disabled', taskId: 'app:build' }),
122
428
  describeMiss({ kind: 'no-daemon', taskId: 'app:build' }),
123
429
  ];
@@ -158,23 +464,115 @@ describe('cliExitOutcome', () => {
158
464
  });
159
465
  });
160
466
 
467
+ describe('the environment Nx runs under', () => {
468
+ const caller = {
469
+ PATH: '/usr/bin',
470
+ NX_SOCKET_DIR: '/tmp/other-sock',
471
+ NX_DAEMON_SOCKET_DIR: '/tmp/other-daemon-sock',
472
+ NX_WORKSPACE_DATA_DIRECTORY: '/shared/workspace-data',
473
+ NX_CACHE_DIRECTORY: '/shared/cache',
474
+ };
475
+ let root = '';
476
+ const workspace = () => join(root, 'workspace');
477
+ const elsewhere = () => join(root, 'elsewhere');
478
+
479
+ beforeEach(async () => {
480
+ root = await realpath(await mkdtemp(join(tmpdir(), 'ensure-built-caller-')));
481
+ await mkdir(join(workspace(), 'packages'), { recursive: true });
482
+ await mkdir(elsewhere());
483
+ await writeFile(join(workspace(), 'nx.json'), '{}');
484
+ });
485
+
486
+ afterEach(async () => {
487
+ await rm(root, { recursive: true, force: true });
488
+ });
489
+
490
+ it("passes none of another workspace's socket, database or cache to the root's Nx", () => {
491
+ // A devenv shell set up for another workspace, entering this root from outside it.
492
+ const owns = callerOwnsWorkspace(caller, elsewhere(), workspace());
493
+ expect(owns).toBe(false);
494
+ expect(workspaceEnvironment(caller, workspace(), owns)).toEqual({
495
+ PATH: '/usr/bin',
496
+ NX_WORKSPACE_ROOT_PATH: workspace(),
497
+ NX_USE_LOCAL: 'true',
498
+ });
499
+ });
500
+
501
+ it('keeps the socket, database and cache of a caller standing in the root it was set up for', () => {
502
+ const owns = callerOwnsWorkspace(caller, join(workspace(), 'packages'), workspace());
503
+ expect(owns).toBe(true);
504
+ expect(workspaceEnvironment({ ...caller, NX_USE_LOCAL: 'false' }, workspace(), owns)).toEqual({
505
+ ...caller,
506
+ NX_WORKSPACE_ROOT_PATH: workspace(),
507
+ NX_USE_LOCAL: 'true',
508
+ });
509
+ });
510
+
511
+ it("takes the caller's workspace from NX_WORKSPACE_ROOT_PATH, relative to where it stands, over its nx.json", () => {
512
+ expect(callerOwnsWorkspace({ NX_WORKSPACE_ROOT_PATH: '../workspace' }, elsewhere(), workspace())).toBe(true);
513
+ expect(callerOwnsWorkspace({ NX_WORKSPACE_ROOT_PATH: elsewhere() }, workspace(), workspace())).toBe(false);
514
+ });
515
+
516
+ it("leaves the caller's environment exactly as it was, whatever Nx set, changed or removed", () => {
517
+ const callerEnv = { PATH: '/usr/bin', NX_SKIP_NX_CACHE: 'caller-skip', NX_DISABLE_NX_CACHE: 'caller-disable' };
518
+ const env: NodeJS.ProcessEnv = {
519
+ PATH: '/usr/bin',
520
+ NX_WORKSPACE_ROOT_PATH: workspace(),
521
+ NX_STREAM_OUTPUT: 'true',
522
+ NX_SKIP_NX_CACHE: 'false',
523
+ };
524
+ assignEnvironment(env, callerEnv);
525
+ expect(env).toEqual(callerEnv);
526
+ });
527
+
528
+ it('retains a real socket-owner mkdir refusal before any target can run', async () => {
529
+ const blocker = join(root, 'ordinary-file');
530
+ const marker = join(workspace(), 'target-ran');
531
+ await writeFile(blocker, 'not a directory');
532
+ await writeFile(
533
+ join(workspace(), 'project.json'),
534
+ JSON.stringify({
535
+ name: 'app',
536
+ targets: { build: { executor: 'nx:run-commands', options: { command: 'touch target-ran' } } },
537
+ }),
538
+ );
539
+ const saved = { ...process.env };
540
+ try {
541
+ process.env.DEVENV_RUNTIME = join(blocker, 'runtime');
542
+ process.env.NX_WORKSPACE_ROOT_PATH = elsewhere();
543
+ process.env.NX_SOCKET_DIR = elsewhere();
544
+ const result = await ensureBuilt({ target: 'app:build', cwd: workspace() });
545
+ expect(result.disposition).toBe('failed');
546
+ if (result.disposition !== 'failed') throw new Error('the socket owner must refuse before the target runs');
547
+ expect(result.reason.kind).toBe('workspace-socket');
548
+ if (result.reason.kind !== 'workspace-socket') throw new Error('the refusal must retain its socket owner');
549
+ expect(result.reason.taskId).toBe('app:build');
550
+ expect(result.reason.workspaceRoot).toBe(workspace());
551
+ expect(result.reason.detail).toContain('socket owner ended with exit');
552
+ expect(result.reason.detail).toContain('mkdir:');
553
+ expect(result.reason.detail).toContain(blocker);
554
+ expect(result.exitCode).not.toBe(0);
555
+ expect(result.signal).toBeNull();
556
+ expect(await readFile(blocker, 'utf8')).toBe('not a directory');
557
+ await expect(readFile(marker)).rejects.toMatchObject({ code: 'ENOENT' });
558
+ } finally {
559
+ assignEnvironment(process.env, saved);
560
+ }
561
+ });
562
+ });
563
+
161
564
  const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
162
565
  const repoRoot = dirname(dirname(packageRoot));
163
566
  const binEntry = join(packageRoot, 'src', 'bin', 'smoo-nx-exec.ts');
164
567
  const builtBinEntry = join(packageRoot, 'dist', 'bin', 'smoo-nx-exec.js');
568
+ const nxEntry = join(repoRoot, 'node_modules', '.bin', 'nx');
165
569
  const MARKER = 'EXEC_OK';
166
- /** Nx keys controlled and reported by the fixture rather than inherited from its parent test task. */
167
- const NX_ENV_KEYS = [
168
- 'NX_WORKSPACE_ROOT_PATH',
169
- 'NX_STREAM_OUTPUT',
170
- 'NX_PREFIX_OUTPUT',
171
- 'NX_LOAD_DOT_ENV_FILES',
172
- 'NX_SKIP_NX_CACHE',
173
- 'NX_DISABLE_NX_CACHE',
174
- 'NX_CACHE_DIRECTORY',
175
- 'NX_WORKSPACE_DATA_DIRECTORY',
176
- ];
177
- const SHARED_NX_DIRECTORY_KEYS = ['NX_CACHE_DIRECTORY', 'NX_WORKSPACE_DATA_DIRECTORY'] as const;
570
+ /**
571
+ * Reports what the exec'd process inherited: the marker proves execve
572
+ * happened, the cwd that it kept the caller's directory, and the root path
573
+ * that the wrapper took its Nx configuration back out of the environment.
574
+ */
575
+ const REPORT = `#!/bin/sh\necho ${MARKER} "$@"\necho "cwd=$PWD"\necho "NX_WORKSPACE_ROOT_PATH=\${NX_WORKSPACE_ROOT_PATH:-unset}"\n`;
178
576
 
179
577
  interface BinRun {
180
578
  readonly code: number | null;
@@ -183,520 +581,682 @@ interface BinRun {
183
581
  readonly stderr: string;
184
582
  }
185
583
 
186
- function fixtureNxEnvironment(env: Readonly<NodeJS.ProcessEnv> = {}): NodeJS.ProcessEnv {
187
- const childEnv = { ...process.env };
188
- for (const key of NX_ENV_KEYS) {
189
- delete childEnv[key];
190
- }
191
- // The parent Nx process may set FORCE_COLOR while the shell exports
192
- // NO_COLOR. Passing both to Bun emits a warning, which would make a genuine
193
- // full hit look noisy.
194
- delete childEnv.NO_COLOR;
195
- childEnv.CI = '';
196
- childEnv.NX_DAEMON = 'true';
197
- for (const [key, value] of Object.entries(env)) {
198
- if (value === undefined) {
199
- delete childEnv[key];
200
- } else {
584
+ /**
585
+ * This process's environment without the `NX_*` an outer
586
+ * `nx run nx-plugin:test` exported to it (its cache bypass and task identity
587
+ * would reconfigure the fixture's Nx), and without NO_COLOR, which beside that
588
+ * outer Nx's FORCE_COLOR makes Bun warn on stderr, where a hit must be silent.
589
+ */
590
+ function childEnvironment(env: Readonly<Record<string, string>>): Record<string, string> {
591
+ const childEnv: Record<string, string> = {};
592
+ for (const [key, value] of Object.entries(process.env)) {
593
+ if (value !== undefined && !key.startsWith('NX_') && key !== 'NO_COLOR') {
201
594
  childEnv[key] = value;
202
595
  }
203
596
  }
204
- // CI shares these directories among the outer Nx tasks. A fixture Nx using
205
- // either one can replace the orchestrator's project graph while sibling
206
- // tasks are still running.
207
- for (const key of SHARED_NX_DIRECTORY_KEYS) {
208
- delete childEnv[key];
209
- }
210
- return childEnv;
597
+ return { ...childEnv, CI: '', ...env };
211
598
  }
212
599
 
213
600
  /**
214
- * The bin is exercised in a child process rather than by calling `ensureBuilt`
215
- * directly, for two reasons that are not incidental: Nx binds its workspace
216
- * root once per process, so a single test process cannot probe a fixture
217
- * workspace and then anything else; and `execve` replaces the process, which is
218
- * the behaviour under test.
601
+ * The wrapper runs in a child process because `execve` replaces the process,
602
+ * which is the behaviour under test.
219
603
  */
220
- function runBinWith(
604
+ function run(
221
605
  runtime: 'bun' | 'node',
222
606
  entry: string,
223
- workspace: string,
607
+ cwd: string,
224
608
  args: readonly string[],
225
- env: Readonly<NodeJS.ProcessEnv>,
609
+ env: Readonly<Record<string, string>>,
226
610
  ): Promise<BinRun> {
227
- const childEnv = fixtureNxEnvironment(env);
228
611
  const child = spawn(runtime, [entry, ...args], {
229
- cwd: workspace,
230
- env: childEnv,
612
+ cwd,
613
+ env: childEnvironment(env),
231
614
  stdio: ['ignore', 'pipe', 'pipe'],
232
615
  });
233
616
  let stdout = '';
234
617
  let stderr = '';
235
- child.stdout.on('data', (chunk: Buffer) => {
236
- stdout += chunk.toString();
618
+ child.stdout.setEncoding('utf8').on('data', (text: string) => {
619
+ stdout += text;
237
620
  });
238
- child.stderr.on('data', (chunk: Buffer) => {
239
- stderr += chunk.toString();
621
+ child.stderr.setEncoding('utf8').on('data', (text: string) => {
622
+ stderr += text;
240
623
  });
241
- // `Promise.withResolvers` would read better but needs lib es2024; this
242
- // package inherits lib es2022 from tsconfig.base.json.
243
- return new Promise((settle, reject) => {
244
- child.once('error', reject);
245
- child.once('close', (code, signal) => settle({ code, signal, stdout, stderr }));
246
- });
247
- }
248
-
249
- function runBin(workspace: string, args: readonly string[], env: Readonly<NodeJS.ProcessEnv> = {}): Promise<BinRun> {
250
- return runBinWith('bun', binEntry, workspace, args, env);
624
+ const { promise, resolve, reject } = Promise.withResolvers<BinRun>();
625
+ child.once('error', reject);
626
+ child.once('close', (code, signal) => resolve({ code, signal, stdout, stderr }));
627
+ return promise;
251
628
  }
252
629
 
253
- function runBuiltBin(workspace: string, args: readonly string[]): Promise<BinRun> {
254
- return runBinWith('node', builtBinEntry, workspace, args, {});
630
+ async function writeExecutable(path: string, content: string): Promise<void> {
631
+ await writeFile(path, content);
632
+ await chmod(path, 0o755);
255
633
  }
256
634
 
257
- function nx(workspace: string, args: readonly string[]): Promise<BinRun> {
258
- return runBinWith('node', join(repoRoot, 'node_modules', '.bin', 'nx'), workspace, args, {
259
- NX_WORKSPACE_ROOT_PATH: workspace,
260
- });
261
- }
262
-
263
- describe('smoo-nx-exec', () => {
635
+ describe('smoo-nx-exec without a daemon', () => {
636
+ // A workspace whose `nx` is a script standing in for the CLI. With the
637
+ // daemon off, the wrapper loads no Nx at all and hands the target straight
638
+ // to that CLI, so what runs here is the wrapper's own process handling —
639
+ // stdio, exit status, signals, cwd, environment, execve — and no Nx.
264
640
  let workspace = '';
265
- const report = () => join(workspace, 'report');
266
- const marker = () => join(workspace, 'packages', 'app', 'dist', 'marker.txt');
267
- // Outside the workspace: a log inside it would be an undeclared output the
268
- // snapshot diff rightly reports as a changed input.
269
- const builds = () => `${workspace}-lib-builds.log`;
270
- const ships = () => `${workspace}-app-ships.log`;
641
+ const daemonless = { NX_DAEMON: 'false' };
642
+ const wrapper = (cwd: string, args: readonly string[], env: Readonly<Record<string, string>> = {}) =>
643
+ run('bun', binEntry, cwd, args, { ...daemonless, ...env });
271
644
 
272
645
  beforeAll(async () => {
273
- // Realpath because macOS puts the temp directory behind a /private
274
- // symlink, and a process's reported cwd is the resolved one.
275
- workspace = await realpath(await mkdtemp(join(tmpdir(), 'ensure-built-')));
276
- // Cowshed's scratch is ignored by its enclosing Git checkout. This is an
277
- // independent Nx workspace: its own Git boundary keeps the daemon's
278
- // ignore-aware watcher from dropping all of its source changes.
279
- const initialized = Bun.spawnSync(['git', 'init', '--quiet', workspace]);
280
- expect(initialized.exitCode).toBe(0);
646
+ workspace = await nxFixtureRoot('ensure-built-cli-');
647
+ await mkdir(join(workspace, 'node_modules', '.bin'), { recursive: true });
281
648
  await mkdir(join(workspace, 'packages', 'app'), { recursive: true });
282
- await mkdir(join(workspace, 'packages', 'lib'), { recursive: true });
283
- // The repository's own node_modules, so the fixture resolves the same Nx
284
- // this package is written against, including node_modules/.bin/nx for the
285
- // daemon-disabled path.
286
- await symlink(join(repoRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
287
- await writeFile(join(workspace, 'nx.json'), JSON.stringify({ useDaemonProcess: true }));
288
- await writeFile(
289
- join(workspace, 'packages', 'lib', 'project.json'),
290
- JSON.stringify({
291
- name: 'lib',
292
- targets: {
293
- build: {
294
- executor: 'nx:run-commands',
295
- cache: true,
296
- inputs: ['{projectRoot}/source*.txt'],
297
- outputs: ['{projectRoot}/dist'],
298
- options: {
299
- command: `mkdir -p dist && cat source*.txt > dist/lib.txt && cat dist/lib.txt >> ${builds()}`,
300
- cwd: '{projectRoot}',
301
- },
302
- },
303
- },
304
- }),
305
- );
306
- // Digit-suffixed so `source*.txt` expands in the same order under every
307
- // locale: en_US.UTF-8 collation ignores punctuation at the first level and
308
- // would put `source2.txt` before `source.txt`.
309
- await writeFile(join(workspace, 'packages', 'lib', 'source1.txt'), 'lib\n');
310
- await writeFile(
311
- join(workspace, 'packages', 'app', 'project.json'),
312
- JSON.stringify({
313
- name: 'app',
314
- targets: {
315
- build: {
316
- executor: 'nx:run-commands',
317
- cache: true,
318
- // `dependentTasksOutputFiles` is the discriminating part of this
319
- // fixture: Nx's runner-warmup hasher deliberately leaves such a
320
- // task unhashed, so a probe that used it instead of hashing every
321
- // task would classify this graph 'unhashable' and never hit.
322
- inputs: ['{projectRoot}/source.txt', { dependentTasksOutputFiles: '**/*' }],
323
- outputs: ['{projectRoot}/dist'],
324
- dependsOn: ['^build'],
325
- options: {
326
- command: 'mkdir -p dist && cat source.txt ../lib/dist/lib.txt > dist/marker.txt',
327
- cwd: '{projectRoot}',
328
- },
329
- },
330
- broken: {
331
- executor: 'nx:run-commands',
332
- cache: true,
333
- options: { command: 'exit 3', cwd: '{projectRoot}' },
334
- },
335
- // A command-less aggregate, as Nx normalizes any target that only
336
- // names dependencies. It declares no `cache`, so it is uncacheable.
337
- stage: {
338
- executor: 'nx:noop',
339
- dependsOn: ['build'],
340
- },
341
- // A cacheable leaf that reaches its build only through the aggregate.
342
- ship: {
343
- executor: 'nx:run-commands',
344
- cache: true,
345
- inputs: ['{projectRoot}/source.txt'],
346
- dependsOn: ['stage'],
347
- options: { command: `cat dist/marker.txt >> ${ships()}`, cwd: '{projectRoot}' },
348
- },
349
- },
350
- implicitDependencies: ['lib'],
351
- }),
352
- );
353
- await writeFile(join(workspace, 'packages', 'app', 'source.txt'), 'built\n');
354
- // Reports what the exec'd process actually inherited: the marker proves
355
- // execve happened, the cwd proves it kept the caller's directory, and the
356
- // NX_ lines prove temporary Nx configuration was removed or restored.
357
- await writeFile(
358
- report(),
359
- `#!/bin/sh\necho ${MARKER} "$@"\necho "cwd=$PWD"\n${NX_ENV_KEYS.map((key) => `echo "${key}=\${${key}:-unset}"`).join('\n')}\n`,
649
+ await writeFile(join(workspace, 'nx.json'), '{}');
650
+ // `nx run <task> --outputStyle=stream`, as the wrapper starts it on a miss.
651
+ await writeExecutable(
652
+ join(workspace, 'node_modules', '.bin', 'nx'),
653
+ '#!/bin/sh\necho "nx run $2"\ncase "$2" in\n app:broken) exit 3 ;;\n app:killed) kill -TERM $$ ;;\nesac\n',
360
654
  );
361
- await chmod(report(), 0o755);
655
+ await writeExecutable(join(workspace, 'report'), REPORT);
362
656
  });
363
657
 
364
658
  afterAll(async () => {
365
659
  if (workspace) {
366
- await nx(workspace, ['daemon', '--stop']);
367
660
  await rm(workspace, { recursive: true, force: true });
368
- await rm(builds(), { force: true });
369
- await rm(ships(), { force: true });
370
661
  }
371
662
  });
372
663
 
373
- it('reuses the normal Nx CLI cache before executing the binary', async () => {
374
- const built = await nx(workspace, ['run-many', '-t', 'build', '-p', 'app', '--outputStyle=static-failures-only']);
375
- expect(built.code, built.stdout + built.stderr).toBe(0);
376
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib\n');
377
- expect(await readFile(builds(), 'utf-8')).toBe('lib\n');
378
-
379
- const run = await runBin(workspace, ['app:build', '--', './report', 'one']);
380
- expect(run.code).toBe(0);
381
- expect(run.stderr).toBe('');
382
- expect(run.stdout.split('\n')[0]).toBe(`${MARKER} one`);
383
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib\n');
384
- expect(await readFile(builds(), 'utf-8')).toBe('lib\n');
385
- });
386
-
387
- it('stays completely silent on a full cache hit', async () => {
388
- const run = await runBin(workspace, ['app:build', '--', './report']);
389
- expect(run.code).toBe(0);
390
- expect(run.stderr).toBe('');
391
- // Nothing but the exec'd binary's own output: no Nx banner, no task log.
392
- expect(run.stdout.split('\n')[0]).toBe(MARKER);
393
- expect(run.stdout).not.toContain('nx run');
394
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib\n');
395
- expect(await readFile(builds(), 'utf-8')).toBe('lib\n');
396
- });
397
-
398
- it('stays silent through an uncacheable nx:noop aggregate, which has no command to run', async () => {
399
- const first = await runBin(workspace, ['app:ship', '--', './report']);
400
- expect(first.code, first.stdout + first.stderr).toBe(0);
401
- expect(await readFile(ships(), 'utf-8')).toBe('built\nlib\n');
402
-
403
- // Every task but the aggregate is now a recorded success. Treating the
404
- // aggregate like an uncacheable command hands the whole graph back to Nx,
405
- // which replays each dependency's cached log on every invocation.
406
- const again = await runBin(workspace, ['app:ship', '--', './report']);
407
- expect(again.code).toBe(0);
408
- expect(again.stderr).toBe('');
409
- expect(again.stdout.split('\n')[0], again.stdout).toBe(MARKER);
410
- expect(again.stdout).not.toContain('nx run');
411
- expect(await readFile(ships(), 'utf-8')).toBe('built\nlib\n');
412
- expect(await readFile(builds(), 'utf-8')).toBe('lib\n');
413
- });
414
-
415
- it('stays silent when the daemon has lost its record of outputs that still match the cache', async () => {
416
- // The daemon's output records live in memory and are lossy: a restart
417
- // drops every one, and in a busy workspace a restore's own write events can
418
- // be processed after Nx's 2 s grace and erase the record just made. Either
419
- // way the working tree still holds exactly the cached bytes.
420
- const stopped = await nx(workspace, ['daemon', '--stop']);
421
- expect(stopped.code, stopped.stdout + stopped.stderr).toBe(0);
422
-
423
- const run = await runBin(workspace, ['app:build', '--', './report']);
424
- expect(run.code).toBe(0);
425
- expect(run.stderr).toBe('');
426
- expect(run.stdout.split('\n')[0], run.stdout).toBe(MARKER);
427
- expect(await readFile(builds(), 'utf-8')).toBe('lib\n');
428
- });
429
-
430
- it('never vouches for rewritten output bytes the daemon holds no record of', async () => {
431
- const stopped = await nx(workspace, ['daemon', '--stop']);
432
- expect(stopped.code, stopped.stdout + stopped.stderr).toBe(0);
433
- // Same length, different bytes: only a content comparison can tell.
434
- await writeFile(marker(), 'BUILT\nLIB\n');
435
-
436
- const run = await runBin(workspace, ['app:build', '--', './report'], { NX_VERBOSE_LOGGING: 'true' });
437
- expect(run.code).toBe(0);
438
- expect(run.stderr).toContain('app:build outputs are missing or modified on disk');
439
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib\n');
440
- expect(await readFile(builds(), 'utf-8')).toBe('lib\n');
664
+ it('shows the run on stderr, then execs the binary with stdout its own', async () => {
665
+ const result = await wrapper(workspace, ['app:build', '--', './report', 'one']);
666
+ expect(result.code, result.stderr).toBe(0);
667
+ // Stdout is the exec'd binary's and holds nothing else, or `wrapper | jq` reads Nx's log as data.
668
+ expect(result.stderr).toContain('nx run app:build');
669
+ expect(result.stdout).toBe(`${MARKER} one\ncwd=${workspace}\nNX_WORKSPACE_ROOT_PATH=unset\n`);
441
670
  });
442
671
 
443
- it('runs the emitted wrapper under Node without losing the hot path', async () => {
444
- const run = await runBuiltBin(workspace, ['app:build', '--', './report']);
445
- expect(run.code).toBe(0);
446
- expect(run.stderr).toBe('');
447
- expect(run.stdout.split('\n')[0]).toBe(MARKER);
672
+ it('without a binary, shows the run on stderr, says why it ran, and exits 0', async () => {
673
+ const result = await wrapper(workspace, ['app:build'], { NX_VERBOSE_LOGGING: 'true' });
674
+ expect(result.code, result.stderr).toBe(0);
675
+ expect(result.stdout).toBe('');
676
+ expect(result.stderr).toContain('nx run app:build');
677
+ expect(result.stderr).toContain(
678
+ `smoo-nx-exec: ran app:build because ${describeMiss({ kind: 'no-daemon', taskId: 'app:build' })}`,
679
+ );
448
680
  });
449
681
 
450
- it("hands the exec'd binary blocking stdio, so a pipe its output fills is never cut", async () => {
451
- // Node leaves a pipe O_NONBLOCK on macOS, and the flag belongs to the open file description, so
452
- // it survives execve: the binary's writes then fail with EAGAIN once the pipe holds 64 KiB and
453
- // nobody is reading. A reader that starts late is what makes the pipe fill.
454
- const flood = join(workspace, 'flood');
455
- await writeFile(flood, '#!/bin/sh\nhead -c 300000 /dev/zero\n');
456
- await chmod(flood, 0o755);
457
- try {
458
- const piped = Bun.spawn(
459
- ['sh', '-c', `"$0" "$1" app:build -- ./flood | { sleep 1; tr -cd '\\000' | wc -c; }`, 'node', builtBinEntry],
460
- { cwd: workspace, env: fixtureNxEnvironment(), stdout: 'pipe', stderr: 'pipe' },
461
- );
462
- const received = (await new Response(piped.stdout).text()).trim();
463
- expect(await piped.exited).toBe(0);
464
- expect(received).toBe('300000');
465
- } finally {
466
- await rm(flood, { force: true });
467
- }
682
+ it("forwards a failing target's exit code and never execs", async () => {
683
+ const result = await wrapper(workspace, ['app:broken', '--', './report']);
684
+ expect(result.code).toBe(3);
685
+ expect(result.stderr).toContain('nx run app:broken');
686
+ expect(result.stdout).toBe('');
468
687
  });
469
688
 
470
- it('leaves the exec\u0027d binary the caller\u0027s cwd and none of Nx\u0027s environment', async () => {
471
- // Invoked from a subdirectory, with the binary named relative to it: the
472
- // resolution the wrapper's users actually perform.
473
- const run = await runBin(join(workspace, 'packages', 'app'), [
474
- 'app:build',
475
- '--workspace-root',
476
- workspace,
477
- '--',
478
- '../../report',
479
- ]);
480
- expect(run.code).toBe(0);
481
- expect(run.stdout).toContain(`cwd=${join(workspace, 'packages', 'app')}`);
482
- for (const key of NX_ENV_KEYS) {
483
- expect(run.stdout).toContain(`${key}=unset`);
484
- }
689
+ it('re-raises the signal that killed nx instead of flattening it to a code', async () => {
690
+ const result = await wrapper(workspace, ['app:killed', '--', './report']);
691
+ expect(result.signal).toBe('SIGTERM');
692
+ expect(result.stdout).toBe('');
485
693
  });
486
694
 
487
- it('keeps fixture Nx out of CI shared state directories', async () => {
488
- const run = await runBin(workspace, ['app:build', '--', './report'], {
489
- NX_CACHE_DIRECTORY: join(workspace, 'shared-cache'),
490
- NX_WORKSPACE_DATA_DIRECTORY: join(workspace, 'shared-workspace-data'),
491
- });
492
- expect(run.code).toBe(0);
493
- expect(run.stdout).toContain('NX_CACHE_DIRECTORY=unset');
494
- expect(run.stdout).toContain('NX_WORKSPACE_DATA_DIRECTORY=unset');
695
+ it("leaves the exec'd binary the caller's cwd, with the binary named relative to it", async () => {
696
+ const app = join(workspace, 'packages', 'app');
697
+ const result = await wrapper(app, ['app:build', '--workspace-root', workspace, '--', '../../report']);
698
+ expect(result.code, result.stderr).toBe(0);
699
+ expect(result.stdout).toBe(`${MARKER}\ncwd=${app}\nNX_WORKSPACE_ROOT_PATH=unset\n`);
495
700
  });
496
701
 
497
- it('restores the caller cache controls before exec', async () => {
498
- const run = await runBin(workspace, ['app:build', '--', './report'], {
499
- NX_SKIP_NX_CACHE: 'caller-skip',
500
- NX_DISABLE_NX_CACHE: 'caller-disable',
501
- });
502
- expect(run.code).toBe(0);
503
- expect(run.stderr).toBe('');
504
- expect(run.stdout).toContain('NX_SKIP_NX_CACHE=caller-skip');
505
- expect(run.stdout).toContain('NX_DISABLE_NX_CACHE=caller-disable');
702
+ it("hands the exec'd binary blocking stdio, so a pipe its output fills is never cut", async () => {
703
+ // Node leaves a pipe O_NONBLOCK on macOS, and the flag belongs to the open file description, so
704
+ // it survives execve: the binary's writes then fail with EAGAIN once the pipe holds 64 KiB and
705
+ // nobody is reading. A reader that starts late is what makes the pipe fill.
706
+ const flood = join(workspace, 'flood');
707
+ await writeExecutable(flood, '#!/bin/sh\nhead -c 300000 /dev/zero\n');
708
+ const piped = Bun.spawn(
709
+ ['sh', '-c', `"$0" "$1" app:build -- ./flood | { sleep 1; tr -cd '\\000' | wc -c; }`, 'node', builtBinEntry],
710
+ { cwd: workspace, env: childEnvironment(daemonless), stdout: 'pipe', stderr: 'pipe' },
711
+ );
712
+ const received = (await new Response(piped.stdout).text()).trim();
713
+ expect(await piped.exited).toBe(0);
714
+ expect(received).toBe('300000');
506
715
  });
716
+ });
507
717
 
508
- it('honors a user cache bypass outside an Nx task child', async () => {
509
- const run = await runBin(workspace, ['app:build', '--', './report'], {
510
- NX_TASK_TARGET_PROJECT: undefined,
511
- NX_TASK_TARGET_TARGET: undefined,
512
- NX_SKIP_NX_CACHE: 'true',
513
- NX_VERBOSE_LOGGING: 'true',
514
- });
515
- expect(run.code).toBe(0);
516
- expect(run.stderr).toContain('the Nx cache is disabled, so app:build must run');
517
- expect(run.stdout).toContain(MARKER);
518
- expect(run.stdout).toContain('NX_SKIP_NX_CACHE=true');
519
- });
718
+ /** Fixture Nx configuration: its cache and database stay under its removable root. */
719
+ const FIXTURE_NX_JSON = { useDaemonProcess: true, cacheDirectory: '.nx/cache' };
520
720
 
521
- it('runs again once a recorded output is gone from the working tree', async () => {
522
- const before = await readFile(builds(), 'utf-8');
523
- await rm(marker());
524
- const run = await runBin(workspace, ['app:build', '--', './report'], { NX_VERBOSE_LOGGING: 'true' });
525
- expect(run.code).toBe(0);
526
- expect(run.stderr).toContain('outputs are missing or modified on disk');
527
- expect(run.stdout).toContain(MARKER);
528
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib\n');
529
- expect(await readFile(builds(), 'utf-8')).toBe(before);
530
- });
531
-
532
- it('runs again when a dependency\u0027s own inputs change, keeping stdout for the binary alone', async () => {
533
- const before = await readFile(builds(), 'utf-8');
534
- await writeFile(join(workspace, 'packages', 'lib', 'source1.txt'), 'lib changed\n');
535
- const changed = await runBin(workspace, ['app:build', '--', './report']);
536
- expect(changed.code).toBe(0);
537
- expect(await readFile(join(workspace, 'packages', 'lib', 'dist', 'lib.txt'), 'utf-8')).toBe('lib changed\n');
538
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib changed\n');
539
- expect(await readFile(builds(), 'utf-8')).toBe(`${before}lib changed\n`);
540
- // The run's log is on stderr. Stdout is the exec'd binary's and holds
541
- // nothing else, or `wrapper | jq` reads Nx's banner as data.
542
- expect(stripVTControlCharacters(changed.stderr)).toContain('nx run lib:build');
543
- expect(changed.stdout.split('\n')[0], changed.stdout).toBe(MARKER);
544
- for (const line of changed.stdout.split('\n').filter((line) => line !== '')) {
545
- expect(line === MARKER || line.startsWith('cwd=') || /^NX_[A-Z_]+=/.test(line), line).toBe(true);
546
- }
721
+ /**
722
+ * Two projects, `app:build` reading `lib:build`'s outputs through
723
+ * `dependentTasksOutputFiles`: Nx's runner-warmup hasher leaves such a task
724
+ * unhashed, so a probe that used it instead of hashing every task would call
725
+ * this graph 'unhashable' and never hit. Each lib build appends to `builds`,
726
+ * outside the workspace: a log inside it would be an undeclared output the
727
+ * snapshot diff rightly reports as a changed input.
728
+ */
729
+ async function writeTwoProjectWorkspace(workspace: string, builds: string): Promise<void> {
730
+ // Cowshed's scratch is ignored by its enclosing Git checkout. This is an
731
+ // independent Nx workspace: its own Git boundary keeps the daemon's
732
+ // ignore-aware watcher from dropping all of its source changes.
733
+ expect(Bun.spawnSync(['git', 'init', '--quiet', workspace]).exitCode).toBe(0);
734
+ await writeFile(join(workspace, '.gitignore'), '.nx\nnode_modules\npackages/*/dist\n');
735
+ await mkdir(join(workspace, 'packages', 'app'), { recursive: true });
736
+ await mkdir(join(workspace, 'packages', 'lib'), { recursive: true });
737
+ // The repository's own node_modules, so the fixture resolves the Nx this package is written against.
738
+ await symlink(join(repoRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
739
+ await writeFile(join(workspace, 'nx.json'), JSON.stringify(FIXTURE_NX_JSON));
740
+ await writeFile(
741
+ join(workspace, 'packages', 'lib', 'project.json'),
742
+ JSON.stringify({
743
+ name: 'lib',
744
+ targets: {
745
+ build: {
746
+ executor: 'nx:run-commands',
747
+ cache: true,
748
+ inputs: ['{projectRoot}/source.txt'],
749
+ outputs: ['{projectRoot}/dist'],
750
+ options: {
751
+ command: `mkdir -p dist && cp source.txt dist/lib.txt && cat dist/lib.txt >> ${builds}`,
752
+ cwd: '{projectRoot}',
753
+ },
754
+ },
755
+ },
756
+ }),
757
+ );
758
+ await writeFile(join(workspace, 'packages', 'lib', 'source.txt'), 'lib\n');
759
+ await writeFile(
760
+ join(workspace, 'packages', 'app', 'project.json'),
761
+ JSON.stringify({
762
+ name: 'app',
763
+ targets: {
764
+ build: {
765
+ executor: 'nx:run-commands',
766
+ cache: true,
767
+ inputs: ['{projectRoot}/source.txt', { dependentTasksOutputFiles: '**/*' }],
768
+ outputs: ['{projectRoot}/dist'],
769
+ dependsOn: ['^build'],
770
+ options: {
771
+ command: 'mkdir -p dist && cat source.txt ../lib/dist/lib.txt > dist/marker.txt',
772
+ cwd: '{projectRoot}',
773
+ },
774
+ },
775
+ },
776
+ implicitDependencies: ['lib'],
777
+ }),
778
+ );
779
+ await writeFile(join(workspace, 'packages', 'app', 'source.txt'), 'built\n');
780
+ await writeExecutable(join(workspace, 'report'), REPORT);
781
+ }
547
782
 
548
- // And the graph settles back to silence, which is only reachable if the
549
- // dependent-outputs task was hashed too.
550
- const settled = await runBin(workspace, ['app:build', '--', './report']);
551
- expect(settled.code).toBe(0);
552
- expect(settled.stderr).toBe('');
553
- expect(settled.stdout.split('\n')[0]).toBe(MARKER);
554
- expect(await readFile(builds(), 'utf-8')).toBe(`${before}lib changed\n`);
555
- });
556
-
557
- it('runs again when a dependency input is added or deleted', async () => {
558
- const addedSource = join(workspace, 'packages', 'lib', 'source2.txt');
559
- await writeFile(addedSource, 'added\n');
560
- const added = await runBin(workspace, ['app:build', '--', './report']);
561
- expect(added.code).toBe(0);
562
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib changed\nadded\n');
563
-
564
- await rm(addedSource);
565
- const removed = await runBin(workspace, ['app:build', '--', './report']);
566
- expect(removed.code).toBe(0);
567
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib changed\n');
568
-
569
- const settled = await runBin(workspace, ['app:build', '--', './report']);
570
- expect(settled.code).toBe(0);
571
- expect(settled.stderr).toBe('');
572
- expect(settled.stdout.split('\n')[0]).toBe(MARKER);
573
- });
574
-
575
- it('without a binary, stays silent and exits 0 when nothing is stale', async () => {
576
- const run = await runBin(workspace, ['app:build']);
577
- expect(run.code, run.stdout + run.stderr).toBe(0);
578
- expect(run.stdout).toBe('');
579
- expect(run.stderr).toBe('');
580
- });
581
-
582
- it('without a binary, runs what is stale, shows that run and exits 0', async () => {
583
- const before = await readFile(builds(), 'utf-8');
584
- await writeFile(join(workspace, 'packages', 'lib', 'source1.txt'), 'lib checked\n');
585
- const run = await runBin(workspace, ['app:build']);
586
- expect(run.code, run.stdout + run.stderr).toBe(0);
587
- // An outer `nx run nx-plugin:test` exports FORCE_COLOR, so the fixture's
588
- // Nx styles its task lines; what the test pins is the line, not its colour.
589
- expect(stripVTControlCharacters(run.stderr)).toContain('nx run lib:build');
590
- expect(run.stdout).toBe('');
591
- expect(await readFile(marker(), 'utf-8')).toBe('built\nlib checked\n');
592
- expect(await readFile(builds(), 'utf-8')).toBe(`${before}lib checked\n`);
593
-
594
- const settled = await runBin(workspace, ['app:build']);
595
- expect(settled.code, settled.stdout + settled.stderr).toBe(0);
596
- expect(settled.stdout).toBe('');
597
- expect(settled.stderr).toBe('');
598
- });
599
-
600
- it('without a binary, exits with a failing target\u0027s code', async () => {
601
- const run = await runBin(workspace, ['app:broken']);
602
- expect(run.code).toBe(1);
603
- expect(stripVTControlCharacters(run.stderr)).toContain('nx run app:broken');
604
- expect(run.stdout).toBe('');
605
- });
606
-
607
- it('forwards a failing target\u0027s exit code and never execs', async () => {
608
- const run = await runBin(workspace, ['app:broken', '--', './report']);
609
- expect(run.code).toBe(1);
610
- expect(run.stdout).not.toContain(MARKER);
611
- });
612
-
613
- it('falls back to the workspace nx CLI when the daemon is disabled', async () => {
614
- const run = await runBin(workspace, ['app:build', '--', './report'], {
615
- NX_DAEMON: 'false',
616
- NX_VERBOSE_LOGGING: 'true',
783
+ describe('smoo-nx-exec with a fresh daemon', () => {
784
+ /**
785
+ * The socket directory a call entered from another workspace's shell is given for `workspace`, or null where the
786
+ * packaged socket owner has no managed shell runtime to bind in (`DEVENV_RUNTIME` unset), and Nx keeps its own
787
+ * defaults. Found by running that same packaged script in the workspace, as the call does, with none of the
788
+ * caller's Nx state: neither the directory nor how it is named is restated here.
789
+ */
790
+ const providerSocketDirectory = (workspace: string): string | null => {
791
+ const runtime = process.env.DEVENV_RUNTIME;
792
+ if (runtime === undefined || runtime === '') return null;
793
+ expect(isAbsolute(runtime), `DEVENV_RUNTIME=${runtime} must name the managed shell runtime directory`).toBe(true);
794
+ const script = join(managedAssetsRoot, 'raw/tooling/direnv/nx-socket-dir.sh');
795
+ const owner = spawnSync('/bin/sh', ['-c', '. "$1" && printf %s "$NX_SOCKET_DIR"', 'sh', script], {
796
+ cwd: workspace,
797
+ env: { ...childEnvironment({}), PWD: workspace },
798
+ encoding: 'utf8',
617
799
  });
618
- expect(run.code).toBe(0);
619
- expect(run.stderr).toContain('daemon is disabled');
620
- expect(run.stdout.split('\n')[0], run.stdout).toBe(MARKER);
621
- });
800
+ expect(owner.status, `${script} in ${workspace}\n${owner.error?.message ?? ''}${owner.stderr}`).toBe(0);
801
+ expect(isAbsolute(owner.stdout), `${script} named ${JSON.stringify(owner.stdout)}`).toBe(true);
802
+ return owner.stdout;
803
+ };
622
804
 
623
- it('prints the message from a plain-object Nx rejection', async () => {
624
- const rejectingWorkspace = await realpath(await mkdtemp(join(tmpdir(), 'ensure-built-rejection-')));
805
+ // These integration controls run real Nx because their subject is the daemon:
806
+ // the daemon a probe starts holds no output records, so every output must be
807
+ // vouched for by comparing the working tree with Nx's cache artifact. The
808
+ // daemon it starts is also the one whose socket is in question, so the same
809
+ // lifetime answers where a root entered from another workspace's shell binds.
810
+ it('reuses authoritative graphs without assuming an unstable generation republishes its witness', async () => {
811
+ await withNxFixture(
812
+ 'ensure-built-graph-witness-',
813
+ async ({ root, workspace, socketDirectory }) => {
814
+ const builds = join(root, 'lib-builds.log');
815
+ await writeTwoProjectWorkspace(workspace, builds);
816
+ const built = await run(
817
+ 'node',
818
+ nxEntry,
819
+ workspace,
820
+ ['run-many', '-t', 'build', '-p', 'app', '--outputStyle=static-failures-only'],
821
+ { NX_DAEMON: 'false', NX_WORKSPACE_ROOT_PATH: workspace },
822
+ );
823
+ expect(built.code, built.stdout + built.stderr).toBe(0);
824
+ const reuseEntry = join(root, 'graph-reuse.ts');
825
+ const resultsPath = join(root, 'graph-checks.json');
826
+ await writeFile(
827
+ reuseEntry,
828
+ `
829
+ import assert from 'node:assert/strict';
830
+ import { existsSync } from 'node:fs';
831
+ import { createRequire } from 'node:module';
832
+ import { chmod, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
833
+ import { join } from 'node:path';
834
+ import { ensureBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
835
+ const requireNx = createRequire(process.cwd() + '/package.json');
836
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
837
+ const { workspaceDataDirectoryForWorkspace } = requireNx('nx/src/utils/cache-directory');
838
+ const witness = join(workspaceDataDirectoryForWorkspace(process.cwd()), 'ensure-built-graph.json');
839
+ const savedWitness = ${JSON.stringify(join(root, 'authoritative-graph.json'))};
840
+ const source = join(process.cwd(), 'packages/lib/source.txt');
841
+ const text = await readFile(source, 'utf8');
842
+ const request = daemonClient.getProjectGraphAndSourceMaps.bind(daemonClient);
843
+ let requests = 0;
844
+ let invalidateGeneration = false;
845
+ daemonClient.getProjectGraphAndSourceMaps = async () => {
846
+ requests += 1;
847
+ const response = await request();
848
+ if (invalidateGeneration) {
849
+ invalidateGeneration = false;
850
+ await writeFile(source, 'transient graph input');
851
+ await writeFile(source, text);
852
+ }
853
+ return response;
854
+ };
855
+ const results = [];
856
+ async function check(label) {
857
+ const before = requests;
858
+ const result = await ensureBuilt({ target: 'app:build', cwd: process.cwd() });
859
+ results.push({ label, requests: requests - before, disposition: result.disposition, witnessExists: existsSync(witness) });
860
+ }
861
+ await check('establish');
862
+ await check('reuse');
863
+ const added = join(process.cwd(), 'new-graph-input.txt');
864
+ await writeFile(added, 'new');
865
+ await check('created');
866
+ await rm(added);
867
+ await check('deleted');
868
+ const project = join(process.cwd(), 'packages/app/project.json');
869
+ const original = await readFile(project, 'utf8');
870
+ const config = JSON.parse(original);
871
+ config.implicitDependencies = [];
872
+ await writeFile(project, JSON.stringify(config));
873
+ await check('dependency');
874
+ await writeFile(project, original);
875
+ await check('dependency-restored');
876
+ // Save only evidence the real daemon generation actually authorized, outside
877
+ // the workspace: the later missing-witness RPC is not obliged to replace it.
878
+ const authoritativeWitness = await readFile(witness, 'utf8');
879
+ const witnessMode = (await stat(witness)).mode & 0o7777;
880
+ await rename(witness, savedWitness);
881
+ // Equal pre/post bytes do not authorize publication after a write/revert.
882
+ // Count and return the actual RPC response, including the required successor.
883
+ invalidateGeneration = true;
884
+ await check('missing-witness');
885
+ assert.equal(invalidateGeneration, false);
886
+ assert.equal(existsSync(witness), false);
887
+ // Restore that same genuine witness, not synthesized evidence or a retry of
888
+ // the unstable generation, so the unreadable control always runs.
889
+ await rename(savedWitness, witness);
890
+ assert.equal(await readFile(witness, 'utf8'), authoritativeWitness);
891
+ await chmod(witness, 0);
892
+ try {
893
+ await assert.rejects(readFile(witness), { code: 'EACCES' });
894
+ await check('unreadable-witness');
895
+ } finally {
896
+ await chmod(witness, witnessMode);
897
+ }
898
+ await writeFile(${JSON.stringify(resultsPath)}, JSON.stringify(results));
899
+ `,
900
+ );
901
+ const reused = await run('bun', reuseEntry, workspace, [], {
902
+ NX_DAEMON: 'true',
903
+ NX_USE_LOCAL: 'true',
904
+ NX_WORKSPACE_ROOT_PATH: workspace,
905
+ NX_SOCKET_DIR: socketDirectory,
906
+ });
907
+ expect(reused.code, reused.stdout + reused.stderr).toBe(0);
908
+ // A changed dependency configuration may legitimately run app:build;
909
+ // its streamed logs are not the graph-observation protocol.
910
+ const graphChecks = typia.json.assertParse<
911
+ { label: string; requests: number; disposition: string; witnessExists: boolean }[]
912
+ >(await readFile(resultsPath, 'utf8'));
913
+ expect(graphChecks.find(({ label }) => label === 'reuse')).toEqual({
914
+ label: 'reuse',
915
+ requests: 0,
916
+ disposition: 'hit',
917
+ witnessExists: true,
918
+ });
919
+ for (const label of ['created', 'deleted', 'dependency', 'dependency-restored', 'unreadable-witness']) {
920
+ expect(graphChecks.find((check) => check.label === label)?.requests, label).toBeGreaterThan(0);
921
+ }
922
+ expect(graphChecks.find(({ label }) => label === 'missing-witness')).toEqual({
923
+ label: 'missing-witness',
924
+ requests: 2,
925
+ disposition: 'hit',
926
+ witnessExists: false,
927
+ });
928
+ expect(graphChecks.find(({ label }) => label === 'unreadable-witness')?.disposition).toBe('hit');
929
+ expect(await readFile(builds, 'utf8')).toBe('lib\n');
930
+ expect(await readFile(join(workspace, 'packages/app/dist/marker.txt'), 'utf8')).toBe('built\nlib\n');
931
+ },
932
+ 'workspace',
933
+ );
934
+ }, 60_000);
935
+
936
+ it('replays current outputs and refreshes stale snapshots without running unrelated edits', async () => {
937
+ // A socket path has a 95 character budget and macOS's temp directory spends most of it, so the
938
+ // socket directory is made in the short socket namespace the sandbox admits.
939
+ const socketDir = await ownedSocketDirectory('eb-sock-', NX_LONGEST_SOCKET_NAME);
940
+ let root = '';
941
+ let failure: { readonly error: unknown } | null = null;
942
+ const providerDirectories: string[] = [];
625
943
  try {
626
- await mkdir(join(rejectingWorkspace, 'node_modules', 'nx', 'src', 'daemon', 'client'), { recursive: true });
627
- await mkdir(join(rejectingWorkspace, 'node_modules', 'nx', 'src', 'utils'), { recursive: true });
628
- await writeFile(join(rejectingWorkspace, 'package.json'), '{}');
629
- await writeFile(join(rejectingWorkspace, 'nx.json'), '{}');
630
- await writeFile(
631
- join(rejectingWorkspace, 'node_modules', 'nx', 'package.json'),
632
- JSON.stringify({ name: 'nx', type: 'commonjs' }),
633
- );
634
- await writeFile(
635
- join(rejectingWorkspace, 'node_modules', 'nx', 'src', 'utils', 'workspace-root.js'),
636
- 'exports.workspaceRoot = process.env.NX_WORKSPACE_ROOT_PATH;\n',
637
- );
638
- await writeFile(
639
- join(rejectingWorkspace, 'node_modules', 'nx', 'src', 'daemon', 'client', 'client.js'),
640
- [
641
- 'exports.daemonClient = {',
642
- ' enabled() {',
643
- " throw { stack: 'synthetic stack', message: 'daemon belongs to a different workspace' };",
644
- ' },',
645
- '};',
646
- '',
647
- ].join('\n'),
944
+ await withNxFixture(
945
+ 'ensure-built-daemon-',
946
+ async (fixture) => {
947
+ root = fixture.root;
948
+ const { workspace } = fixture;
949
+ const builds = join(root, 'lib-builds.log');
950
+ await writeTwoProjectWorkspace(workspace, builds);
951
+ // What the provider binds for this workspace when the call is entered from another one's shell.
952
+ const providerSockets = providerSocketDirectory(workspace);
953
+ if (providerSockets !== null) providerDirectories.push(providerSockets);
954
+ const ownEnv: Record<string, string> = providerSockets === null ? {} : { NX_SOCKET_DIR: providerSockets };
955
+
956
+ // Built by daemonless Nx, as CI or a restarted daemon leaves a tree:
957
+ // cached and on disk, recorded by no daemon.
958
+ const built = await run(
959
+ 'node',
960
+ nxEntry,
961
+ workspace,
962
+ ['run-many', '-t', 'build', '-p', 'app', '--outputStyle=static-failures-only'],
963
+ { NX_DAEMON: 'false', NX_WORKSPACE_ROOT_PATH: workspace },
964
+ );
965
+ expect(built.code, built.stdout + built.stderr).toBe(0);
966
+ expect(await readFile(builds, 'utf-8')).toBe('lib\n');
967
+
968
+ // Entered from outside the root by a shell set up for another
969
+ // workspace, as a managed devenv's is: its socket directory belongs to
970
+ // that workspace's daemon, and a second daemon listening there would
971
+ // take the socket from it.
972
+ const caller = join(root, 'caller');
973
+ await mkdir(caller);
974
+ const hit = await run(
975
+ 'bun',
976
+ binEntry,
977
+ caller,
978
+ ['app:build', '--workspace-root', workspace, '--', join(workspace, 'report')],
979
+ { NX_DAEMON: 'true', NX_USE_LOCAL: 'true', NX_SOCKET_DIR: socketDir },
980
+ );
981
+ expect(hit.code, hit.stdout + hit.stderr).toBe(0);
982
+ expect(hit.stderr).toBe('');
983
+ expect(hit.stdout.split('\n')[0], hit.stdout).toBe(MARKER);
984
+ expect(await readFile(builds, 'utf-8')).toBe('lib\n');
985
+ expect(await readdir(socketDir)).toEqual([]);
986
+ const record = await readFile(join(workspace, '.nx', 'workspace-data', 'd', 'server-process.json'), 'utf-8');
987
+ expect(record).not.toContain(socketDir);
988
+ // The daemon it started binds in the directory the provider named, not the caller's nor Nx's default.
989
+ const daemon = typia.json.assertParse<DaemonProcessJson>(record);
990
+ if (providerSockets !== null) {
991
+ expect(daemon.socketPath.startsWith(`${providerSockets}/`), record).toBe(true);
992
+ }
993
+
994
+ // That hit re-armed the daemon's records. The emitted wrapper, under
995
+ // Node and with nothing to exec, is as silent.
996
+ const again = await run('node', builtBinEntry, workspace, ['app:build'], {
997
+ NX_DAEMON: 'true',
998
+ NX_USE_LOCAL: 'true',
999
+ ...ownEnv,
1000
+ });
1001
+ expect(again).toEqual({ code: 0, signal: null, stdout: '', stderr: '' });
1002
+ expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1003
+
1004
+ // Probe-only receipts use the real Nx keys/cache and independently
1005
+ // census public output bytes without starting a task runner.
1006
+ const committed = spawnSync(
1007
+ 'git',
1008
+ [
1009
+ '-C',
1010
+ workspace,
1011
+ 'add',
1012
+ '.gitignore',
1013
+ 'report',
1014
+ 'nx.json',
1015
+ 'packages/app/project.json',
1016
+ 'packages/app/source.txt',
1017
+ 'packages/lib/project.json',
1018
+ 'packages/lib/source.txt',
1019
+ ],
1020
+ { encoding: 'utf8' },
1021
+ );
1022
+ expect(committed.status, committed.stdout + committed.stderr).toBe(0);
1023
+ const sourceCommit = spawnSync(
1024
+ 'git',
1025
+ [
1026
+ '-C',
1027
+ workspace,
1028
+ '-c',
1029
+ 'user.name=EnsureBuilt fixture',
1030
+ '-c',
1031
+ 'user.email=fixture@example.invalid',
1032
+ 'commit',
1033
+ '-qm',
1034
+ 'source fixture',
1035
+ ],
1036
+ { encoding: 'utf8' },
1037
+ );
1038
+ expect(sourceCommit.status, sourceCommit.stdout + sourceCommit.stderr).toBe(0);
1039
+ const probeEntry = join(root, 'probe-receipt.ts');
1040
+ await writeFile(
1041
+ probeEntry,
1042
+ `
1043
+ import { readFile, stat, writeFile } from 'node:fs/promises';
1044
+ import { join } from 'node:path';
1045
+ import { probeBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1046
+ const output = join(process.cwd(), 'packages/app/dist/marker.txt');
1047
+ const source = join(process.cwd(), 'packages/lib/source.txt');
1048
+ const originalOutput = await readFile(output, 'utf8');
1049
+ const originalSource = await readFile(source, 'utf8');
1050
+ const before = await stat(output, { bigint: true });
1051
+ const hit = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1052
+ const after = await stat(output, { bigint: true });
1053
+ process.env.NX_DAEMON = 'false';
1054
+ const daemonless = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1055
+ process.env.NX_DAEMON = 'true';
1056
+ await writeFile(output, 'tampered');
1057
+ const stale = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1058
+ await writeFile(output, originalOutput);
1059
+ await writeFile(source, 'new uncached source');
1060
+ const uncached = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1061
+ const outputAfterMiss = await readFile(output, 'utf8');
1062
+ await writeFile(source, originalSource);
1063
+ console.log(JSON.stringify({ hit, daemonless, stale, uncached, outputUnwritten: before.ino === after.ino && before.mtimeNs === after.mtimeNs && before.ctimeNs === after.ctimeNs, outputAfterMiss }));
1064
+ `,
1065
+ );
1066
+ const probed = await run('bun', probeEntry, workspace, [], {
1067
+ NX_DAEMON: 'true',
1068
+ NX_USE_LOCAL: 'true',
1069
+ NX_WORKSPACE_ROOT_PATH: workspace,
1070
+ ...ownEnv,
1071
+ });
1072
+ expect(probed.code, probed.stdout + probed.stderr).toBe(0);
1073
+ const receipts = typia.json.assertParse<{
1074
+ hit: import('./ensure-built.js').EnsureBuiltProbeResult;
1075
+ daemonless: import('./ensure-built.js').EnsureBuiltProbeResult;
1076
+ stale: import('./ensure-built.js').EnsureBuiltProbeResult;
1077
+ uncached: import('./ensure-built.js').EnsureBuiltProbeResult;
1078
+ outputUnwritten: boolean;
1079
+ outputAfterMiss: string;
1080
+ }>(probed.stdout);
1081
+ expect(receipts.hit.disposition, probed.stderr).toBe('hit');
1082
+ if (receipts.hit.disposition === 'hit') {
1083
+ expect(receipts.hit.receipt.tasks.map(({ id }) => id).sort()).toEqual(['app:build', 'lib:build']);
1084
+ expect(
1085
+ receipts.hit.receipt.tasks
1086
+ .flatMap(({ outputs }) => outputs)
1087
+ .find(({ path }) => path === 'packages/app/dist/marker.txt'),
1088
+ ).toMatchObject({ type: 'file', sha256: expect.stringMatching(/^[a-f0-9]{64}$/) });
1089
+ }
1090
+ expect(receipts.daemonless).toEqual({
1091
+ disposition: 'miss',
1092
+ reason: { kind: 'no-daemon', taskId: 'app:build' },
1093
+ });
1094
+ expect(receipts.stale).toEqual({
1095
+ disposition: 'miss',
1096
+ reason: { kind: 'stale-outputs', taskId: 'app:build' },
1097
+ });
1098
+ expect(receipts.uncached.disposition).toBe('miss');
1099
+ expect(receipts.outputUnwritten).toBe(true);
1100
+ expect(receipts.outputAfterMiss).toBe('built\nlib\n');
1101
+ expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1102
+
1103
+ const sourceRaceEntry = join(root, 'receipt-source-race.ts');
1104
+ await writeFile(
1105
+ sourceRaceEntry,
1106
+ `
1107
+ import { createRequire } from 'node:module';
1108
+ import { readFile, writeFile } from 'node:fs/promises';
1109
+ import { join } from 'node:path';
1110
+ import { probeBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1111
+ const source = join(process.cwd(), 'packages/lib/source.txt');
1112
+ const text = await readFile(source, 'utf8');
1113
+ const { daemonClient } = createRequire(process.cwd() + '/package.json')('nx/src/daemon/client/client');
1114
+ const hash = daemonClient.hashTasks.bind(daemonClient);
1115
+ daemonClient.hashTasks = async (...args) => {
1116
+ const result = await hash(...args);
1117
+ await writeFile(source, 'transient source');
1118
+ await writeFile(source, text);
1119
+ return result;
1120
+ };
1121
+ console.log(JSON.stringify(await probeBuilt({ target: 'app:build', cwd: process.cwd() })));
1122
+ `,
1123
+ );
1124
+ const sourceRace = await run('bun', sourceRaceEntry, workspace, [], {
1125
+ NX_DAEMON: 'true',
1126
+ NX_USE_LOCAL: 'true',
1127
+ NX_WORKSPACE_ROOT_PATH: workspace,
1128
+ ...ownEnv,
1129
+ });
1130
+ expect(sourceRace.code, sourceRace.stdout + sourceRace.stderr).toBe(0);
1131
+ const sourceRaceResult = typia.json.assertParse<import('./ensure-built.js').EnsureBuiltProbeResult>(
1132
+ sourceRace.stdout,
1133
+ );
1134
+ expect(sourceRaceResult).toMatchObject({
1135
+ disposition: 'failed',
1136
+ reason: { kind: 'provider-proof', detail: expect.stringContaining('across Nx hashing') },
1137
+ });
1138
+ expect(sourceRace.stderr).toContain('Provider source');
1139
+ expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1140
+
1141
+ // An awaited daemon graph can see B while both disk snapshots see
1142
+ // A. Node stamps revoke that generation; the fresh daemon file table
1143
+ // supplies the A reconciliation instead of an empty A-to-A diff.
1144
+ const generationRaceEntry = join(root, 'graph-generation-race.ts');
1145
+ await writeFile(
1146
+ generationRaceEntry,
1147
+ `
1148
+ import { createRequire } from 'node:module';
1149
+ import { readFile, rm, writeFile } from 'node:fs/promises';
1150
+ import { join } from 'node:path';
1151
+ import { ensureBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1152
+ const source = join(process.cwd(), 'packages/lib/source.txt');
1153
+ const text = await readFile(source, 'utf8');
1154
+ await ensureBuilt({ target: 'app:build', cwd: process.cwd() });
1155
+ const requireNx = createRequire(process.cwd() + '/package.json');
1156
+ const { workspaceDataDirectoryForWorkspace } = requireNx('nx/src/utils/cache-directory');
1157
+ await rm(join(workspaceDataDirectoryForWorkspace(process.cwd()), 'ensure-built-graph.json'), { force: true });
1158
+ const { daemonClient } = createRequire(process.cwd() + '/package.json')('nx/src/daemon/client/client');
1159
+ const request = daemonClient.getProjectGraphAndSourceMaps.bind(daemonClient);
1160
+ let requests = 0;
1161
+ daemonClient.getProjectGraphAndSourceMaps = async () => {
1162
+ requests += 1;
1163
+ const result = await request();
1164
+ if (requests !== 1) return result;
1165
+ await writeFile(source, 'transient graph input');
1166
+ await daemonClient.updateWorkspaceContext([], ['packages/lib/source.txt'], []);
1167
+ const next = await request();
1168
+ await writeFile(source, text);
1169
+ return next;
1170
+ };
1171
+ const result = await ensureBuilt({ target: 'app:build', cwd: process.cwd() });
1172
+ console.log(JSON.stringify({ result, requests }));
1173
+ `,
1174
+ );
1175
+ const generationRace = await run('bun', generationRaceEntry, workspace, [], {
1176
+ NX_DAEMON: 'true',
1177
+ NX_USE_LOCAL: 'true',
1178
+ NX_WORKSPACE_ROOT_PATH: workspace,
1179
+ ...ownEnv,
1180
+ });
1181
+ expect(generationRace.code, generationRace.stdout + generationRace.stderr).toBe(0);
1182
+ const generations = typia.json.assertParse<{
1183
+ result: import('./ensure-built.js').EnsureBuiltResult;
1184
+ requests: number;
1185
+ }>(generationRace.stdout);
1186
+ expect(generations.result).toEqual({ disposition: 'hit' });
1187
+ expect(generations.requests).toBeGreaterThanOrEqual(2);
1188
+ expect(generationRace.stderr).toBe('');
1189
+ expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1190
+ // Coordinate a real write after the real daemon returned its file
1191
+ // table. The response is not substituted: this makes the
1192
+ // graph→snapshot race deterministic without relying on FSEvents.
1193
+ const raceEntry = join(root, 'freshness-race.ts');
1194
+ await writeFile(
1195
+ raceEntry,
1196
+ `
1197
+ import { createRequire } from 'node:module';
1198
+ import { writeFile } from 'node:fs/promises';
1199
+ import { ensureBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1200
+ const { daemonClient } = createRequire(process.cwd() + '/package.json')('nx/src/daemon/client/client');
1201
+ const readFiles = daemonClient.getWorkspaceContextFileData.bind(daemonClient);
1202
+ daemonClient.getWorkspaceContextFileData = async () => {
1203
+ const files = await readFiles();
1204
+ await writeFile(process.argv[2], process.argv[3]);
1205
+ return files;
1206
+ };
1207
+ console.log(JSON.stringify(await ensureBuilt({ target: 'app:build', cwd: process.cwd() })));
1208
+ `,
1209
+ );
1210
+ const refreshed = await run(
1211
+ 'bun',
1212
+ raceEntry,
1213
+ workspace,
1214
+ [join(workspace, 'README.md'), 'an unrelated edit\n'],
1215
+ { NX_DAEMON: 'true', NX_USE_LOCAL: 'true', NX_WORKSPACE_ROOT_PATH: workspace, ...ownEnv },
1216
+ );
1217
+ expect(refreshed.code, refreshed.stdout + refreshed.stderr).toBe(0);
1218
+ expect(refreshed.stdout.trim()).toBe(JSON.stringify({ disposition: 'hit' }));
1219
+ expect(refreshed.stderr).toBe('');
1220
+ expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1221
+
1222
+ // STRICT-BY: the same boundary moving an actual declared input must
1223
+ // miss, run its producer, and rebuild the dependent artifact.
1224
+ const changed = await run(
1225
+ 'bun',
1226
+ raceEntry,
1227
+ workspace,
1228
+ [join(workspace, 'packages', 'lib', 'source.txt'), 'changed\n'],
1229
+ { NX_DAEMON: 'true', NX_USE_LOCAL: 'true', NX_WORKSPACE_ROOT_PATH: workspace, ...ownEnv },
1230
+ );
1231
+ expect(changed.code, changed.stdout + changed.stderr).toBe(0);
1232
+ expect(changed.stdout).toContain('"disposition":"built"');
1233
+ expect(await readFile(builds, 'utf-8')).toBe('lib\nchanged\n');
1234
+ expect(await readFile(join(workspace, 'packages', 'app', 'dist', 'marker.txt'), 'utf-8')).toBe(
1235
+ 'built\nchanged\n',
1236
+ );
1237
+ },
1238
+ 'workspace',
648
1239
  );
649
-
650
- const run = await runBin(rejectingWorkspace, ['app:build', '--', './never-runs']);
651
- expect(run.code).toBe(1);
652
- expect(run.stderr).toContain('daemon belongs to a different workspace');
653
- expect(run.stderr).not.toContain('[object Object]');
654
- } finally {
655
- await rm(rejectingWorkspace, { recursive: true, force: true });
1240
+ } catch (error) {
1241
+ failure = { error };
656
1242
  }
657
- });
658
-
659
- it('rejects a malformed invocation with a usage error', async () => {
660
- const emptyCommand = await runBin(workspace, ['app:build', '--']);
661
- expect(emptyCommand.code).toBe(2);
662
- expect(emptyCommand.stderr).toContain('no binary given');
663
-
664
- const badTarget = await runBin(workspace, ['build', '--', './report']);
665
- expect(badTarget.code).toBe(2);
666
- expect(badTarget.stderr).toContain('not a project:target');
667
-
668
- const pathLookup = await runBin(workspace, ['app:build', '--', 'report']);
669
- expect(pathLookup.code).toBe(2);
670
- expect(pathLookup.stderr).toContain('not a name to look up on PATH');
671
- });
672
- });
673
-
674
- describe('smoo-nx-exec signal forwarding', () => {
675
- let workspace = '';
676
-
677
- // A workspace whose `nx` is a script that kills itself. The daemon-disabled
678
- // path spawns exactly that binary, so this is the whole signal path end to
679
- // end — and deterministic, unlike racing a real build with a kill.
680
- beforeAll(async () => {
681
- workspace = await realpath(await mkdtemp(join(tmpdir(), 'ensure-built-signal-')));
682
- await mkdir(join(workspace, 'node_modules', '.bin'), { recursive: true });
683
- await writeFile(join(workspace, 'nx.json'), '{}');
684
- const fakeNx = join(workspace, 'node_modules', '.bin', 'nx');
685
- await writeFile(fakeNx, '#!/bin/sh\nkill -TERM $$\n');
686
- await chmod(fakeNx, 0o755);
687
- await writeFile(join(workspace, 'report'), `#!/bin/sh\necho ${MARKER}\n`);
688
- await chmod(join(workspace, 'report'), 0o755);
689
- });
690
-
691
- afterAll(async () => {
692
- if (workspace) {
693
- await rm(workspace, { recursive: true, force: true });
1243
+ // Only the directories this test made: the caller's, and the one the provider bound for this workspace.
1244
+ for (const directory of [socketDir, ...providerDirectories]) {
1245
+ await rm(directory, { recursive: true, force: true });
694
1246
  }
695
- });
696
-
697
- it('re-raises the signal that killed nx instead of flattening it to a code', async () => {
698
- const run = await runBin(workspace, ['app:build', '--', './report'], { NX_DAEMON: 'false' });
699
- expect(run.signal).toBe('SIGTERM');
700
- expect(run.stdout).not.toContain(MARKER);
701
- });
1247
+ // The fixture retires on every exit path of its body, a throwing one
1248
+ // included: once it has, nothing works in its root.
1249
+ const leftovers = root === '' ? [] : await pidsWorkingIn(root);
1250
+ if (failure === null) {
1251
+ expect(leftovers).toEqual([]);
1252
+ } else if (leftovers.length === 0) {
1253
+ throw failure.error;
1254
+ } else {
1255
+ // A cause, not an AggregateError: the test harness prints an aggregate's
1256
+ // inner errors without its message.
1257
+ throw new Error(`processes ${leftovers.join(', ')} still work in ${root} after its body failed`, {
1258
+ cause: failure.error,
1259
+ });
1260
+ }
1261
+ }, 60_000);
702
1262
  });