@smoothbricks/nx-plugin 0.4.28 → 0.4.30

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 (158) hide show
  1. package/README.md +277 -89
  2. package/dist/bin/smoo-nx-test-clocks.d.ts +3 -0
  3. package/dist/bin/smoo-nx-test-clocks.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-test-clocks.js +28 -0
  5. package/dist/bounded-test-policy.d.ts +8 -8
  6. package/dist/bounded-test-policy.d.ts.map +1 -1
  7. package/dist/bounded-test-policy.js +18 -30
  8. package/dist/cargo-closure-input.d.ts +23 -0
  9. package/dist/cargo-closure-input.d.ts.map +1 -1
  10. package/dist/cargo-closure-input.js +41 -9
  11. package/dist/cargo-source-hash.d.ts.map +1 -1
  12. package/dist/cargo-source-hash.js +42 -19
  13. package/dist/ensure-built-receipt.d.ts +40 -6
  14. package/dist/ensure-built-receipt.d.ts.map +1 -1
  15. package/dist/ensure-built-receipt.js +297 -159
  16. package/dist/ensure-built-witness.d.ts +65 -4
  17. package/dist/ensure-built-witness.d.ts.map +1 -1
  18. package/dist/ensure-built-witness.js +2237 -23
  19. package/dist/ensure-built.d.ts +99 -1
  20. package/dist/ensure-built.d.ts.map +1 -1
  21. package/dist/ensure-built.js +45 -56
  22. package/dist/executors/bounded-exec/cpu-pool.d.ts +22 -7
  23. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  24. package/dist/executors/bounded-exec/cpu-pool.js +51 -22
  25. package/dist/executors/bounded-exec/executor.d.ts +12 -3
  26. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  27. package/dist/executors/bounded-exec/executor.js +174 -51
  28. package/dist/executors/bounded-exec/no-space.d.ts +8 -0
  29. package/dist/executors/bounded-exec/no-space.d.ts.map +1 -0
  30. package/dist/executors/bounded-exec/no-space.js +31 -0
  31. package/dist/executors/bounded-exec/ram-temp.d.ts +20 -11
  32. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  33. package/dist/executors/bounded-exec/ram-temp.js +42 -17
  34. package/dist/executors/bounded-exec/verdict.d.ts +34 -4
  35. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
  36. package/dist/executors/bounded-exec/verdict.js +54 -3
  37. package/dist/generators/bun-test-tracing/generator.js +2 -2
  38. package/dist/graph-input-contract.d.ts +102 -0
  39. package/dist/graph-input-contract.d.ts.map +1 -0
  40. package/dist/graph-input-contract.js +637 -0
  41. package/dist/index.d.ts +12 -5
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +17 -3
  44. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  45. package/dist/managed-files/ci-workflow.js +5 -2
  46. package/dist/managed-files/publish-workflow.d.ts +11 -1
  47. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  48. package/dist/owned-installation.d.ts +14 -0
  49. package/dist/owned-installation.d.ts.map +1 -0
  50. package/dist/owned-installation.js +324 -0
  51. package/dist/producer-receipts.d.ts +19 -0
  52. package/dist/producer-receipts.d.ts.map +1 -0
  53. package/dist/producer-receipts.js +926 -0
  54. package/dist/test-backstop.d.ts +9 -0
  55. package/dist/test-backstop.d.ts.map +1 -0
  56. package/dist/test-backstop.js +10 -0
  57. package/dist/test-clock-policy.d.ts +30 -0
  58. package/dist/test-clock-policy.d.ts.map +1 -0
  59. package/dist/test-clock-policy.js +686 -0
  60. package/dist/testing.d.ts +8 -0
  61. package/dist/testing.d.ts.map +1 -1
  62. package/dist/testing.js +66 -1
  63. package/managed/raw/patches/nx@23.2.1.patch +328 -50
  64. package/managed/raw/tooling/direnv/developer-links.ts +148 -29
  65. package/managed/raw/tooling/direnv/devenv.smoo.nix +7 -7
  66. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +14 -5
  67. package/managed/raw/tooling/direnv/linked-snapshots.ts +206 -40
  68. package/managed/raw/tooling/direnv/repo-path +15 -2
  69. package/managed/raw/tooling/direnv/setup-environment.ts +179 -115
  70. package/managed/templates/github/actions/cache-node-modules/action.yml +9 -0
  71. package/managed/templates/github/actions/setup-devenv/action.yml +63 -7
  72. package/nextest.toml +1 -1
  73. package/package.json +25 -9
  74. package/src/__tests__/cargo-closure-fixture.ts +113 -0
  75. package/src/__tests__/counted-cargo.ts +8 -25
  76. package/src/__tests__/directory-change.ts +27 -0
  77. package/src/__tests__/fixture-nx-env.ts +7 -0
  78. package/src/__tests__/owned-installation.ts +14 -0
  79. package/src/__tests__/past-tick.ts +12 -0
  80. package/src/bin/smoo-nx-bound-failures.test.ts +1 -1
  81. package/src/bin/smoo-nx-test-clocks.ts +29 -0
  82. package/src/bounded-test-policy.test.ts +36 -22
  83. package/src/bounded-test-policy.ts +18 -32
  84. package/src/bun-bootstrap.test.ts +1 -1
  85. package/src/cargo-closure-input.property.test.ts +50 -0
  86. package/src/cargo-closure-input.test.ts +73 -121
  87. package/src/cargo-closure-input.ts +47 -8
  88. package/src/cargo-closure-key.test.ts +239 -0
  89. package/src/cargo-resolve-cache.test.ts +168 -31
  90. package/src/cargo-source-hash.test.ts +78 -3
  91. package/src/cargo-source-hash.ts +48 -30
  92. package/src/cross-check-policy.test.ts +2 -2
  93. package/src/ensure-built-receipt.test.ts +111 -16
  94. package/src/ensure-built-receipt.ts +294 -149
  95. package/src/ensure-built-witness.test.ts +306 -13
  96. package/src/ensure-built-witness.ts +255 -24
  97. package/src/ensure-built.test.ts +228 -102
  98. package/src/ensure-built.ts +127 -66
  99. package/src/executors/bounded-exec/cpu-pool.test.ts +134 -32
  100. package/src/executors/bounded-exec/cpu-pool.ts +64 -20
  101. package/src/executors/bounded-exec/cpu-tokens.test.ts +2 -2
  102. package/src/executors/bounded-exec/disk-lease.test.ts +47 -13
  103. package/src/executors/bounded-exec/executor-host.test.ts +74 -52
  104. package/src/executors/bounded-exec/executor.test.ts +343 -97
  105. package/src/executors/bounded-exec/executor.ts +192 -56
  106. package/src/executors/bounded-exec/hang-diagnostics.test.ts +14 -8
  107. package/src/executors/bounded-exec/no-space.ts +40 -0
  108. package/src/executors/bounded-exec/progress.test.ts +1 -1
  109. package/src/executors/bounded-exec/ram-temp-host.test.ts +51 -21
  110. package/src/executors/bounded-exec/ram-temp.test.ts +92 -16
  111. package/src/executors/bounded-exec/ram-temp.ts +49 -20
  112. package/src/executors/bounded-exec/verdict.test.ts +127 -22
  113. package/src/executors/bounded-exec/verdict.ts +78 -3
  114. package/src/generators/bounded-test-targets/generator.test.ts +1 -3
  115. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  116. package/src/generators/bun-test-tracing/generator.ts +2 -2
  117. package/src/graph-input-contract.test.ts +379 -0
  118. package/src/graph-input-contract.ts +627 -0
  119. package/src/index.test.ts +3 -3
  120. package/src/index.ts +24 -3
  121. package/src/linked-snapshots.nx.test.ts +112 -30
  122. package/src/managed-files/ci-workflow.ts +5 -2
  123. package/src/managed-files/publish-workflow.ts +12 -1
  124. package/src/managed-files/repo-path.test.ts +44 -1
  125. package/src/managed-files/setup-devenv-free-disk.test.ts +95 -0
  126. package/src/nextest-code-bound.test.ts +23 -17
  127. package/src/nextest-extraction.test.ts +114 -4
  128. package/src/nextest-partitions.test.ts +7 -1
  129. package/src/nx-cache-restore-mtime.test.ts +2 -2
  130. package/src/nx-daemon-claim.test.ts +10 -8
  131. package/src/nx-daemon-idle-cpu.test.ts +0 -1
  132. package/src/nx-daemon-idle-policy.test.ts +61 -1
  133. package/src/nx-daemon-ignore-files.test.ts +2 -2
  134. package/src/nx-daemon-validity.test.ts +36 -22
  135. package/src/nx-dot-input-policy.test.ts +5 -5
  136. package/src/nx-files-archive-racy.test.ts +1 -1
  137. package/src/nx-incomplete-run-summary.test.ts +1 -1
  138. package/src/nx-plugin-load-errors.test.ts +2 -2
  139. package/src/nx-project-graph-errors.test.ts +70 -0
  140. package/src/nx-skipped-task-exit.test.ts +2 -2
  141. package/src/nx-store-resolution.test.ts +7 -25
  142. package/src/nx-task-output-lease.test.ts +3 -3
  143. package/src/nx-use-local.test.ts +7 -5
  144. package/src/owned-installation.ts +174 -0
  145. package/src/producer-receipts.test.ts +164 -0
  146. package/src/producer-receipts.ts +636 -0
  147. package/src/runtime-input.test.ts +1 -1
  148. package/src/serial-group-wiring.test.ts +4 -4
  149. package/src/task-results.test.ts +18 -16
  150. package/src/test-backstop.ts +11 -0
  151. package/src/test-clock-policy.test.ts +338 -0
  152. package/src/test-clock-policy.ts +708 -0
  153. package/src/test-timings.test.ts +2 -2
  154. package/src/testing.test.ts +5 -5
  155. package/src/testing.ts +67 -1
  156. package/src/typecheck-test-policy.test.ts +1 -1
  157. package/src/typescript-resolution.test.ts +76 -0
  158. package/test-timings.json +8 -0
package/src/index.ts CHANGED
@@ -8,6 +8,8 @@ import {
8
8
  type CreateNodesContextV2,
9
9
  type CreateNodesResultV2,
10
10
  type CreateNodesV2,
11
+ type PostTasksExecution,
12
+ type PreTasksExecution,
11
13
  readJsonFile,
12
14
  type TargetConfiguration,
13
15
  } from 'nx/src/devkit-exports.js';
@@ -71,9 +73,14 @@ import {
71
73
  EXTRACTED_TARGET_DIR,
72
74
  NEXTEST_EXTRACT_BIN,
73
75
  } from './nextest-extraction.js';
76
+ import {
77
+ type ProducerReceiptsOptions,
78
+ postTasksExecution as postProducerReceipts,
79
+ preTasksExecution as preProducerReceipts,
80
+ } from './producer-receipts.js';
74
81
  import { runtimeInput, shellWord } from './runtime-input.js';
75
82
  import { isNonSourceDirectory } from './source-directories.js';
76
- import { postTasksExecution, preTasksExecution } from './task-results.js';
83
+ import { postTasksExecution as postTaskResults, preTasksExecution as preTaskResults } from './task-results.js';
77
84
  import { SHARD_TIMINGS_EXECUTOR, SHARD_TIMINGS_TARGET, timingsShardedSuite } from './test-timings.js';
78
85
  import {
79
86
  isBuildOutputTargetName,
@@ -83,7 +90,7 @@ import {
83
90
  } from './workspace-config-policy.js';
84
91
  import { globIndexedFiles } from './workspace-index.js';
85
92
 
86
- export { CARGO_TEST_COMPILE_TARGET, postTasksExecution, preTasksExecution };
93
+ export { CARGO_TEST_COMPILE_TARGET };
87
94
 
88
95
  /** Makes a version live and proves it answers; never cached. */
89
96
  export const DEPLOY_TARGET = 'deploy';
@@ -1077,6 +1084,20 @@ function isBuildOutputPackageJson(packageJsonPath: string): boolean {
1077
1084
  return BUILD_OUTPUT_SEGMENTS.some((segment) => normalized.includes(segment));
1078
1085
  }
1079
1086
 
1087
+ /**
1088
+ * Nx accepts one pre/post task-hook pair per plugin. Two independent observers share it: the controller's task-results
1089
+ * hint and the opt-in producer completion receipts. Each sees the same options and run context; neither reads the
1090
+ * other's output. The hint is recorded first so a producer-receipt bug cannot cost the controller its evidence.
1091
+ */
1092
+ export const preTasksExecution: PreTasksExecution<ProducerReceiptsOptions> = async (options, context) => {
1093
+ preTaskResults(options, context);
1094
+ await preProducerReceipts(options, context);
1095
+ };
1096
+ export const postTasksExecution: PostTasksExecution<ProducerReceiptsOptions> = async (options, context) => {
1097
+ await postTaskResults(options, context);
1098
+ await postProducerReceipts(options, context);
1099
+ };
1100
+
1080
1101
  export default { createNodesV2, postTasksExecution, preTasksExecution };
1081
1102
 
1082
1103
  interface PackageJson {
@@ -2347,7 +2368,7 @@ function createNapiTestTarget(projectRoot: string, hasDedicatedBunfig: boolean):
2347
2368
  // package's cargo target/ directory turns that scan into tens of
2348
2369
  // seconds. bun only auto-loads bunfig from the cwd, so the package
2349
2370
  // config is passed explicitly.
2350
- command: `bun test${configFlag} --timeout=30000 native.test.ts`,
2371
+ command: `bun test${configFlag} --timeout=0 native.test.ts`,
2351
2372
  cwd: `${projectRoot}/src`,
2352
2373
  // Routes the package's native loader to the napi-debug artifact under
2353
2374
  // .cache/native-debug instead of the packaged dist/native tree.
@@ -1,29 +1,30 @@
1
- // A linked-package snapshot vouched for by real Nx: the managed snapshot module's default probe, which loads the
1
+ // A linked-package snapshot vouched for by real Nx: the managed snapshot module's `pluginProbe`, which loads the
2
2
  // plugin product a consumer installs (this package's built `ensure-built`) and calls its read-only `probeBuilt`
3
- // against a provider workspace that real Nx built and cached. No receipt is injected: the hit, the task hash, HEAD
4
- // and every output byte come from the provider's own Nx, and a provider Nx cannot vouch for is refused unwritten.
5
- import { describe, expect, it } from 'bun:test';
3
+ // against a provider workspace whose nx.json enables this plugin's producer receipts. No receipt is injected: the
4
+ // production record, task hash, HEAD and every output byte come from the provider's own Nx run, and a provider no
5
+ // production vouches for is refused unwritten.
6
+ import { afterAll, describe, expect, it } from 'bun:test';
7
+ import { existsSync } from 'node:fs';
6
8
  import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises';
7
9
  import { tmpdir } from 'node:os';
8
- import { dirname, join } from 'node:path';
9
- import { fileURLToPath } from 'node:url';
10
+ import { join } from 'node:path';
10
11
  import typia from 'typia';
11
12
  import { fixtureNxEnv, withNxFixture } from './__tests__/fixture-nx-env.js';
13
+ import { testFileInstallation } from './__tests__/owned-installation.js';
12
14
  import { managedAssetsRoot } from './managed-assets.js';
13
15
 
14
- const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
15
- const repoRoot = dirname(dirname(packageRoot));
16
- const nxEntry = join(repoRoot, 'node_modules', '.bin', 'nx');
16
+ /** The Nx and the plugin product the provider and the consumer link, one copy this file owns; none may write into it. */
17
+ const installation = testFileInstallation('linked-snapshot-installation-');
17
18
  const SNAPSHOTS = join(managedAssetsRoot, 'raw/tooling/direnv/linked-snapshots.ts');
18
19
  const DECLARATION = { targets: ['linked-api:build'], artifactModules: [] };
19
20
 
20
- /** One capture through the default probe, in a fresh Bun process as shell entry runs it: no plugins preloaded. */
21
+ /** One capture via the consumer's installed plugin in a fresh Bun process, as shell entry runs it: none preloaded. */
21
22
  const CAPTURE = `
22
23
  const snapshots = await import(Bun.argv[1]);
23
24
  const [consumer, source, declaration] = JSON.parse(Bun.argv[2]);
24
- const binding = await snapshots.snapshotBinding(consumer, 'linked-api', source, declaration);
25
+ const binding = await snapshots.snapshotBinding(consumer, 'linked-api', source, declaration, snapshots.pluginProbe(consumer));
25
26
  const receipt = binding.kind === 'snapshot' ? snapshots.verifySnapshot(binding.directory.slice(0, -'/packages/api'.length)) : null;
26
- process.stdout.write(JSON.stringify({ binding, receipt }));
27
+ await new Promise<void>((resolve, reject) => process.stdout.write(JSON.stringify({ binding, receipt }), error => error ? reject(error) : resolve()));
27
28
  `;
28
29
 
29
30
  interface Captured {
@@ -39,7 +40,14 @@ interface Captured {
39
40
  readonly head: string;
40
41
  readonly headTree: string;
41
42
  readonly tasks: readonly { readonly id: string; readonly hash: string }[];
43
+ readonly producers: readonly { readonly target: string; readonly basis: string; readonly sha256: string }[];
42
44
  };
45
+ readonly producerReceipts: readonly {
46
+ readonly version: number;
47
+ readonly target: string;
48
+ readonly argv: readonly string[];
49
+ readonly trackedTreeClean: boolean;
50
+ }[];
43
51
  } | null;
44
52
  }
45
53
 
@@ -63,16 +71,47 @@ async function git(workspace: string, ...args: string[]): Promise<string> {
63
71
  return run.stdout.trim();
64
72
  }
65
73
 
66
- /** A provider Nx workspace whose `linked-api:build` copies its source into `dist`, committed. */
74
+ /**
75
+ * A provider Nx workspace whose `linked-api:build` copies its source into `dist`, committed. Its nx.json registers
76
+ * this plugin with the producer option naming that target, so a successful run publishes its completion receipt.
77
+ */
67
78
  async function writeProvider(workspace: string): Promise<string> {
68
79
  await git(workspace, 'init', '--quiet');
69
80
  await writeFile(join(workspace, '.gitignore'), '.nx\nnode_modules\npackages/*/dist\n');
70
- // The repository's own node_modules, so the fixture resolves the Nx this package is written against.
71
- await symlink(join(repoRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
72
- await writeFile(join(workspace, 'nx.json'), JSON.stringify({ useDaemonProcess: true, cacheDirectory: '.nx/cache' }));
81
+ await symlink(await installation.nodeModules(), join(workspace, 'node_modules'), 'dir');
82
+ await writeFile(
83
+ join(workspace, 'nx.json'),
84
+ JSON.stringify({
85
+ useDaemonProcess: true,
86
+ cacheDirectory: '.nx/cache',
87
+ plugins: [{ plugin: '@smoothbricks/nx-plugin', options: { producerReceipts: { targets: DECLARATION.targets } } }],
88
+ }),
89
+ );
90
+ // A lockfile package no task's project can resolve, as a Bun isolated install leaves most of them: the build names no
91
+ // externalDependencies, so Nx keys it on AllExternalDependencies, which this package is part of. The receipt binds
92
+ // that set by Nx's lockfile hash and must not try to resolve it from the task's project.
73
93
  await writeFile(
74
94
  join(workspace, 'package.json'),
75
- JSON.stringify({ name: 'provider', private: true, workspaces: ['packages/*'] }),
95
+ JSON.stringify({
96
+ name: 'provider',
97
+ private: true,
98
+ workspaces: ['packages/*'],
99
+ devDependencies: { '@fixture/elsewhere': '1.0.0' },
100
+ }),
101
+ );
102
+ await writeFile(
103
+ join(workspace, 'bun.lock'),
104
+ JSON.stringify({
105
+ lockfileVersion: 1,
106
+ workspaces: {
107
+ '': { name: 'provider', devDependencies: { '@fixture/elsewhere': '1.0.0' } },
108
+ 'packages/api': { name: 'linked-api', version: '1.0.0' },
109
+ },
110
+ packages: {
111
+ '@fixture/elsewhere': ['@fixture/elsewhere@1.0.0', '', {}, `sha512-${'A'.repeat(86)}==`],
112
+ 'linked-api': ['linked-api@workspace:packages/api'],
113
+ },
114
+ }),
76
115
  );
77
116
  const api = join(workspace, 'packages/api');
78
117
  await mkdir(join(api, 'src'), { recursive: true });
@@ -108,24 +147,33 @@ async function writeProvider(workspace: string): Promise<string> {
108
147
  }
109
148
 
110
149
  describe('linked snapshots vouched for by the provider’s real Nx', () => {
111
- it('captures what real Nx built, names a new commit anew, and refuses stale output without writing it', async () => {
150
+ afterAll(() => installation.retire());
151
+
152
+ it('captures only what a real Nx production published, once per commit, and refuses stale output without writing it', async () => {
112
153
  const consumer = await mkdtemp(join(tmpdir(), 'linked-snapshot-consumer-'));
113
154
  try {
114
155
  await withNxFixture('linked-snapshot-', async ({ workspace, socketDirectory }) => {
115
156
  const source = await writeProvider(workspace);
116
157
  const daemonless = { ...fixtureNxEnv(workspace, socketDirectory), NX_DAEMON: 'false' };
117
- const built = await execute(
118
- 'node',
119
- [nxEntry, 'run', 'linked-api:build', '--outputStyle=static'],
120
- workspace,
121
- daemonless,
122
- );
123
- expect(built.status, built.stdout + built.stderr).toBe(0);
158
+ const build = async () => {
159
+ const built = await execute(
160
+ 'node',
161
+ [join(workspace, 'node_modules', '.bin', 'nx'), 'run', 'linked-api:build', '--outputStyle=static'],
162
+ workspace,
163
+ daemonless,
164
+ );
165
+ expect(built.status, built.stdout + built.stderr).toBe(0);
166
+ };
124
167
 
125
- // The consumer installs this package's built plugin product, as a workspace installs @smoothbricks/nx-plugin.
168
+ // The consumer installs this package's built plugin product, as a workspace installs @smoothbricks/nx-plugin:
169
+ // the copy in the file's installation, whose dependencies resolve inside that copy.
126
170
  await mkdir(join(consumer, 'node_modules/@smoothbricks'), { recursive: true });
127
171
  await writeFile(join(consumer, 'package.json'), JSON.stringify({ name: 'consumer', private: true }));
128
- await symlink(packageRoot, join(consumer, 'node_modules/@smoothbricks/nx-plugin'), 'dir');
172
+ await symlink(
173
+ join(await installation.nodeModules(), '@smoothbricks/nx-plugin'),
174
+ join(consumer, 'node_modules/@smoothbricks/nx-plugin'),
175
+ 'dir',
176
+ );
129
177
  const env = { ...fixtureNxEnv(workspace, socketDirectory), NX_DAEMON: 'true' };
130
178
  const capture = async (): Promise<Captured> => {
131
179
  const run = await execute(
@@ -138,21 +186,55 @@ describe('linked snapshots vouched for by the provider’s real Nx', () => {
138
186
  return typia.json.assertParse<Captured>(run.stdout);
139
187
  };
140
188
 
189
+ // Nothing produced yet: no receipt vouches for the provider, so nothing is captured and nothing is built.
190
+ const unproduced = await capture();
191
+ expect(unproduced.binding.kind).toBe('refused');
192
+ expect(existsSync(join(source, 'dist'))).toBe(false);
193
+
194
+ await build();
141
195
  const first = await capture();
142
196
  expect(first.binding.kind, first.binding.reason).toBe('snapshot');
143
197
  expect(first.receipt?.provenance.head).toBe(await git(workspace, 'rev-parse', 'HEAD'));
144
198
  expect(first.receipt?.provenance.headTree).toBe(await git(workspace, 'rev-parse', 'HEAD^{tree}'));
145
199
  expect(first.receipt?.provenance.tasks.map(({ id }) => id)).toContain('linked-api:build');
200
+ // The receipt the provider's own run published, retained verbatim and bound by the snapshot's name.
201
+ expect(first.receipt?.provenance.producers.map(({ target }) => target)).toEqual(['linked-api:build']);
202
+ const produced = first.receipt?.producerReceipts[0];
203
+ expect(produced?.version).toBe(1);
204
+ expect(produced?.target).toBe('linked-api:build');
205
+ expect(produced?.trackedTreeClean).toBe(true);
206
+ expect(produced?.argv.join(' ')).toContain('linked-api:build');
146
207
  expect(await readFile(join(first.binding.directory ?? '', 'dist/index.js'), 'utf8')).toBe(
147
208
  'export const value = "first";\n',
148
209
  );
149
210
 
150
- // The same bytes under another commit are another snapshot with another provenance.
211
+ // The committed tree decides validity; an empty commit preserves the real original producer basis.
212
+ const originalBasis = first.receipt?.provenance.head;
213
+ if (originalBasis === undefined) throw new Error('the real producer omitted its basis');
151
214
  await git(workspace, 'commit', '-qm', 'same tree', '--allow-empty');
215
+ expect(await git(workspace, 'rev-parse', 'HEAD')).not.toBe(originalBasis);
216
+ const sameTree = await capture();
217
+ expect(sameTree.binding.kind, sameTree.binding.reason).toBe('snapshot');
218
+ expect(sameTree.binding.id).toBe(first.binding.id);
219
+ expect(sameTree.receipt?.provenance.head).toBe(originalBasis);
220
+ expect(sameTree.receipt?.provenance.producers[0]?.basis).toBe(originalBasis);
221
+
222
+ // A genuinely changed committed tree cannot borrow the old production.
223
+ await writeFile(join(source, 'src/index.js'), 'export const value = "second";\n');
224
+ await git(workspace, 'add', '-A');
225
+ await git(workspace, 'commit', '-qm', 'changed tree');
226
+ expect((await capture()).binding.kind).toBe('refused');
227
+ await build();
152
228
  const second = await capture();
153
229
  expect(second.binding.kind, second.binding.reason).toBe('snapshot');
154
230
  expect(second.binding.id).not.toBe(first.binding.id);
155
231
  expect(second.receipt?.provenance.head).toBe(await git(workspace, 'rev-parse', 'HEAD'));
232
+ expect(await readFile(join(second.binding.directory ?? '', 'dist/index.js'), 'utf8')).toBe(
233
+ 'export const value = "second";\n',
234
+ );
235
+ expect(await readFile(join(first.binding.directory ?? '', 'dist/index.js'), 'utf8')).toBe(
236
+ 'export const value = "first";\n',
237
+ );
156
238
 
157
239
  // Output the producer did not record: refused as not current, and the provider's dist is left as it was.
158
240
  const output = join(source, 'dist/index.js');
@@ -160,7 +242,7 @@ describe('linked snapshots vouched for by the provider’s real Nx', () => {
160
242
  const before = await stat(output, { bigint: true });
161
243
  const stale = await capture();
162
244
  expect(stale.binding.kind).toBe('refused');
163
- expect(stale.binding.reason).toContain('is not current');
245
+ expect(stale.binding.reason).toContain('Public product bytes differ from actual producer receipt');
164
246
  const after = await stat(output, { bigint: true });
165
247
  expect([after.ino, after.mtimeNs, after.ctimeNs]).toEqual([before.ino, before.mtimeNs, before.ctimeNs]);
166
248
  expect(await readFile(output, 'utf8')).toBe('export const value = "tampered";\n');
@@ -168,5 +250,5 @@ describe('linked snapshots vouched for by the provider’s real Nx', () => {
168
250
  } finally {
169
251
  await rm(consumer, { recursive: true, force: true });
170
252
  }
171
- }, 60_000);
253
+ });
172
254
  });
@@ -561,7 +561,10 @@ function yamlLinesForStep(step: CiWorkflowStep, options: CiWorkflowDefinitionOpt
561
561
  'upload',
562
562
  [
563
563
  'name: trace-results-${{ github.run_id }}',
564
- `path: ${TRACE_DB_ARTIFACT_GLOB}`,
564
+ 'path: |',
565
+ ` ${TRACE_DB_ARTIFACT_GLOB}`,
566
+ " ${{ job.status == 'failure' && format('{0}/project-graph.json', env.NX_WORKSPACE_DATA_DIRECTORY || '.nx/workspace-data') || '' }}",
567
+ " ${{ job.status == 'failure' && format('{0}/d/daemon.log', env.NX_WORKSPACE_DATA_DIRECTORY || '.nx/workspace-data') || '' }}",
565
568
  'if-no-files-found: ignore',
566
569
  'retention-days: 14',
567
570
  'include-hidden-files: true',
@@ -1142,7 +1145,7 @@ function renderOptionalLines(lines: string[]): string {
1142
1145
  function nxSmartStep(step: CiWorkflowStep, target: string, name: string): string[] {
1143
1146
  return [
1144
1147
  ` - name: ${step.name}`,
1145
- ` run: smoo github-ci nx-smart --target ${target} --name "${name}" --step ${step.number}`,
1148
+ ` run: ${step.kind === CiWorkflowStepKind.Build ? 'NX_VERBOSE_LOGGING=true ' : ''}smoo github-ci nx-smart --target ${target} --name "${name}" --step ${step.number}`,
1146
1149
  ];
1147
1150
  }
1148
1151
 
@@ -133,8 +133,19 @@ export interface PublishWorkflowInputs {
133
133
  dryRun: boolean;
134
134
  }
135
135
 
136
+ /**
137
+ * The `mode=` output of `smoo release version --github-output`, which every
138
+ * release gate in this workflow reads. `new`: Nx created a release commit.
139
+ * `complete`: HEAD already carries the release (a rerun, or tags moved by
140
+ * `smoo release retag-unpublished`) and publish completes its missing durable
141
+ * state. `dry-run`: the preview of a release. `none`: nothing to release.
142
+ * Every mode but `none` names packages the workflow must build and validate,
143
+ * because `smoo release publish --prebuilt` refuses an unbuilt package.
144
+ */
145
+ export type ReleaseVersionMode = 'new' | 'complete' | 'dry-run' | 'none';
146
+
136
147
  export interface PublishWorkflowVersionOutputs {
137
- mode: 'new' | 'none';
148
+ mode: ReleaseVersionMode;
138
149
  projects: string[];
139
150
  }
140
151
 
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from 'bun:test';
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
4
- import { tmpdir } from 'node:os';
4
+ import { tmpdir, userInfo } from 'node:os';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { managedAssetsRoot } from '../managed-assets.js';
7
7
 
@@ -126,4 +126,47 @@ describe('managed repo-path', () => {
126
126
  });
127
127
  },
128
128
  );
129
+
130
+ it("names this checkout's own shell's evaluated profile, never the checkout's re-pointable link", async () => {
131
+ await withRepoPath(async (fixture) => {
132
+ // The link is what any activation of the checkout last pointed it at; the shell evaluated another profile.
133
+ const evaluated = join(fixture.root, 'evaluated-profile');
134
+ await executable(join(evaluated, 'bin/bun'), 'evaluated-bun');
135
+ await executable(join(fixture.entries[0], 'bun'), 'link-bun');
136
+ const run = (args: readonly string[], devenvRoot: string) => {
137
+ const result = spawnSync(join(fixture.tools, 'bash'), [fixture.helper, ...args], {
138
+ encoding: 'utf8',
139
+ env: { HOME: fixture.home, PATH: fixture.tools, DEVENV_ROOT: devenvRoot, DEVENV_PROFILE: evaluated },
140
+ });
141
+ expect(result.stderr).toBe('');
142
+ expect(result.status).toBe(0);
143
+ return result.stdout;
144
+ };
145
+ const own = join(fixture.root, 'tooling/direnv');
146
+ expect(run(['--print'], own).split('\n')[0]).toBe(join(evaluated, 'bin'));
147
+ // Another checkout's shell, inherited by a hook run here, does not name this checkout's profile.
148
+ expect(run(['--print'], join(fixture.root, 'system-bin')).split('\n')[0]).toBe(fixture.entries[0]);
149
+
150
+ const selected = spawnSync(join(fixture.tools, 'bash'), ['-c', 'bun'], {
151
+ encoding: 'utf8',
152
+ env: { HOME: fixture.home, PATH: run([], own).trimEnd() },
153
+ });
154
+ expect(selected.stderr).toBe('');
155
+ expect(selected.stdout).toBe('evaluated-bun\n');
156
+ });
157
+ });
158
+
159
+ it("reaches the installed cowshed through the real uid's passwd home when the caller passes only PATH", async () => {
160
+ await withRepoPath(async (fixture) => {
161
+ // A formatter or hook that passes { PATH } alone leaves HOME unset; it is not the helper's to require.
162
+ const result = spawnSync(join(fixture.tools, 'bash'), [fixture.helper], {
163
+ encoding: 'utf8',
164
+ env: { PATH: fixture.tools },
165
+ });
166
+ expect(result.stderr).toBe('');
167
+ expect(result.status).toBe(0);
168
+ const installed = join(userInfo().homedir, 'Library/Application Support/dev.cowshed/bin');
169
+ expect(result.stdout).toBe(`${[installed, ...fixture.entries].join(':')}:${fixture.tools}\n`);
170
+ });
171
+ });
129
172
  });
@@ -0,0 +1,95 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ /** The setup action's steps in the order a runner takes them, each as its fields. */
7
+ function actionSteps(yaml: string): Map<string, unknown>[] {
8
+ const action: unknown = Bun.YAML.parse(yaml);
9
+ if (typeof action !== 'object' || action === null || !('runs' in action)) return [];
10
+ const runs = action.runs;
11
+ if (typeof runs !== 'object' || runs === null || !('steps' in runs) || !Array.isArray(runs.steps)) return [];
12
+ return runs.steps.map(
13
+ (step: unknown) => new Map(typeof step === 'object' && step !== null ? Object.entries(step) : []),
14
+ );
15
+ }
16
+
17
+ const steps = actionSteps(
18
+ readFileSync(new URL('../../managed/templates/github/actions/setup-devenv/action.yml', import.meta.url), 'utf8'),
19
+ );
20
+ const freeDiskAt = steps.findIndex((step) => String(step.get('run') ?? '').includes('sudo rm -rf'));
21
+ const freeDisk = steps[freeDiskAt];
22
+
23
+ /**
24
+ * Runs the step's script the way GitHub runs a bash step, with df reporting `freeGiB` free on / and sudo exiting with
25
+ * `sudoStatus`. A sudo that succeeds frees 40 GiB; nothing on disk is deleted.
26
+ */
27
+ function runFreeDisk(freeGiB: number, sudoStatus: number) {
28
+ if (!freeDisk) throw new Error('setup-devenv has no step that frees runner disk');
29
+ const tools = mkdtempSync(join(tmpdir(), 'hostedtoolcache-'));
30
+ try {
31
+ const stubs = [
32
+ 'free=$((FREE_GIB * 1024 * 1024))',
33
+ 'df() { if [ "$1" = -k ]; then printf "Avail\\n%s\\n" "$free"; else echo "df $*"; fi; }',
34
+ 'sudo() { echo "sudo $*"; [ "$SUDO_STATUS" = 0 ] || return "$SUDO_STATUS"; free=$((free + 40 * 1024 * 1024)); }',
35
+ ].join('\n');
36
+ const result = Bun.spawnSync(
37
+ ['bash', '--noprofile', '--norc', '-eo', 'pipefail', '-c', `${stubs}\n${String(freeDisk.get('run'))}`],
38
+ {
39
+ env: {
40
+ ...process.env,
41
+ AGENT_TOOLSDIRECTORY: tools,
42
+ FREE_GIB: String(freeGiB),
43
+ SUDO_STATUS: String(sudoStatus),
44
+ },
45
+ },
46
+ );
47
+ const stdout = result.stdout.toString();
48
+ return {
49
+ tools,
50
+ status: result.exitCode,
51
+ stdout,
52
+ deletes: stdout.split('\n').filter((line) => line.startsWith('sudo rm -rf ')),
53
+ };
54
+ } finally {
55
+ rmSync(tools, { recursive: true, force: true });
56
+ }
57
+ }
58
+
59
+ describe('freeing GitHub-hosted runner disk in setup-devenv', () => {
60
+ test('runs only on GitHub-hosted Linux runners that take the ephemeral path', () => {
61
+ // A self-hosted machine keeps everything, even one that takes the ephemeral branch.
62
+ expect(String(freeDisk?.get('if')).split(' && ').sort()).toEqual([
63
+ "runner.environment == 'github-hosted'",
64
+ "runner.os == 'Linux'",
65
+ "steps.runner-kind.outputs.host != 'true'",
66
+ ]);
67
+ });
68
+
69
+ test('frees the space before any action restores or installs something on the disk', () => {
70
+ expect(freeDisk).toBeDefined();
71
+ // Every action the setup uses restores a cache or installs Nix.
72
+ const actions = steps.flatMap((step, index) => (step.has('uses') ? [index] : []));
73
+ expect(actions.length).toBeGreaterThan(0);
74
+ expect(Math.min(...actions)).toBeGreaterThan(freeDiskAt);
75
+ });
76
+
77
+ test('deletes nothing on a runner that already has the space', () => {
78
+ const run = runFreeDisk(90, 0);
79
+ expect(run.status).toBe(0);
80
+ expect(run.deletes).toEqual([]);
81
+ });
82
+
83
+ test('stops deleting as soon as / has the space', () => {
84
+ const run = runFreeDisk(10, 0);
85
+ expect(run.status).toBe(0);
86
+ expect(run.deletes).toHaveLength(1);
87
+ });
88
+
89
+ test('warns and goes on when a delete fails, since freeing space is never a gate', () => {
90
+ const run = runFreeDisk(10, 1);
91
+ expect(run.status).toBe(0);
92
+ expect(run.deletes).toContain(`sudo rm -rf ${run.tools}`);
93
+ expect(run.stdout).toContain(`::warning::could not remove ${run.tools}`);
94
+ });
95
+ });
@@ -82,25 +82,28 @@ describe('code time', () => {
82
82
 
83
83
  describe('nextest-code-bound wrapper', () => {
84
84
  /**
85
- * A stand-in test binary: it records `wait` seconds of lease wait in the record its wrapper names,
86
- * from a child process as a disk-lease client in the test's tree would, then works `work` seconds
87
- * and exits `status`.
85
+ * A stand-in test binary: when `wait` is a number, a child process, as a disk-lease client in the
86
+ * test's tree would, records one wait in the record its wrapper names, sleeps `wait` seconds and
87
+ * ends it; then the binary works `work` seconds and exits `status`. The recorded wait starts at
88
+ * the epoch and ends at the largest safe integer, so the wrapper's clipping to the run makes it
89
+ * cover the whole run: the code time is exactly zero however long process startup takes on a
90
+ * busy host. A `null` wait records nothing, so the code time is the whole wall time.
88
91
  */
89
- const runWrapped = (bound: string, wait: number, work: number, status: number) => {
92
+ const runWrapped = (bound: string, wait: number | null, work: number, status: number) => {
90
93
  const root = mkdtempSync(join(tmpdir(), 'nextest-code-bound-'));
91
94
  try {
92
95
  const binary = join(root, 'fake-test');
96
+ const lease =
97
+ wait === null
98
+ ? []
99
+ : [
100
+ 'sh -c \'echo "start $$ 0 0 namespace" >> "$COWSHED_LEASE_WAIT_RECORD"; ' +
101
+ `sleep ${wait}; ` +
102
+ `echo "end $$ 0 ${Number.MAX_SAFE_INTEGER}" >> "$COWSHED_LEASE_WAIT_RECORD"'`,
103
+ ];
93
104
  writeFileSync(
94
105
  binary,
95
- [
96
- '#!/bin/sh',
97
- 'sh -c \'echo "start $$ 0 $(perl -MTime::HiRes=time -e "printf q(%d), time() * 1000000") namespace" >> "$COWSHED_LEASE_WAIT_RECORD"; ' +
98
- `sleep ${wait}; ` +
99
- 'echo "end $$ 0 $(perl -MTime::HiRes=time -e "printf q(%d), time() * 1000000")" >> "$COWSHED_LEASE_WAIT_RECORD"\'',
100
- `sleep ${work}`,
101
- 'echo "argument $1"',
102
- `exit ${status}`,
103
- ].join('\n'),
106
+ ['#!/bin/sh', ...lease, `sleep ${work}`, 'echo "argument $1"', `exit ${status}`].join('\n'),
104
107
  );
105
108
  chmodSync(binary, 0o755);
106
109
  // The wrapper makes its record in its TMPDIR: this case's own root, so the count below is this run's alone.
@@ -115,22 +118,24 @@ describe('nextest-code-bound wrapper', () => {
115
118
  }
116
119
  };
117
120
 
118
- // Real processes and real time, so the cases sleep as little as proves each verdict: 0.75s in all.
121
+ // Real processes and real time, so the cases sleep as little as proves each verdict: 0.75s in all. No verdict
122
+ // depends on how fast the host starts a process: a covered run's code time is zero, and an uncovered one only grows.
119
123
  it('passes a test whose wall time is over its class only by its lease waits', () => {
120
124
  const run = runWrapped('0.3', 0.4, 0, 0);
121
125
  expect(run.stdout).toContain('argument --exact');
122
126
  expect(run.stderr).toMatch(
123
- /nextest-code-bound: code 0\.\d+s of 0\.3s, within its class \(wall \d+\.\d+s less \d+\.\ds waiting/,
127
+ /nextest-code-bound: code 0\.0s of 0\.3s, within its class \(wall (?:0\.[4-9]|[1-9]\d*\.\d)s less \d+\.\ds waiting/,
124
128
  );
125
129
  expect(run.status).toBe(0);
126
130
  expect(run.recordsLeft).toBe(0);
127
131
  });
128
132
 
129
133
  it('reports code-time verdicts without changing the test exit status', () => {
130
- for (const { label, bound, work, status, verdict } of [
134
+ for (const { label, bound, wait, work, status, verdict } of [
131
135
  {
132
136
  label: 'warns of a passing test whose code time is over its class, and still passes it',
133
137
  bound: '0.3',
138
+ wait: null,
134
139
  work: 0.35,
135
140
  status: 0,
136
141
  verdict: 'OVER its class (a warning)',
@@ -138,12 +143,13 @@ describe('nextest-code-bound wrapper', () => {
138
143
  {
139
144
  label: "keeps a failing test's own exit status and still reports its split",
140
145
  bound: '30',
146
+ wait: 0,
141
147
  work: 0,
142
148
  status: 3,
143
149
  verdict: 'within its class',
144
150
  },
145
151
  ]) {
146
- const run = runWrapped(bound, 0, work, status);
152
+ const run = runWrapped(bound, wait, work, status);
147
153
  expect(run.stderr, label).toContain(verdict);
148
154
  expect(run.status, label).toBe(status);
149
155
  }