@smoothbricks/nx-plugin 0.4.28 → 0.4.29

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 (124) hide show
  1. package/README.md +203 -83
  2. package/dist/bounded-test-policy.d.ts +10 -3
  3. package/dist/bounded-test-policy.d.ts.map +1 -1
  4. package/dist/bounded-test-policy.js +19 -25
  5. package/dist/cargo-closure-input.d.ts +12 -0
  6. package/dist/cargo-closure-input.d.ts.map +1 -1
  7. package/dist/cargo-closure-input.js +29 -7
  8. package/dist/cargo-source-hash.d.ts.map +1 -1
  9. package/dist/cargo-source-hash.js +42 -19
  10. package/dist/ensure-built-receipt.d.ts +34 -6
  11. package/dist/ensure-built-receipt.d.ts.map +1 -1
  12. package/dist/ensure-built-receipt.js +265 -159
  13. package/dist/ensure-built-witness.d.ts +27 -2
  14. package/dist/ensure-built-witness.d.ts.map +1 -1
  15. package/dist/ensure-built-witness.js +2176 -15
  16. package/dist/ensure-built.d.ts +99 -1
  17. package/dist/ensure-built.d.ts.map +1 -1
  18. package/dist/ensure-built.js +34 -53
  19. package/dist/executors/bounded-exec/cpu-pool.d.ts +16 -5
  20. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  21. package/dist/executors/bounded-exec/cpu-pool.js +43 -19
  22. package/dist/executors/bounded-exec/executor.d.ts +11 -2
  23. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  24. package/dist/executors/bounded-exec/executor.js +139 -39
  25. package/dist/executors/bounded-exec/ram-temp.d.ts +17 -11
  26. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  27. package/dist/executors/bounded-exec/ram-temp.js +27 -13
  28. package/dist/generators/bun-test-tracing/generator.js +2 -2
  29. package/dist/graph-input-contract.d.ts +98 -0
  30. package/dist/graph-input-contract.d.ts.map +1 -0
  31. package/dist/graph-input-contract.js +624 -0
  32. package/dist/index.d.ts +12 -5
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +17 -3
  35. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  36. package/dist/managed-files/ci-workflow.js +5 -2
  37. package/dist/managed-files/publish-workflow.d.ts +11 -1
  38. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  39. package/dist/producer-receipts.d.ts +19 -0
  40. package/dist/producer-receipts.d.ts.map +1 -0
  41. package/dist/producer-receipts.js +921 -0
  42. package/dist/testing.d.ts +8 -0
  43. package/dist/testing.d.ts.map +1 -1
  44. package/dist/testing.js +58 -0
  45. package/managed/raw/patches/nx@23.2.1.patch +328 -50
  46. package/managed/raw/tooling/direnv/developer-links.ts +147 -21
  47. package/managed/raw/tooling/direnv/devenv.smoo.nix +7 -7
  48. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +14 -5
  49. package/managed/raw/tooling/direnv/linked-snapshots.ts +206 -40
  50. package/managed/raw/tooling/direnv/repo-path +15 -2
  51. package/managed/raw/tooling/direnv/setup-environment.ts +179 -114
  52. package/managed/templates/github/actions/cache-node-modules/action.yml +9 -0
  53. package/managed/templates/github/actions/setup-devenv/action.yml +63 -7
  54. package/nextest.toml +1 -1
  55. package/package.json +11 -6
  56. package/src/__tests__/fixture-nx-env.ts +7 -0
  57. package/src/__tests__/owned-installation.ts +174 -0
  58. package/src/bin/smoo-nx-bound-failures.test.ts +1 -1
  59. package/src/bounded-test-policy.test.ts +36 -22
  60. package/src/bounded-test-policy.ts +19 -27
  61. package/src/bun-bootstrap.test.ts +1 -1
  62. package/src/cargo-closure-input.test.ts +60 -11
  63. package/src/cargo-closure-input.ts +28 -6
  64. package/src/cargo-resolve-cache.test.ts +140 -25
  65. package/src/cargo-source-hash.test.ts +78 -3
  66. package/src/cargo-source-hash.ts +48 -30
  67. package/src/cross-check-policy.test.ts +2 -2
  68. package/src/ensure-built-receipt.test.ts +111 -16
  69. package/src/ensure-built-receipt.ts +251 -149
  70. package/src/ensure-built-witness.test.ts +197 -13
  71. package/src/ensure-built-witness.ts +187 -15
  72. package/src/ensure-built.test.ts +156 -102
  73. package/src/ensure-built.ts +114 -64
  74. package/src/executors/bounded-exec/cpu-pool.test.ts +116 -32
  75. package/src/executors/bounded-exec/cpu-pool.ts +55 -17
  76. package/src/executors/bounded-exec/cpu-tokens.test.ts +2 -2
  77. package/src/executors/bounded-exec/executor-host.test.ts +51 -41
  78. package/src/executors/bounded-exec/executor.test.ts +155 -35
  79. package/src/executors/bounded-exec/executor.ts +156 -45
  80. package/src/executors/bounded-exec/progress.test.ts +1 -1
  81. package/src/executors/bounded-exec/ram-temp-host.test.ts +46 -17
  82. package/src/executors/bounded-exec/ram-temp.test.ts +65 -3
  83. package/src/executors/bounded-exec/ram-temp.ts +32 -16
  84. package/src/executors/bounded-exec/verdict.test.ts +17 -12
  85. package/src/generators/bounded-test-targets/generator.test.ts +1 -3
  86. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  87. package/src/generators/bun-test-tracing/generator.ts +2 -2
  88. package/src/graph-input-contract.test.ts +371 -0
  89. package/src/graph-input-contract.ts +605 -0
  90. package/src/index.test.ts +3 -3
  91. package/src/index.ts +24 -3
  92. package/src/linked-snapshots.nx.test.ts +112 -30
  93. package/src/managed-files/ci-workflow.ts +5 -2
  94. package/src/managed-files/publish-workflow.ts +12 -1
  95. package/src/managed-files/repo-path.test.ts +44 -1
  96. package/src/managed-files/setup-devenv-free-disk.test.ts +95 -0
  97. package/src/nextest-code-bound.test.ts +23 -17
  98. package/src/nextest-partitions.test.ts +7 -1
  99. package/src/nx-cache-restore-mtime.test.ts +2 -2
  100. package/src/nx-daemon-claim.test.ts +5 -5
  101. package/src/nx-daemon-idle-cpu.test.ts +0 -1
  102. package/src/nx-daemon-idle-policy.test.ts +56 -0
  103. package/src/nx-daemon-ignore-files.test.ts +2 -2
  104. package/src/nx-daemon-validity.test.ts +31 -9
  105. package/src/nx-dot-input-policy.test.ts +5 -5
  106. package/src/nx-files-archive-racy.test.ts +1 -1
  107. package/src/nx-incomplete-run-summary.test.ts +1 -1
  108. package/src/nx-plugin-load-errors.test.ts +2 -2
  109. package/src/nx-project-graph-errors.test.ts +70 -0
  110. package/src/nx-skipped-task-exit.test.ts +2 -2
  111. package/src/nx-store-resolution.test.ts +7 -25
  112. package/src/nx-task-output-lease.test.ts +3 -3
  113. package/src/nx-use-local.test.ts +7 -5
  114. package/src/producer-receipts.test.ts +164 -0
  115. package/src/producer-receipts.ts +631 -0
  116. package/src/runtime-input.test.ts +1 -1
  117. package/src/serial-group-wiring.test.ts +4 -4
  118. package/src/task-results.test.ts +18 -16
  119. package/src/test-timings.test.ts +2 -2
  120. package/src/testing.test.ts +5 -5
  121. package/src/testing.ts +59 -0
  122. package/src/typecheck-test-policy.test.ts +1 -1
  123. package/src/typescript-resolution.test.ts +76 -0
  124. package/test-timings.json +5 -0
@@ -0,0 +1,631 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import {
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ realpathSync,
9
+ renameSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import { createRequire } from 'node:module';
14
+ import { delimiter, dirname, join, resolve } from 'node:path';
15
+ import type { NxJsonConfiguration } from 'nx/src/config/nx-json';
16
+ import type { ProjectGraph } from 'nx/src/config/project-graph';
17
+ import type { Task, TaskGraph } from 'nx/src/config/task-graph';
18
+ import type { PostTasksExecutionContext, PreTasksExecutionContext } from 'nx/src/project-graph/plugins/public-api';
19
+ import typia from 'typia';
20
+ import {
21
+ createWorkspaceNxRequire,
22
+ type EnsureBuiltProducerReceipt,
23
+ type EnsureBuiltProducerTool,
24
+ type EnsureBuiltReceipt,
25
+ parseTargetSelector,
26
+ providerInputProof,
27
+ selectorTaskId,
28
+ } from './ensure-built.js';
29
+ import {
30
+ captureProducerSource,
31
+ type ProducerSourceWitness,
32
+ producerOutputPaths,
33
+ providerReceipt,
34
+ type ReceiptEvidence,
35
+ receiptNode,
36
+ } from './ensure-built-receipt.js';
37
+ import {
38
+ graphInstallationIdentity,
39
+ movedNodes,
40
+ type NodeWitness,
41
+ nodesUnchanged,
42
+ workspaceSnapshot,
43
+ } from './ensure-built-witness.js';
44
+ import { graphInputContractIdentity } from './graph-input-contract.js';
45
+
46
+ export interface ProducerReceiptsOptions {
47
+ readonly producerReceipts?: { readonly targets: readonly string[] };
48
+ }
49
+ interface ToolResolution {
50
+ readonly name: string;
51
+ readonly from: string;
52
+ readonly target: string | null;
53
+ }
54
+ interface Installation {
55
+ readonly nodes: readonly NodeWitness[];
56
+ readonly resolutions: readonly (readonly [string, string, string | null])[];
57
+ readonly localInputs: string | null;
58
+ }
59
+ interface TargetBasis {
60
+ readonly graph: TaskGraph;
61
+ readonly source: ProducerSourceWitness;
62
+ }
63
+ interface RunBasis {
64
+ readonly projectGraph: ProjectGraph;
65
+ readonly nxJson: NxJsonConfiguration;
66
+ readonly targets: ReadonlyMap<string, TargetBasis>;
67
+ readonly tools: readonly EnsureBuiltProducerTool[];
68
+ readonly toolNodes: readonly NodeWitness[];
69
+ }
70
+ type RunFrame = ReceiptEvidence<RunBasis>;
71
+ interface PublishedReceipt {
72
+ readonly version: 1;
73
+ readonly disposition: 'published';
74
+ readonly receipt: EnsureBuiltReceipt;
75
+ readonly projectGraph: ProjectGraph;
76
+ readonly taskGraph: TaskGraph;
77
+ readonly nxJson: NxJsonConfiguration;
78
+ }
79
+ interface RefusedReceipt {
80
+ readonly version: 1;
81
+ readonly disposition: 'refused';
82
+ readonly target: string;
83
+ readonly detail: string;
84
+ }
85
+ type ProducerRecord = PublishedReceipt | RefusedReceipt;
86
+ const runs = new Map<string, RunFrame>();
87
+ function sha(value: unknown): string {
88
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');
89
+ }
90
+ function configured(options: ProducerReceiptsOptions | undefined): readonly string[] {
91
+ return options?.producerReceipts?.targets ?? [];
92
+ }
93
+ /**
94
+ * Where a record of `disposition` lives. A refusal has its own file beside the receipt, so a run that could not prove
95
+ * its products never replaces the receipt an earlier run published: readers validate that receipt on its own evidence.
96
+ */
97
+ function recordPath(root: string, target: string, disposition: ProducerRecord['disposition']): string {
98
+ const load = createWorkspaceNxRequire(root);
99
+ return join(
100
+ load('nx/src/utils/cache-directory').workspaceDataDirectoryForWorkspace(root),
101
+ `producer-${disposition === 'published' ? 'receipt' : 'refusal'}-${sha(target)}.json`,
102
+ );
103
+ }
104
+ function publish(root: string, target: string, record: ProducerRecord): ReceiptEvidence<true> {
105
+ try {
106
+ const path = recordPath(root, target, record.disposition);
107
+ mkdirSync(dirname(path), { recursive: true });
108
+ const temporary = `${path}.${randomUUID()}`;
109
+ try {
110
+ writeFileSync(temporary, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
111
+ renameSync(temporary, path);
112
+ } finally {
113
+ rmSync(temporary, { force: true });
114
+ }
115
+ // A receipt answers the refusal of any run before it.
116
+ if (record.disposition === 'published') rmSync(recordPath(root, target, 'refused'), { force: true });
117
+ return { ok: true, value: true };
118
+ } catch (error) {
119
+ if (error instanceof Error)
120
+ return { ok: false, detail: `Cannot publish producer ${record.disposition} record: ${error.message}` };
121
+ throw error;
122
+ }
123
+ }
124
+ function same(left: unknown, right: unknown): boolean {
125
+ return JSON.stringify(left) === JSON.stringify(right);
126
+ }
127
+ /**
128
+ * Whether a tool node whose ctime alone moved still reads as `tools` recorded it: the same bytes, link text,
129
+ * membership and mode. Bun's global store is shared by every checkout, and linking a package's bin on any of their
130
+ * installs re-chmods the store file to the mode it already has; that moves the ctime of a node these tools witness
131
+ * without changing it, and is no reason to refuse the run.
132
+ */
133
+ function recordedTool(tools: readonly EnsureBuiltProducerTool[]): (path: string) => boolean {
134
+ const recorded = new Map(tools.flatMap((tool) => tool.nodes.map((node) => [node.path, node] as const)));
135
+ return (path) => {
136
+ const node = recorded.get(path);
137
+ return node !== undefined && same(receiptNode(path, path, []), node);
138
+ };
139
+ }
140
+ function missing(paths: readonly string[]): boolean {
141
+ return paths.every((path) => {
142
+ try {
143
+ lstatSync(path);
144
+ return false;
145
+ } catch (error) {
146
+ if (error instanceof Error && 'code' in error && ['ENOENT', 'ENOTDIR'].includes(String(error.code))) return true;
147
+ throw error;
148
+ }
149
+ });
150
+ }
151
+ function defaultOverrides(task: Task): boolean {
152
+ return Object.entries(task.overrides).every(
153
+ ([name, value]) => name === '__overrides_unparsed__' && Array.isArray(value) && value.length === 0,
154
+ );
155
+ }
156
+ function targetGraph(root: string, target: string, projectGraph: ProjectGraph): TaskGraph {
157
+ const selector = parseTargetSelector(target);
158
+ if (selector === null) throw new Error(`Invalid declared producer target ${target}`);
159
+ return createWorkspaceNxRequire(root)('nx/src/tasks-runner/create-task-graph').createTaskGraph(
160
+ projectGraph,
161
+ {},
162
+ [selector.project],
163
+ [selector.target],
164
+ selector.configuration,
165
+ {},
166
+ false,
167
+ );
168
+ }
169
+ /** Tool resolution is captured in producer scope; readers inspect its recorded filesystem, not their own environment. */
170
+ function toolsFor(
171
+ root: string,
172
+ nxJson: NxJsonConfiguration,
173
+ projectGraph: ProjectGraph,
174
+ bases: readonly TargetBasis[],
175
+ ): ReceiptEvidence<{ readonly tools: readonly EnsureBuiltProducerTool[]; readonly nodes: readonly NodeWitness[] }> {
176
+ try {
177
+ const load = createWorkspaceNxRequire(root);
178
+ const data = load('nx/src/utils/cache-directory').workspaceDataDirectoryForWorkspace(root);
179
+ const snapshot = workspaceSnapshot(root, new (load('nx/src/native').WorkspaceContext)(root, data), undefined);
180
+ const local = graphInputContractIdentity(root, nxJson, snapshot);
181
+ // A task's npm external inputs (AllExternalDependencies, and the `npm:` nodes of its project's dependency closure)
182
+ // are Nx's lockfile identities, bound by the receipt's hashDetails and the committed tree's bun.lock. They add no
183
+ // installed closure: resolved from the task's project, a transitive or uninstalled-optional node is unresolvable
184
+ // under Bun's isolated linker, and the installed closure of every lockfile package measured 46 MB of evidence and
185
+ // 10 s of census. The tools that compute the graph and hashes are still bound below.
186
+ let needsCargo = false;
187
+ for (const basis of bases) {
188
+ const proof = providerInputProof(root, nxJson, projectGraph, basis.graph, load);
189
+ if (proof.runtimeSource.kind === 'opaque') return { ok: false, detail: proof.runtimeSource.detail };
190
+ needsCargo ||= Object.values(proof.inputs).some((input) => input.runtime.length > 0);
191
+ }
192
+ let installationMiss = 'unproved installed module/resolution closure';
193
+ const identity = graphInstallationIdentity(
194
+ root,
195
+ nxJson,
196
+ load('nx/src/utils/package-json').readModulePackageJson,
197
+ load('nx/src/native').expandOutputs,
198
+ local ?? { plugins: [], packages: [], identity: '[]' },
199
+ (detail) => {
200
+ installationMiss = detail;
201
+ },
202
+ );
203
+ if (identity === null)
204
+ return { ok: false, detail: `Producer installed module/resolution closure is unproved: ${installationMiss}` };
205
+ const installation = typia.json.isParse<Installation>(identity);
206
+ if (installation === null) return { ok: false, detail: 'Invalid installed module closure evidence' };
207
+ const observed: NodeWitness[] = [];
208
+ const paths = new Set(installation.nodes.map(({ path }) => path));
209
+ const absent = new Set<string>();
210
+ function namespace(path: string): void {
211
+ let stats: ReturnType<typeof lstatSync>;
212
+ try {
213
+ stats = lstatSync(path);
214
+ } catch (error) {
215
+ if (error instanceof Error && 'code' in error && ['ENOENT', 'ENOTDIR'].includes(String(error.code))) {
216
+ absent.add(path);
217
+ return;
218
+ }
219
+ throw error;
220
+ }
221
+ paths.add(path);
222
+ if (stats.isSymbolicLink()) paths.add(realpathSync(path));
223
+ if (stats.isDirectory()) for (const name of readdirSync(path)) paths.add(join(path, name));
224
+ }
225
+ const resolutions: ToolResolution[] = [];
226
+ for (const [from, name, target] of installation.resolutions) {
227
+ resolutions.push({ from, name, target });
228
+ for (const directory of createRequire(join(from, 'package.json')).resolve.paths(name) ?? []) {
229
+ namespace(directory);
230
+ const candidate = join(directory, name);
231
+ if (existsSync(candidate)) namespace(candidate);
232
+ else absent.add(candidate);
233
+ }
234
+ }
235
+ const nodes = [...paths].sort().map((path) => receiptNode(path, path, observed));
236
+ const module: EnsureBuiltProducerTool = {
237
+ kind: 'module',
238
+ name: 'installed-nx-plugin-closure',
239
+ from: root,
240
+ path: root,
241
+ physicalPath: realpathSync(root),
242
+ nodes,
243
+ missing: [...absent].sort(),
244
+ resolutions,
245
+ sha256: sha(nodes),
246
+ };
247
+ const tools: EnsureBuiltProducerTool[] = [module];
248
+ for (const name of ['nx-runtime', 'bun', 'sh', 'git', ...(needsCargo ? ['rustc', 'cargo'] : [])]) {
249
+ const candidates =
250
+ name === 'nx-runtime'
251
+ ? [process.execPath]
252
+ : (process.env.PATH ?? '').split(delimiter).map((directory) => resolve(directory || root, name));
253
+ const skipped: string[] = [];
254
+ let path: string | undefined;
255
+ for (const candidate of candidates) {
256
+ if (
257
+ (existsSync(candidate) && lstatSync(candidate).isFile()) ||
258
+ (existsSync(candidate) && lstatSync(candidate).isSymbolicLink())
259
+ ) {
260
+ path = candidate;
261
+ break;
262
+ }
263
+ skipped.push(candidate);
264
+ }
265
+ if (path === undefined) return { ok: false, detail: `Unbound producer executable ${name}` };
266
+ const physicalPath = realpathSync(path);
267
+ const entries = [...new Set([path, physicalPath])].map((entry) => receiptNode(entry, entry, observed));
268
+ tools.push({
269
+ kind: 'executable',
270
+ name,
271
+ from: root,
272
+ path,
273
+ physicalPath,
274
+ nodes: entries,
275
+ missing: skipped,
276
+ resolutions: [],
277
+ sha256: sha(entries),
278
+ });
279
+ }
280
+ const capture = movedNodes(observed, recordedTool(tools));
281
+ if (capture !== null)
282
+ return { ok: false, detail: `Producer tool/module namespace moved during capture: ${capture}` };
283
+ if (!missing(module.missing))
284
+ return { ok: false, detail: 'Producer tool/module namespace moved during capture: a missing candidate appeared' };
285
+ return { ok: true, value: { tools, nodes: observed } };
286
+ } catch (error) {
287
+ if (error instanceof Error) return { ok: false, detail: `Cannot prove producer tool closure: ${error.message}` };
288
+ throw error;
289
+ }
290
+ }
291
+ function verifyTools(tools: readonly EnsureBuiltProducerTool[]): ReceiptEvidence<readonly NodeWitness[]> {
292
+ try {
293
+ const observed: NodeWitness[] = [];
294
+ for (const tool of tools) {
295
+ if (realpathSync(tool.path) !== tool.physicalPath || !missing(tool.missing))
296
+ return { ok: false, detail: `Producer tool alias/namespace changed: ${tool.name}` };
297
+ const nodes = tool.nodes.map((node) => receiptNode(node.path, node.path, observed));
298
+ if (!same(nodes, tool.nodes) || sha(nodes) !== tool.sha256)
299
+ return { ok: false, detail: `Producer tool/module bytes changed: ${tool.name}` };
300
+ }
301
+ return nodesUnchanged(observed)
302
+ ? { ok: true, value: observed }
303
+ : { ok: false, detail: 'Producer tool nodes changed during readonly validation' };
304
+ } catch (error) {
305
+ if (error instanceof Error) return { ok: false, detail: `Cannot validate producer tools: ${error.message}` };
306
+ throw error;
307
+ }
308
+ }
309
+ export function completedProducerTasks(
310
+ graph: TaskGraph,
311
+ results: PostTasksExecutionContext['taskResults'],
312
+ ): ReceiptEvidence<readonly Task[]> {
313
+ const tasks: Task[] = [];
314
+ for (const planned of Object.values(graph.tasks)) {
315
+ const result = results[planned.id];
316
+ if (
317
+ result === undefined ||
318
+ result.code !== 0 ||
319
+ !['success', 'local-cache', 'local-cache-kept-existing', 'remote-cache'].includes(result.status)
320
+ )
321
+ return { ok: false, detail: `No actual successful completion for ${planned.id}` };
322
+ if (
323
+ result.task.hash === undefined ||
324
+ result.task.hashDetails === undefined ||
325
+ !defaultOverrides(result.task) ||
326
+ !same(result.task.outputs, planned.outputs) ||
327
+ !same(result.task.target, planned.target)
328
+ )
329
+ return { ok: false, detail: `Unbound actual hash/default target/outputs for ${planned.id}` };
330
+ tasks.push(result.task);
331
+ }
332
+ return { ok: true, value: tasks };
333
+ }
334
+ export function producerEnvironmentIdentity(inputs: EnsureBuiltProducerReceipt['inputs']): string {
335
+ return sha(
336
+ inputs.map(({ taskId, expanded, hashDetails }) => ({
337
+ taskId,
338
+ runtime: expanded.runtime,
339
+ environment: expanded.environment,
340
+ identity: hashDetails,
341
+ })),
342
+ );
343
+ }
344
+ export async function preTasksExecution(
345
+ options: ProducerReceiptsOptions | undefined,
346
+ context: PreTasksExecutionContext,
347
+ ): Promise<void> {
348
+ const targets = configured(options);
349
+ if (targets.length === 0) return;
350
+ try {
351
+ const load = createWorkspaceNxRequire(context.workspaceRoot);
352
+ const projectGraph = await load('nx/src/project-graph/project-graph').createProjectGraphAsync();
353
+ const bases = new Map<string, TargetBasis>();
354
+ for (const target of targets) {
355
+ const graph = targetGraph(context.workspaceRoot, target, projectGraph);
356
+ const outputs = producerOutputPaths(
357
+ context.workspaceRoot,
358
+ Object.values(graph.tasks),
359
+ load('nx/src/native').expandOutputs,
360
+ );
361
+ const source = captureProducerSource(context.workspaceRoot, outputs);
362
+ if (!source.ok) {
363
+ runs.set(context.id, source);
364
+ return;
365
+ }
366
+ bases.set(target, { graph, source: source.value });
367
+ }
368
+ const tools = toolsFor(context.workspaceRoot, context.nxJsonConfiguration, projectGraph, [...bases.values()]);
369
+ runs.set(
370
+ context.id,
371
+ tools.ok
372
+ ? {
373
+ ok: true,
374
+ value: {
375
+ projectGraph,
376
+ nxJson: context.nxJsonConfiguration,
377
+ targets: bases,
378
+ tools: tools.value.tools,
379
+ toolNodes: tools.value.nodes,
380
+ },
381
+ }
382
+ : tools,
383
+ );
384
+ } catch (error) {
385
+ if (error instanceof Error) runs.set(context.id, { ok: false, detail: error.message });
386
+ else throw error;
387
+ }
388
+ }
389
+ export async function postTasksExecution(
390
+ options: ProducerReceiptsOptions | undefined,
391
+ context: PostTasksExecutionContext,
392
+ ): Promise<void> {
393
+ const frame = runs.get(context.id);
394
+ runs.delete(context.id);
395
+ for (const target of configured(options)) {
396
+ const selected = parseTargetSelector(target);
397
+ if (selected === null) continue;
398
+ const targetBasis = frame?.ok === true ? frame.value.targets.get(target) : undefined;
399
+ const plannedRoot =
400
+ targetBasis === undefined
401
+ ? undefined
402
+ : Object.values(targetBasis.graph.tasks).find(
403
+ (task) => task.target.project === selected.project && task.target.target === selected.target,
404
+ );
405
+ const rootResult =
406
+ plannedRoot === undefined
407
+ ? Object.values(context.taskResults).find(
408
+ ({ task }) =>
409
+ task.target.project === selected.project &&
410
+ task.target.target === selected.target &&
411
+ (selected.configuration === undefined || task.target.configuration === selected.configuration),
412
+ )
413
+ : context.taskResults[plannedRoot.id];
414
+ if (rootResult === undefined) continue;
415
+ const refuse = (detail: string) => {
416
+ const saved = publish(context.workspaceRoot, target, { version: 1, disposition: 'refused', target, detail });
417
+ if (!saved.ok) process.stderr.write(`producerReceipts: ${target}: ${saved.detail}\n`);
418
+ process.stderr.write(`producerReceipts: ${target}: ${detail}\n`);
419
+ };
420
+ if (frame === undefined || !frame.ok) {
421
+ refuse(frame === undefined ? 'No bound producer pre-execution frame' : frame.detail);
422
+ continue;
423
+ }
424
+ const basis = frame.value.targets.get(target);
425
+ if (basis === undefined) {
426
+ refuse('No declared target pre-execution basis');
427
+ continue;
428
+ }
429
+ const completed = completedProducerTasks(basis.graph, context.taskResults);
430
+ if (!completed.ok) {
431
+ refuse(completed.detail);
432
+ continue;
433
+ }
434
+ const tasks = completed.value;
435
+ let detail: string | undefined;
436
+ const execution = movedNodes(frame.value.toolNodes, recordedTool(frame.value.tools));
437
+ if (execution !== null) {
438
+ refuse(`Producer tool/module nodes changed across actual execution: ${execution}`);
439
+ continue;
440
+ }
441
+ const load = createWorkspaceNxRequire(context.workspaceRoot);
442
+ const graph: TaskGraph = { ...basis.graph, tasks: Object.fromEntries(tasks.map((task) => [task.id, task])) };
443
+ const proof = providerInputProof(
444
+ context.workspaceRoot,
445
+ context.nxJsonConfiguration,
446
+ frame.value.projectGraph,
447
+ graph,
448
+ load,
449
+ );
450
+ if (proof.runtimeSource.kind === 'opaque') {
451
+ refuse(proof.runtimeSource.detail);
452
+ continue;
453
+ }
454
+ const files = new Map(basis.source.files.map((file) => [file.path, file]));
455
+ const inputs: EnsureBuiltProducerReceipt['inputs'][number][] = [];
456
+ for (const task of tasks) {
457
+ const expanded = proof.inputs[task.id];
458
+ const hashDetails = task.hashDetails;
459
+ if (expanded === undefined || hashDetails === undefined || expanded.files.some((path) => !files.has(path))) {
460
+ detail = `Actual FILE/hash evidence is unbound for ${task.id}`;
461
+ break;
462
+ }
463
+ const declared =
464
+ frame.value.projectGraph.nodes[task.target.project]?.data.targets?.[task.target.target]?.inputs ?? [];
465
+ inputs.push({
466
+ taskId: task.id,
467
+ overrides: task.overrides,
468
+ declared,
469
+ expanded,
470
+ hashDetails,
471
+ files: expanded.files.map((path) => {
472
+ const file = files.get(path);
473
+ if (file === undefined) throw new Error(`Lost HEAD-bound input ${path}`);
474
+ return file;
475
+ }),
476
+ });
477
+ }
478
+ if (detail !== undefined) {
479
+ refuse(detail);
480
+ continue;
481
+ }
482
+ const producer: Omit<EnsureBuiltProducerReceipt, 'outputSha256'> = {
483
+ version: 1,
484
+ target,
485
+ argv: [...context.argv],
486
+ trackedTreeClean: true,
487
+ environmentIdentity: producerEnvironmentIdentity(inputs),
488
+ inputs,
489
+ tools: frame.value.tools,
490
+ wallTimeMs: context.endTime - context.startTime,
491
+ };
492
+ if (!Number.isFinite(producer.wallTimeMs) || producer.wallTimeMs < 0) {
493
+ refuse('Invalid actual Nx execution timing');
494
+ continue;
495
+ }
496
+ const result = providerReceipt(
497
+ context.workspaceRoot,
498
+ selectorTaskId(selected),
499
+ tasks,
500
+ proof,
501
+ load('nx/src/native').expandOutputs,
502
+ basis.source,
503
+ producer,
504
+ );
505
+ if (result.disposition !== 'hit') {
506
+ refuse(result.reason.detail);
507
+ continue;
508
+ }
509
+ const census = movedNodes(frame.value.toolNodes, recordedTool(frame.value.tools));
510
+ if (census !== null) {
511
+ refuse(`Producer tools changed during post-execution product census: ${census}`);
512
+ continue;
513
+ }
514
+ const publication = publish(context.workspaceRoot, target, {
515
+ version: 1,
516
+ disposition: 'published',
517
+ receipt: result.receipt,
518
+ projectGraph: frame.value.projectGraph,
519
+ taskGraph: graph,
520
+ nxJson: frame.value.nxJson,
521
+ });
522
+ if (!publication.ok) process.stderr.write(`producerReceipts: ${target}: ${publication.detail}\n`);
523
+ }
524
+ }
525
+ /**
526
+ * Readonly consumers accept actual producer completion evidence, never their own environment/cache rows. A receipt
527
+ * that does not validate is a miss whose detail also carries the refusal of the producer's latest run, when it left one.
528
+ */
529
+ export function readProducerReceipt(root: string, target: string): ReceiptEvidence<EnsureBuiltReceipt> {
530
+ const published = validatedReceipt(root, target);
531
+ if (published.ok) return published;
532
+ const refusal = latestRefusal(root, target);
533
+ return refusal === null
534
+ ? published
535
+ : { ok: false, detail: `${published.detail}; the producer's latest run refused: ${refusal}` };
536
+ }
537
+ /** The detail of the refusal a producer run left after the last receipt, or null when none did. */
538
+ function latestRefusal(root: string, target: string): string | null {
539
+ try {
540
+ const record = typia.json.isParse<RefusedReceipt>(readFileSync(recordPath(root, target, 'refused'), 'utf8'));
541
+ return record === null || record.version !== 1 ? 'corrupt producer refusal record' : record.detail;
542
+ } catch (error) {
543
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return null;
544
+ if (error instanceof Error) return `unreadable producer refusal record: ${error.message}`;
545
+ throw error;
546
+ }
547
+ }
548
+ function validatedReceipt(root: string, target: string): ReceiptEvidence<EnsureBuiltReceipt> {
549
+ try {
550
+ const record = typia.json.isParse<PublishedReceipt>(readFileSync(recordPath(root, target, 'published'), 'utf8'));
551
+ if (record === null || record.version !== 1)
552
+ return { ok: false, detail: 'Missing/corrupt producer completion contract' };
553
+ const receipt = record.receipt;
554
+ if (
555
+ receipt.workspaceRoot !== realpathSync(root) ||
556
+ receipt.producer.version !== 1 ||
557
+ receipt.producer.target !== target ||
558
+ !receipt.producer.trackedTreeClean
559
+ )
560
+ return { ok: false, detail: 'Producer receipt target/provider identity differs' };
561
+ if (receipt.producer.environmentIdentity !== producerEnvironmentIdentity(receipt.producer.inputs))
562
+ return { ok: false, detail: 'Corrupt declared producer environment identity' };
563
+ if (
564
+ receipt.producer.inputs.length !== receipt.tasks.length ||
565
+ new Set(receipt.producer.inputs.map(({ taskId }) => taskId)).size !== receipt.tasks.length
566
+ )
567
+ return { ok: false, detail: 'Producer input/task membership differs' };
568
+ const expected = targetGraph(root, target, record.projectGraph);
569
+ if (
570
+ !same(Object.keys(expected.tasks).sort(), Object.keys(record.taskGraph.tasks).sort()) ||
571
+ Object.values(record.taskGraph.tasks).some(
572
+ (task) =>
573
+ !defaultOverrides(task) ||
574
+ !same(task.target, expected.tasks[task.id]?.target) ||
575
+ !same(task.outputs, expected.tasks[task.id]?.outputs),
576
+ )
577
+ )
578
+ return { ok: false, detail: 'Producer target/default overrides or configuration differ' };
579
+ const source = captureProducerSource(
580
+ root,
581
+ receipt.tasks.flatMap(({ outputs }) => outputs.map(({ path }) => path)),
582
+ );
583
+ if (!source.ok) return source;
584
+ if (source.value.headTree !== receipt.headTree)
585
+ return { ok: false, detail: 'Current committed tree differs from producer basis tree' };
586
+ const tools = verifyTools(receipt.producer.tools);
587
+ if (!tools.ok) return tools;
588
+ const load = createWorkspaceNxRequire(root);
589
+ const proof = providerInputProof(root, record.nxJson, record.projectGraph, record.taskGraph, load);
590
+ const files = new Map(source.value.files.map((file) => [file.path, file]));
591
+ for (const task of receipt.tasks) {
592
+ const input = receipt.producer.inputs.find(({ taskId }) => taskId === task.id);
593
+ if (
594
+ input === undefined ||
595
+ !same(input.expanded, proof.inputs[task.id]) ||
596
+ !same(input.hashDetails, record.taskGraph.tasks[task.id]?.hashDetails) ||
597
+ !same(input.overrides, record.taskGraph.tasks[task.id]?.overrides) ||
598
+ input.files.some((file) => !same(files.get(file.path), file))
599
+ )
600
+ return { ok: false, detail: `Declared FILE/input identity differs for ${task.id}` };
601
+ }
602
+ const census = providerReceipt(
603
+ root,
604
+ target,
605
+ Object.values(record.taskGraph.tasks),
606
+ proof,
607
+ load('nx/src/native').expandOutputs,
608
+ source.value,
609
+ receipt.producer,
610
+ );
611
+ if (
612
+ census.disposition !== 'hit' ||
613
+ !same(census.receipt.tasks, receipt.tasks) ||
614
+ census.receipt.producer.outputSha256 !== receipt.producer.outputSha256
615
+ )
616
+ return {
617
+ ok: false,
618
+ detail:
619
+ census.disposition === 'hit'
620
+ ? 'Public product bytes differ from actual producer receipt'
621
+ : census.reason.detail,
622
+ };
623
+ if (!nodesUnchanged(tools.value))
624
+ return { ok: false, detail: 'Producer tool namespace changed during independent product validation' };
625
+ return { ok: true, value: receipt };
626
+ } catch (error) {
627
+ if (error instanceof Error)
628
+ return { ok: false, detail: `Cannot validate producer completion receipt: ${error.message}` };
629
+ throw error;
630
+ }
631
+ }
@@ -141,7 +141,7 @@ describe('a planted runtime input failure through real Nx', () => {
141
141
  expect(await readFile(join(record, 'stderr'), 'utf8')).toBe('planted-cause\n');
142
142
  expect(await readFile(join(record, 'report'), 'utf8')).toContain('runtime input exited 3: sh -c');
143
143
  });
144
- }, 60_000);
144
+ });
145
145
  }
146
146
  });
147
147
 
@@ -81,7 +81,7 @@ describe('the real-APFS serial groups of this repository', () => {
81
81
  for (const inputs of [device, host]) {
82
82
  expect(inputs.filter((input) => input.startsWith('!') && /\btests?\b/.test(input))).toEqual([]);
83
83
  }
84
- }, 60_000);
84
+ });
85
85
 
86
86
  it('run the host group after the device group, so two real-image runners never overlap', async () => {
87
87
  const nx = await readRecord('nx.json', JSON.parse);
@@ -160,7 +160,7 @@ describe('the real-APFS serial groups of this repository', () => {
160
160
  expect(planned(['host-e2e']).filter((id) => id !== hostGate)).toEqual(planned([DEVICE_GROUP, HOST_GROUP]));
161
161
  expect(planned(['test'])).not.toContain(device);
162
162
  expect(planned(['test'])).not.toContain(host);
163
- }, 120_000);
163
+ });
164
164
 
165
165
  it('wrap exactly their tests in the 30s code-bound class, behind the 60s class that wins first', async () => {
166
166
  const config = await readRecord(NEXTEST_REPO_CONFIG_PATH, parseToml);
@@ -198,7 +198,7 @@ describe('the real-APFS serial groups of this repository', () => {
198
198
  // ordinary shard beside every other test, not in a serial group.
199
199
  expect([...owners].filter((name) => !scoped.has(name))).toEqual([]);
200
200
  expect([...owners].sort()).toEqual(['cowshed-apfs-tests', 'cowshed-cli', 'cowshed-core']);
201
- }, 60_000);
201
+ });
202
202
 
203
203
  it('pin each exact test by a function that exists at that module path', async () => {
204
204
  const groups = serialTestGroups(join(REPOSITORY, NEXTEST_REPO_CONFIG_PATH));
@@ -217,7 +217,7 @@ describe('the real-APFS serial groups of this repository', () => {
217
217
  expect(holders[0]?.path, exactName).toMatch(new RegExp(`/src/${modulePath}(?:/mod)?\\.rs$`));
218
218
  expect(holders[0]?.text, exactName).toContain('mod tests');
219
219
  }
220
- }, 60_000);
220
+ });
221
221
  });
222
222
 
223
223
  /** `path` of the repository, parsed by `parse`, which must be an object. */