@smoothbricks/nx-plugin 0.7.12 → 0.7.14

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 (89) hide show
  1. package/README.md +91 -27
  2. package/dist/.build-inputs.json +20 -12
  3. package/dist/built-output-packages.d.ts +27 -0
  4. package/dist/built-output-packages.d.ts.map +1 -0
  5. package/dist/built-output-packages.js +97 -0
  6. package/dist/cross-check-policy.d.ts +13 -1
  7. package/dist/cross-check-policy.d.ts.map +1 -1
  8. package/dist/cross-check-policy.js +13 -1
  9. package/dist/executors/bounded-exec/admission-queue.d.ts +68 -0
  10. package/dist/executors/bounded-exec/admission-queue.d.ts.map +1 -0
  11. package/dist/executors/bounded-exec/admission-queue.js +131 -0
  12. package/dist/executors/bounded-exec/cpu-grant.d.ts +14 -0
  13. package/dist/executors/bounded-exec/cpu-grant.d.ts.map +1 -0
  14. package/dist/executors/bounded-exec/cpu-grant.js +18 -0
  15. package/dist/executors/bounded-exec/cpu-pool.d.ts +1 -14
  16. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  17. package/dist/executors/bounded-exec/cpu-pool.js +2 -49
  18. package/dist/executors/bounded-exec/executor.d.ts +5 -12
  19. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  20. package/dist/executors/bounded-exec/executor.js +51 -154
  21. package/dist/executors/bounded-exec/memory-retry.d.ts +39 -0
  22. package/dist/executors/bounded-exec/memory-retry.d.ts.map +1 -0
  23. package/dist/executors/bounded-exec/memory-retry.js +33 -0
  24. package/dist/executors/bounded-exec/parent-grant.d.ts +43 -0
  25. package/dist/executors/bounded-exec/parent-grant.d.ts.map +1 -0
  26. package/dist/executors/bounded-exec/parent-grant.js +37 -0
  27. package/dist/executors/bounded-exec/peak-charge.d.ts +17 -0
  28. package/dist/executors/bounded-exec/peak-charge.d.ts.map +1 -0
  29. package/dist/executors/bounded-exec/peak-charge.js +20 -0
  30. package/dist/executors/bounded-exec/pool-environment.d.ts +25 -0
  31. package/dist/executors/bounded-exec/pool-environment.d.ts.map +1 -0
  32. package/dist/executors/bounded-exec/pool-environment.js +34 -0
  33. package/dist/executors/bounded-exec/run-cpu-pool.d.ts.map +1 -1
  34. package/dist/executors/bounded-exec/run-cpu-pool.js +1 -1
  35. package/dist/executors/bounded-exec/verdict.d.ts +3 -18
  36. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
  37. package/dist/executors/bounded-exec/verdict.js +4 -25
  38. package/dist/index.d.ts +4 -1
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +97 -31
  41. package/dist/managed-files/ci-workflow.d.ts +29 -5
  42. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  43. package/dist/managed-files/ci-workflow.js +111 -16
  44. package/dist/managed-files/context.d.ts.map +1 -1
  45. package/dist/managed-files/context.js +1 -0
  46. package/dist/managed-files/files.d.ts +3 -1
  47. package/dist/managed-files/files.d.ts.map +1 -1
  48. package/dist/managed-files/files.js +2 -0
  49. package/dist/managed-files/publish-workflow.d.ts +6 -1
  50. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  51. package/dist/managed-files/publish-workflow.js +16 -11
  52. package/dist/owned-installation.d.ts.map +1 -1
  53. package/dist/owned-installation.js +48 -14
  54. package/dist/typecheck-route.d.ts +28 -0
  55. package/dist/typecheck-route.d.ts.map +1 -0
  56. package/dist/typecheck-route.js +109 -0
  57. package/dist/workspace-manifest.d.ts +50 -5
  58. package/dist/workspace-manifest.d.ts.map +1 -1
  59. package/executors.json +10 -0
  60. package/managed/raw/patches/ttsc@0.34.1.patch +93 -8
  61. package/managed/raw/tooling/direnv/apple-developer.sh +8 -1
  62. package/managed/raw/tooling/direnv/compiler-variables.sh +1 -1
  63. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +4 -2
  64. package/managed/raw/tooling/direnv/secret-references.ts +19 -5
  65. package/managed/raw/tooling/git-hooks/pre-push.sh +20 -10
  66. package/managed/templates/github/actions/forgejo-artifact.cjs +9 -9
  67. package/managed/templates/github/actions/setup-devenv/action.yml +53 -0
  68. package/package.json +2 -2
  69. package/src/built-output-packages.ts +125 -0
  70. package/src/cross-check-policy.ts +14 -1
  71. package/src/executors/bounded-exec/admission-queue.ts +163 -0
  72. package/src/executors/bounded-exec/cpu-grant.ts +32 -0
  73. package/src/executors/bounded-exec/cpu-pool.ts +2 -33
  74. package/src/executors/bounded-exec/executor.ts +60 -201
  75. package/src/executors/bounded-exec/memory-retry.ts +63 -0
  76. package/src/executors/bounded-exec/parent-grant.ts +75 -0
  77. package/src/executors/bounded-exec/peak-charge.ts +25 -0
  78. package/src/executors/bounded-exec/pool-environment.ts +45 -0
  79. package/src/executors/bounded-exec/run-cpu-pool.ts +2 -1
  80. package/src/executors/bounded-exec/verdict.ts +7 -35
  81. package/src/index.ts +105 -31
  82. package/src/managed-files/ci-workflow.ts +143 -16
  83. package/src/managed-files/context.ts +1 -0
  84. package/src/managed-files/files.ts +5 -0
  85. package/src/managed-files/publish-workflow.ts +26 -10
  86. package/src/owned-installation.ts +63 -14
  87. package/src/typecheck-route.ts +64 -0
  88. package/src/workspace-manifest.ts +56 -5
  89. package/test-timings.json +141 -139
@@ -0,0 +1,125 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ import type {
5
+ CreateDependenciesContext,
6
+ CreateNodesContextV2,
7
+ ProjectGraphExternalNode,
8
+ RawProjectGraphDependency,
9
+ } from 'nx/src/devkit-exports.js';
10
+ import { hashArray } from 'nx/src/hasher/file-hasher.js';
11
+ import { readBunLockFile } from 'nx/src/plugins/js/lock-file/bun-parser.js';
12
+ import { getLockFileDependencies, getLockFileName, getLockFileNodes } from 'nx/src/plugins/js/lock-file/lock-file.js';
13
+ import { jsPluginConfig } from 'nx/src/plugins/js/utils/config.js';
14
+ import { detectPackageManager, type PackageManager } from 'nx/src/utils/package-manager.js';
15
+ import { nxVersion } from 'nx/src/utils/versions.js';
16
+
17
+ import { isRecord } from './type-guards.js';
18
+
19
+ /**
20
+ * Built-output packages: lockfile package nodes that carry no version identity for the packages a workspace keys by
21
+ * what its tasks run.
22
+ *
23
+ * Nx keys a task on an npm package through the package's external node, hashing the integrity the lockfile records for
24
+ * it (`hash_external`). A `^` input adds the node of every package a dependency project declares or imports, from any
25
+ * of its files, so a version bump of one package re-keys every task whose dependency closure reaches an importer of it.
26
+ * That is wrong for a package the workspace already keys by its bytes where a task runs them, as a consumer keys the Nx
27
+ * plugin per executor and module closure. The plugin's `builtOutputPackages` option names such packages.
28
+ *
29
+ * The workspace turns Nx's own lockfile analysis off (`pluginsConfig["@nx/js"].analyzeLockfile: false`): Nx merges its
30
+ * default plugin's nodes after every configured plugin's, so they would replace these. This plugin then publishes the
31
+ * nodes and package edges Nx's own parser makes (`getLockFileNodes`, `getLockFileDependencies`), every node of a named
32
+ * package with a `data.hash` that names the package alone. Only that hash differs from Nx's graph: names, versions and
33
+ * edges stay, so a task that reaches a named package still keys each of its dependencies by its own integrity.
34
+ */
35
+
36
+ /** The `data.hash` of a named package's nodes: the package's name, the one identity Nx's graph keys it by. */
37
+ export function builtOutputHash(packageName: string): string {
38
+ return `built-output:${packageName}`;
39
+ }
40
+
41
+ /** One read of the lockfile and Nx's parse of it. */
42
+ interface LockfileRead {
43
+ readonly packageManager: PackageManager;
44
+ readonly lockFile: string;
45
+ readonly contents: string;
46
+ readonly hash: string;
47
+ readonly nodes: Record<string, ProjectGraphExternalNode>;
48
+ readonly keyMap: Map<string, unknown>;
49
+ }
50
+
51
+ /**
52
+ * The read whose nodes createNodes published last. An install can rewrite the lockfile between the two hooks, so
53
+ * createDependencies links the nodes the graph holds, as Nx's own lockfile plugin does.
54
+ */
55
+ let published: LockfileRead | undefined;
56
+
57
+ /** The packages the option names, or null when it names none. */
58
+ function namedPackages(options: unknown): ReadonlySet<string> | null {
59
+ if (!isRecord(options) || options.builtOutputPackages === undefined) return null;
60
+ const names: unknown = options.builtOutputPackages;
61
+ if (!Array.isArray(names) || !names.every((name): name is string => typeof name === 'string' && name.length > 0)) {
62
+ throw new Error('builtOutputPackages must be a list of package names');
63
+ }
64
+ return names.length === 0 ? null : new Set(names);
65
+ }
66
+
67
+ /** The workspace's lockfile, as Nx's own lockfile plugin reads it, and Nx's parse of it. */
68
+ function readLockfile(context: CreateNodesContextV2): LockfileRead {
69
+ const packageManager = detectPackageManager(context.workspaceRoot);
70
+ const lockFile = getLockFileName(packageManager);
71
+ const path = join(context.workspaceRoot, lockFile);
72
+ if (!existsSync(path)) throw new Error(`builtOutputPackages names packages, but ${path} does not exist`);
73
+ const contents = packageManager === 'bun' ? readBunLockFile(path) : readFileSync(path, 'utf-8');
74
+ const hash = hashArray([nxVersion, contents]);
75
+ if (published?.hash === hash) return published;
76
+ const { nodes, keyMap } = getLockFileNodes(packageManager, lockFile, contents, hash, context);
77
+ return { packageManager, lockFile, contents, hash, nodes, keyMap };
78
+ }
79
+
80
+ /**
81
+ * The lockfile's package nodes, each of a named package hashed by {@link builtOutputHash}; none when the option names
82
+ * no package. Refuses while Nx's own nodes would replace them, and for a named package the lockfile installs nowhere.
83
+ */
84
+ export function builtOutputLockfileNodes(
85
+ options: unknown,
86
+ context: CreateNodesContextV2,
87
+ ): Record<string, ProjectGraphExternalNode> {
88
+ const packages = namedPackages(options);
89
+ if (packages === null) return {};
90
+ if (jsPluginConfig(context.nxJsonConfiguration).analyzeLockfile) {
91
+ throw new Error(
92
+ `builtOutputPackages (${[...packages].join(', ')}) needs nx.json pluginsConfig["@nx/js"].analyzeLockfile ` +
93
+ "set to false: Nx merges its own lockfile nodes after this plugin's, and they would key each of these " +
94
+ 'packages by its version',
95
+ );
96
+ }
97
+ const read = readLockfile(context);
98
+ published = read;
99
+ const nodes: Record<string, ProjectGraphExternalNode> = {};
100
+ const found = new Set<string>();
101
+ for (const [name, node] of Object.entries(read.nodes)) {
102
+ const packageName = node.data.packageName;
103
+ if (!packages.has(packageName)) {
104
+ nodes[name] = node;
105
+ continue;
106
+ }
107
+ found.add(packageName);
108
+ nodes[name] = { ...node, data: { ...node.data, hash: builtOutputHash(packageName) } };
109
+ }
110
+ const absent = [...packages].filter((name) => !found.has(name));
111
+ if (absent.length > 0) {
112
+ throw new Error(`builtOutputPackages names ${absent.join(', ')}, which ${read.lockFile} installs nowhere`);
113
+ }
114
+ return nodes;
115
+ }
116
+
117
+ /** The package edges Nx's parser reads from the lockfile whose nodes the graph holds; none when no package is named. */
118
+ export function builtOutputLockfileDependencies(
119
+ options: unknown,
120
+ context: CreateDependenciesContext,
121
+ ): RawProjectGraphDependency[] {
122
+ if (namedPackages(options) === null) return [];
123
+ const read = published ?? readLockfile(context);
124
+ return getLockFileDependencies(read.packageManager, read.lockFile, read.contents, read.hash, context, read.keyMap);
125
+ }
@@ -191,17 +191,30 @@ export const CARGO_LINT_CLIPPY_COMMAND = cargoFrozen(
191
191
  /** Root `package.json` script name, in the repo's `verb:qualifier` style. */
192
192
  export const CROSS_CHECK_SCRIPT_NAME = 'check:linux';
193
193
 
194
+ /**
195
+ * The caller variables a declared command keeps: cowshed clears the environment of every command a land runs, its
196
+ * gate and its push among them, and passes these on when the caller has them, with a `PATH`
197
+ * (specs/cowshed/02_workspaces.md, "The declared commands' environment"). The managed pre-push hook spells the same
198
+ * list in shell, and a test holds the two equal.
199
+ */
200
+ export const DECLARED_COMMAND_IDENTITY = ['HOME', 'USER', 'LOGNAME', 'TERM', 'LANG', 'SSH_AUTH_SOCK'] as const;
201
+
194
202
  /**
195
203
  * The developer entry point: one command on macOS that reports what CI's Linux
196
204
  * job would. A plain Nx run, because every managed devenv shell carries the
197
205
  * cross toolchain; the land gate's Nx graph holds the same target.
198
206
  *
207
+ * It runs from the environment the land gate and the pre-push probe run in: the identity variables and `PATH` alone,
208
+ * with the checkout's devenv entered over them. Run in the caller's shell, it keyed every cargo task on whatever that
209
+ * shell carried and the checkout does not declare (an `AR=ar` from a parent directory's devenv moved the toolchain
210
+ * input), so its verdict was one the probe never asks for.
211
+ *
199
212
  * Deliberately NOT `--quiet`. The pre-push gate is a probe: it consults the Nx
200
213
  * cache and refuses a push that has no hit, never starting a compile of its own.
201
214
  * The clippy behind this script is unbounded, so a silent terminal is
202
215
  * indistinguishable from a hang.
203
216
  */
204
- export const CROSS_CHECK_SCRIPT_COMMAND = `nx run-many -t ${CARGO_CROSS_LINT_TARGET}`;
217
+ export const CROSS_CHECK_SCRIPT_COMMAND = `env -i ${DECLARED_COMMAND_IDENTITY.map((name) => `${name}="$${name}"`).join(' ')} PATH="$PATH" direnv exec "$PWD" nx run-many -t ${CARGO_CROSS_LINT_TARGET}`;
205
218
 
206
219
  /**
207
220
  * A cross-built test archive and the target that EXECUTES it, per foreign
@@ -0,0 +1,163 @@
1
+ import { admissionWaitMs, type BoundEvent, NO_ADMISSION_WAIT, stepAdmissionWait } from './bounds.js';
2
+ import { HANG_CAPTURE_MS } from './hang-diagnostics.js';
3
+ import { MBX_QUEUE_POLL_MS, type MbxQueuedRequest, snapshotMbxQueue } from './mbx-queue.js';
4
+ import { type AdmissionQueueWait, describeAdmissionQueue } from './verdict.js';
5
+
6
+ /**
7
+ * What a Cargo or reserved leaf waits in: mbx's admission queue. The snapshots of it are said on stderr and decide
8
+ * whether the wait is credited against the idle bound, so they can fail a run and never change a command that passes:
9
+ * the key leaves this out (README, "Bounded exec key"). The bounds themselves (bounds.ts) stay keyed.
10
+ */
11
+
12
+ /** The mbx host a snapshot runs `mbx` through; the real one unless a test injects another. */
13
+ export type QueueHost = Parameters<typeof snapshotMbxQueue>[3];
14
+
15
+ /** What the run tells its observation of itself. */
16
+ export interface ObservationHost {
17
+ /** The run is over: it settled or a bound expired. Nothing more is observed or credited. */
18
+ over(): boolean;
19
+ /** The command's pid, once it is spawned. */
20
+ pid(): number | undefined;
21
+ /** The environment the command runs with, through which mbx finds its session. */
22
+ environment(): NodeJS.ProcessEnv;
23
+ /** Told, never thrown. */
24
+ tell(text: string): void;
25
+ /** The bounds' next event. */
26
+ step(event: BoundEvent): void;
27
+ /** Whether the command is running a test. */
28
+ testing(): boolean;
29
+ readonly queueHost: QueueHost | undefined;
30
+ }
31
+
32
+ /** One run's view of the admission queue its leaf waits in. */
33
+ export class AdmissionObservation {
34
+ /** mbx granted the leaf its cores. */
35
+ admitted = false;
36
+ private wait = NO_ADMISSION_WAIT;
37
+ private requests: readonly MbxQueuedRequest[] = [];
38
+ /**
39
+ * Why the last admission snapshot failed, while the one after it has not succeeded; null otherwise. A snapshot only
40
+ * decides whether waiting on mbx admission is credited against the idle bound, so a failed one withholds that credit
41
+ * and ends nothing: the bounds decide, and an idle expiry names it.
42
+ */
43
+ private failure: string | null = null;
44
+ /** When the last successful snapshot completed (`Date.now()`): credit runs to it and no further. */
45
+ private confirmedAt: number | null = null;
46
+ private readonly abort = new AbortController();
47
+ private timer: NodeJS.Timeout | undefined;
48
+ private snapshot: Promise<void> | null = null;
49
+ private lastDiagnostic = '';
50
+ private lastDiagnosticAt: number | null = null;
51
+ private lastSnapshotDiagnostics = '';
52
+
53
+ constructor(private readonly host: ObservationHost) {}
54
+
55
+ /** Why the last snapshot failed, while the one after it has not succeeded. */
56
+ get unconfirmed(): string | null {
57
+ return this.failure;
58
+ }
59
+
60
+ /**
61
+ * A reserved leaf's own request on its run's endpoint is its admission wait; a Cargo leaf's comes from mbx's report.
62
+ * `reserved` is whether the leaf holds a reservation of its own.
63
+ */
64
+ queueWait(reserved: boolean): AdmissionQueueWait | null {
65
+ return this.admitted || (this.requests.length === 0 && !reserved)
66
+ ? null
67
+ : { waitedMs: admissionWaitMs(this.wait, performance.now()), requests: this.requests };
68
+ }
69
+
70
+ /** A reserved leaf's request began to wait on its run's endpoint. */
71
+ waiting(): void {
72
+ this.wait = stepAdmissionWait(this.wait, { kind: 'snapshot', at: performance.now(), waiting: true });
73
+ }
74
+
75
+ /** Only mbx's activity report says whether a Cargo leaf's compiler or test waits in the pool: poll it. */
76
+ poll(): void {
77
+ this.timer = setInterval(() => {
78
+ void this.refresh(false);
79
+ }, MBX_QUEUE_POLL_MS);
80
+ void this.refresh(false);
81
+ }
82
+
83
+ /** The run ended: the wait stops counting and no snapshot is taken or credited again. */
84
+ stop(): void {
85
+ this.wait = stepAdmissionWait(this.wait, { kind: 'stop', at: performance.now() });
86
+ clearInterval(this.timer);
87
+ this.abort.abort();
88
+ }
89
+
90
+ /** The snapshot in flight, if any, has finished. */
91
+ async idle(): Promise<void> {
92
+ await this.snapshot;
93
+ }
94
+
95
+ private unconfirm(detail: string): void {
96
+ if (this.host.over() || this.abort.signal.aborted) return;
97
+ if (this.failure !== detail) {
98
+ this.host.tell(
99
+ `bounded-exec: mbx admission snapshot failed: ${detail}; admission is unconfirmed, so this wait earns no idle credit until a snapshot succeeds\n`,
100
+ );
101
+ }
102
+ this.failure = detail;
103
+ this.requests = [];
104
+ this.wait = stepAdmissionWait(this.wait, { kind: 'snapshot', at: performance.now(), waiting: false });
105
+ // The wait since the last confirmed snapshot is unconfirmed: the idle bound resumes from that snapshot.
106
+ this.host.step({
107
+ kind: 'admission-queue',
108
+ at: this.confirmedAt ?? Date.now(),
109
+ waiting: false,
110
+ testing: this.host.testing(),
111
+ });
112
+ }
113
+
114
+ /** Take a snapshot; `fresh` drains an older poll first. */
115
+ async refresh(fresh: boolean): Promise<void> {
116
+ if (fresh && this.snapshot !== null) await this.snapshot;
117
+ const pid = this.host.pid();
118
+ if (this.host.over() || this.abort.signal.aborted || pid === undefined) return;
119
+ this.snapshot ??= (async () => {
120
+ const snapshot = await snapshotMbxQueue(pid, this.host.environment(), this.abort.signal, this.host.queueHost);
121
+ if (this.host.over() || this.abort.signal.aborted) return;
122
+ if (!snapshot.ok) {
123
+ this.unconfirm(snapshot.detail);
124
+ return;
125
+ }
126
+ const diagnostics = snapshot.diagnostics?.join('; ') ?? '';
127
+ if (diagnostics !== '' && diagnostics !== this.lastSnapshotDiagnostics) {
128
+ this.host.tell(`bounded-exec: ${diagnostics}\n`);
129
+ }
130
+ this.lastSnapshotDiagnostics = diagnostics;
131
+ const waiting = snapshot.requests.length > 0;
132
+ const observedAt = Date.now();
133
+ const observedWaitAt = performance.now();
134
+ this.wait = stepAdmissionWait(this.wait, { kind: 'snapshot', at: observedWaitAt, waiting });
135
+ this.failure = null;
136
+ this.confirmedAt = observedAt;
137
+ if (waiting) {
138
+ this.requests = snapshot.requests;
139
+ const positions = JSON.stringify(snapshot.requests);
140
+ if (
141
+ positions !== this.lastDiagnostic ||
142
+ this.lastDiagnosticAt === null ||
143
+ Date.now() - this.lastDiagnosticAt >= HANG_CAPTURE_MS
144
+ ) {
145
+ const waitedMs = admissionWaitMs(this.wait, observedWaitAt);
146
+ this.host.tell(`cowshed: mbx ${describeAdmissionQueue({ waitedMs, requests: snapshot.requests })}\n`);
147
+ this.lastDiagnostic = positions;
148
+ this.lastDiagnosticAt = Date.now();
149
+ }
150
+ } else {
151
+ this.lastDiagnostic = '';
152
+ }
153
+ this.host.step({ kind: 'admission-queue', at: observedAt, waiting, testing: this.host.testing() });
154
+ })()
155
+ .catch((error: unknown) => {
156
+ this.unconfirm(error instanceof Error ? error.message : String(error));
157
+ })
158
+ .finally(() => {
159
+ this.snapshot = null;
160
+ });
161
+ await this.snapshot;
162
+ }
163
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The CPU grant a run's record names (verdict.ts keeps the record; this is what it says of the pool). The tokens are the
3
+ * parallelism the record's peak was measured under, which the task's next run reads (peak-charge.ts) to charge that
4
+ * peak in proportion to the parallelism it is lent. It is scheduling metadata: a record that names none, or names one
5
+ * that is malformed, changes no verdict a passing run records.
6
+ */
7
+ export interface CpuGrantRecord {
8
+ readonly tokens: number;
9
+ readonly want: number;
10
+ readonly waitedMs: number;
11
+ }
12
+
13
+ /** What a record's `cpu` field holds: no grant, a grant, or something that is no grant. */
14
+ export function parseCpuGrant(value: unknown): CpuGrantRecord | undefined | 'malformed' {
15
+ if (value === undefined) {
16
+ return undefined;
17
+ }
18
+ if (typeof value !== 'object' || value === null) {
19
+ return 'malformed';
20
+ }
21
+ const tokens: unknown = Reflect.get(value, 'tokens');
22
+ const want: unknown = Reflect.get(value, 'want');
23
+ const waitedMs: unknown = Reflect.get(value, 'waitedMs');
24
+ if (
25
+ !(typeof tokens === 'number' && Number.isSafeInteger(tokens) && tokens >= 1) ||
26
+ !(typeof want === 'number' && Number.isSafeInteger(want) && want >= 1) ||
27
+ !(typeof waitedMs === 'number' && Number.isFinite(waitedMs) && waitedMs >= 0)
28
+ ) {
29
+ return 'malformed';
30
+ }
31
+ return { tokens, want, waitedMs };
32
+ }
@@ -10,7 +10,7 @@ import { holdLease, type Unleased } from './gateway-lease.js';
10
10
  import { type LiveUsageReading, type RunMemory, readLiveUsage } from './host-memory.js';
11
11
  import { type CpuLeaseProgress, type CpuLeaseQueued, CpuLeaseWait, HEARTBEAT_MS } from './lease-wait.js';
12
12
  import { admit } from './pool-admission.js';
13
- import { CPU_TOKENS_ENV, parseInheritedTokens } from './runner-sizing.js';
13
+ import { type InheritedCpuPool, poolEnvironment } from './pool-environment.js';
14
14
 
15
15
  /**
16
16
  * A CPU pool: the tokens a process lends the runners it starts, held live rather than inherited as a
@@ -38,16 +38,6 @@ import { CPU_TOKENS_ENV, parseInheritedTokens } from './runner-sizing.js';
38
38
  * frees the slot. A Cargo reading the fifo and a nested runner holding a socket grant so share one count.
39
39
  */
40
40
 
41
- /** The environment name a child reads its parent's pool endpoint from; its count is `CPU_TOKENS_ENV`. */
42
- export const CPU_POOL_ENV = 'BOUNDED_EXEC_CPU_POOL';
43
-
44
- /** An inherited pool descriptor; only a grant from its endpoint proves a live allocation. */
45
- export interface InheritedCpuPool {
46
- readonly socket: string;
47
- /** The count the parent names beside its endpoint. */
48
- readonly tokens: number;
49
- }
50
-
51
41
  /** A running pool: the environment a child inherits to reach it, and how to close it. */
52
42
  export interface CpuPool {
53
43
  /** The endpoint, the count the pool actually holds, and its make jobserver fifo. */
@@ -142,20 +132,6 @@ interface Waiter {
142
132
  /** One framed reply line. The newline is the framing; every reply goes through here. */
143
133
  const frame = (reply: CpuPoolReply): string => `${stringifyReply(reply)}\n`;
144
134
 
145
- /**
146
- * The inherited descriptor, or null when malformed or absent. A missing or bare count, or an empty
147
- * or NUL-bearing endpoint, proves no allocation; the count is a positive whole number. A valid
148
- * descriptor still needs a live endpoint grant.
149
- */
150
- export function readInheritedCpuPool(environment: Readonly<NodeJS.ProcessEnv>): InheritedCpuPool | null {
151
- const socket = environment[CPU_POOL_ENV];
152
- const tokens = parseInheritedTokens(environment[CPU_TOKENS_ENV]);
153
- if (socket === undefined || socket.length === 0 || socket.includes('\0') || tokens === null) {
154
- return null;
155
- }
156
- return { socket, tokens };
157
- }
158
-
159
135
  /**
160
136
  * Tokens a parent pool lent, held until released, or why there are none. `charged` is the bytes the pool charged the
161
137
  * grant, null from a pool that charges none. `oversized` names the run's memory when the child's charge alone exceeds
@@ -791,17 +767,10 @@ export async function createCpuPool(
791
767
  if (closing) {
792
768
  return abort(CLOSED_WHILE_MADE);
793
769
  }
794
- // Cargo and make read the fifo from here; `-j` with a jobserver names no count of its own.
795
- const jobserverFlags = `-j --jobserver-auth=fifo:${fifoPath}`;
796
770
  return {
797
771
  ok: true,
798
772
  pool: {
799
- environment: {
800
- [CPU_POOL_ENV]: socketPath,
801
- [CPU_TOKENS_ENV]: String(tokens),
802
- CARGO_MAKEFLAGS: jobserverFlags,
803
- MAKEFLAGS: jobserverFlags,
804
- },
773
+ environment: poolEnvironment(socketPath, tokens, fifoPath),
805
774
  close: shutdown,
806
775
  },
807
776
  };