@gadicc/loom 2.2.0 → 2.3.0

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 (39) hide show
  1. package/.loom-source-manifest.json +6 -1
  2. package/README.md +6 -4
  3. package/db/testing.d.ts +38 -1
  4. package/db/testing.js +66 -18
  5. package/db/testingTiming.js +45 -0
  6. package/esm/src/cli/mod.d.ts.map +1 -1
  7. package/esm/src/cli/mod.js +46 -0
  8. package/esm/src/cli/mod.js.map +1 -1
  9. package/esm/src/cli/testResourceCommand.d.ts +9 -0
  10. package/esm/src/cli/testResourceCommand.d.ts.map +1 -0
  11. package/esm/src/cli/testResourceCommand.js +33 -0
  12. package/esm/src/cli/testResourceCommand.js.map +1 -0
  13. package/esm/src/cli/testResourceHost.d.ts +36 -0
  14. package/esm/src/cli/testResourceHost.d.ts.map +1 -0
  15. package/esm/src/cli/testResourceHost.js +207 -0
  16. package/esm/src/cli/testResourceHost.js.map +1 -0
  17. package/esm/src/cli/testResourceLaunch.d.ts +22 -0
  18. package/esm/src/cli/testResourceLaunch.d.ts.map +1 -0
  19. package/esm/src/cli/testResourceLaunch.js +189 -0
  20. package/esm/src/cli/testResourceLaunch.js.map +1 -0
  21. package/esm/src/cli/testResourcePolicy.d.ts +24 -0
  22. package/esm/src/cli/testResourcePolicy.d.ts.map +1 -0
  23. package/esm/src/cli/testResourcePolicy.js +103 -0
  24. package/esm/src/cli/testResourcePolicy.js.map +1 -0
  25. package/esm/src/cli/testVitestRunner.d.ts +28 -0
  26. package/esm/src/cli/testVitestRunner.d.ts.map +1 -0
  27. package/esm/src/cli/testVitestRunner.js +159 -0
  28. package/esm/src/cli/testVitestRunner.js.map +1 -0
  29. package/package.json +2 -2
  30. package/skills/loom-db/SKILL.md +5 -2
  31. package/skills/loom-db/references/test-boundaries.md +76 -0
  32. package/skills/loom-scaffold/SKILL.md +4 -0
  33. package/skills/loom-scaffold/references/greenfield-workflow.md +25 -2
  34. package/source/src/cli/mod.ts +70 -0
  35. package/source/src/cli/testResourceCommand.ts +49 -0
  36. package/source/src/cli/testResourceHost.ts +299 -0
  37. package/source/src/cli/testResourceLaunch.ts +257 -0
  38. package/source/src/cli/testResourcePolicy.ts +135 -0
  39. package/source/src/cli/testVitestRunner.ts +222 -0
@@ -0,0 +1,135 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ /** Static online physical-core identity; inherited affinity is deliberately absent. */
4
+ export interface TestCpuCore {
5
+ socket: number;
6
+ core: number;
7
+ cpus: readonly number[];
8
+ }
9
+
10
+ /** Experimental v1 selection, computed in memory without creating host state. */
11
+ export interface TestCpuSelection {
12
+ spec: "loom-cpu-selection-v1";
13
+ epoch: string;
14
+ reservedCpus: number[];
15
+ testCpus: number[];
16
+ reservedCores: number;
17
+ topology: "physical" | "logical-fallback";
18
+ }
19
+
20
+ /** Parses Linux CPU lists strictly and returns normalized ascending indices. */
21
+ export function parseCpuList(text: string): number[] {
22
+ const result = new Set<number>();
23
+ for (const part of text.trim().split(",")) {
24
+ const match = /^(\d+)(?:-(\d+))?$/.exec(part);
25
+ if (!match) throw new Error("Invalid CPU list");
26
+ const start = Number(match[1]);
27
+ const end = Number(match[2] ?? match[1]);
28
+ if (end < start || end > 1_000_000) throw new Error("Invalid CPU range");
29
+ for (let cpu = start; cpu <= end; cpu++) result.add(cpu);
30
+ }
31
+ return [...result].sort((a, b) => a - b);
32
+ }
33
+
34
+ /** Stable selection shared by projects; private masks never choose substitute cores. */
35
+ export function selectTestCpus(
36
+ online: readonly number[],
37
+ inherited: readonly number[],
38
+ physical: readonly TestCpuCore[] | undefined,
39
+ reserve?: number,
40
+ ): TestCpuSelection {
41
+ const normalized = parseCpuList(online.join(","));
42
+ const onlineSet = new Set(normalized);
43
+ const cores = physical
44
+ ? physical.map((item) => ({
45
+ socket: item.socket,
46
+ core: item.core,
47
+ cpus: [...item.cpus].sort((a, b) => a - b),
48
+ }))
49
+ : normalized.map((cpu) => ({ socket: 0, core: cpu, cpus: [cpu] }));
50
+ cores.sort(
51
+ (a, b) => a.socket - b.socket || a.core - b.core || a.cpus[0] - b.cpus[0],
52
+ );
53
+ const covered = cores.flatMap((item) => item.cpus);
54
+ if (
55
+ cores.some(
56
+ (item) =>
57
+ !Number.isInteger(item.socket) ||
58
+ !Number.isInteger(item.core) ||
59
+ item.cpus.length === 0,
60
+ ) ||
61
+ covered.length !== normalized.length ||
62
+ new Set(covered).size !== covered.length ||
63
+ covered.some((cpu) => !onlineSet.has(cpu))
64
+ ) {
65
+ throw new Error("Physical topology must partition the online CPU set");
66
+ }
67
+ const count = reserve ?? (cores.length <= 2 ? 0 : cores.length < 8 ? 1 : 2);
68
+ if (!Number.isSafeInteger(count) || count < 0 || count >= cores.length) {
69
+ throw new Error("Reservation must leave at least one online core");
70
+ }
71
+ const reservedCpus = cores
72
+ .slice(0, count)
73
+ .flatMap((item) => item.cpus)
74
+ .sort((a, b) => a - b);
75
+ const reserved = new Set(reservedCpus);
76
+ const testCpus = [...new Set(inherited)]
77
+ .filter((cpu) => onlineSet.has(cpu) && !reserved.has(cpu))
78
+ .sort((a, b) => a - b);
79
+ if (testCpus.length === 0) {
80
+ throw new Error(
81
+ "Inherited CPU restrictions leave no test CPUs after exclusion",
82
+ );
83
+ }
84
+ const spec = "loom-cpu-selection-v1";
85
+ // No inherited mask, dynamic frequency, memory, or worker choice in the epoch.
86
+ const epoch = createHash("sha256")
87
+ .update(
88
+ JSON.stringify({
89
+ spec,
90
+ online: normalized,
91
+ cores,
92
+ reserve: reserve ?? null,
93
+ }),
94
+ )
95
+ .digest("hex");
96
+ return {
97
+ spec,
98
+ epoch,
99
+ reservedCpus,
100
+ testCpus,
101
+ reservedCores: count,
102
+ topology: physical ? "physical" : "logical-fallback",
103
+ };
104
+ }
105
+
106
+ /** A cgroup quota ceiling, or undefined when any applicable limit is unknown. */
107
+ export function testCpuQuota(
108
+ texts: readonly (string | undefined)[],
109
+ ): number | undefined {
110
+ let capacity = Infinity;
111
+ for (const text of texts) {
112
+ if (text === undefined) return undefined;
113
+ const fields = text.trim().split(/\s+/);
114
+ if (fields.length !== 2 || !/^\d+$/.test(fields[1])) return undefined;
115
+ const period = Number(fields[1]);
116
+ if (!Number.isSafeInteger(period) || period <= 0) return undefined;
117
+ if (fields[0] === "max") continue;
118
+ if (!/^\d+$/.test(fields[0])) return undefined;
119
+ const quota = Number(fields[0]);
120
+ if (!Number.isSafeInteger(quota) || quota <= 0) return undefined;
121
+ capacity = Math.min(capacity, quota / period);
122
+ }
123
+ return texts.length ? capacity : undefined;
124
+ }
125
+
126
+ /** Local desktop reserve; CI does not use this floor. */
127
+ export function testMemoryHeadroom(capacityBytes: number): number {
128
+ if (!Number.isFinite(capacityBytes) || capacityBytes <= 0) {
129
+ throw new Error("Memory capacity must be positive and finite");
130
+ }
131
+ return Math.min(
132
+ 2 * 1024 ** 3,
133
+ Math.max(256 * 1024 ** 2, capacityBytes * 0.1),
134
+ );
135
+ }
@@ -0,0 +1,222 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { createRequire } from "node:module";
3
+ import { join } from "node:path";
4
+ import process from "node:process";
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ /** Minimal supported resolved config; Vitest stays an optional consumer dependency. */
8
+ interface ManagedConfig {
9
+ maxWorkers?: number;
10
+ pool?: unknown;
11
+ watch?: boolean;
12
+ projects?: unknown;
13
+ browser?: { enabled?: boolean };
14
+ typecheck?: { enabled?: boolean };
15
+ passWithNoTests?: boolean;
16
+ standalone?: boolean;
17
+ ui?: boolean;
18
+ api?: unknown;
19
+ mergeReports?: unknown;
20
+ inspect?: unknown;
21
+ inspectBrk?: unknown;
22
+ }
23
+
24
+ interface ManagedVitest {
25
+ config: ManagedConfig;
26
+ projects: { config: ManagedConfig }[];
27
+ start: (filters: string[]) => Promise<{
28
+ testModules: { state: () => string }[];
29
+ unhandledErrors: unknown[];
30
+ }>;
31
+ close: () => Promise<void>;
32
+ }
33
+
34
+ interface VitestApi {
35
+ parseCLI: (argv: string[]) => {
36
+ filter: string[];
37
+ options: Record<string, unknown>;
38
+ };
39
+ createVitest: (...args: unknown[]) => Promise<ManagedVitest>;
40
+ FilesNotFoundError?: new (...args: never[]) => Error;
41
+ TestsNotFoundError?: new (...args: never[]) => Error;
42
+ }
43
+
44
+ /** Location used by the CLI to launch the same source or emitted runner module. */
45
+ export const managedVitestModuleURL = import.meta.url;
46
+
47
+ /** Restrict a single, already resolved config before Vitest creates its pool. */
48
+ export function clampResolvedTestWorkers(
49
+ config: ManagedConfig,
50
+ ceiling: number,
51
+ ): number {
52
+ if (!Number.isSafeInteger(ceiling) || ceiling < 1)
53
+ throw new Error("Invalid worker ceiling");
54
+ if (config.pool !== "threads" && config.pool !== "forks")
55
+ throw new Error("Managed tests support only threads and forks pools");
56
+ const api = config.api;
57
+ // Vitest resolves its disabled API to internal middleware metadata. Only
58
+ // a listening/unknown API mode is unsupported, not that ordinary default.
59
+ const listeningApi =
60
+ api !== undefined &&
61
+ api !== false &&
62
+ api !== null &&
63
+ (typeof api !== "object" ||
64
+ !("middlewareMode" in api) ||
65
+ api.middlewareMode !== true ||
66
+ ("port" in api && api.port !== undefined));
67
+ if (
68
+ config.watch ||
69
+ config.standalone ||
70
+ config.ui ||
71
+ listeningApi ||
72
+ config.mergeReports ||
73
+ config.inspect ||
74
+ config.inspectBrk ||
75
+ config.projects ||
76
+ config.browser?.enabled ||
77
+ config.typecheck?.enabled
78
+ ) {
79
+ throw new Error(
80
+ "Managed tests currently require a single Node test project without watch, UI/API, standalone, merging, inspectors, browser or typecheck pools",
81
+ );
82
+ }
83
+ const existing = config.maxWorkers;
84
+ if (
85
+ existing !== undefined &&
86
+ (!Number.isSafeInteger(existing) || existing < 1)
87
+ ) {
88
+ throw new Error("Unsupported resolved Vitest worker limit");
89
+ }
90
+ const selected = Math.min(ceiling, existing ?? ceiling);
91
+ // Later reporter hooks cannot raise a validated value before pool creation.
92
+ Object.defineProperty(config, "maxWorkers", {
93
+ value: selected,
94
+ enumerable: true,
95
+ writable: false,
96
+ configurable: false,
97
+ });
98
+ return selected;
99
+ }
100
+
101
+ /** Load the installed runner once, clamp final config, then execute that same instance. */
102
+ export async function runManagedVitest(
103
+ cwd: string,
104
+ args: string[],
105
+ ceiling: number,
106
+ report: (workers: number, pool: string) => void = () => {},
107
+ ): Promise<number> {
108
+ let context: ManagedVitest | undefined;
109
+ let started = false;
110
+ let outcome = 120;
111
+ let api: VitestApi | undefined;
112
+ try {
113
+ if (args[0] !== "run")
114
+ throw new Error(
115
+ "Managed Vitest requires the run command; watch is not yet supported",
116
+ );
117
+ const require = createRequire(join(cwd, "package.json"));
118
+ const packagePath = require.resolve("vitest/package.json");
119
+ const pkg: { version: string } = JSON.parse(
120
+ await readFile(packagePath, "utf8"),
121
+ );
122
+ const major = Number(pkg.version.split(".")[0]);
123
+ if (major !== 4 && major !== 5)
124
+ throw new Error(`Unsupported managed Vitest major ${major}`);
125
+ api = (await import(
126
+ pathToFileURL(require.resolve("vitest/node")).href
127
+ )) as VitestApi;
128
+ const parsed = api.parseCLI(["vitest", ...args]);
129
+ const options = parsed.options;
130
+ if (
131
+ options.watch ||
132
+ options.standalone ||
133
+ options.ui ||
134
+ options.api ||
135
+ options.mergeReports ||
136
+ options.help ||
137
+ options.version ||
138
+ options.inspect ||
139
+ options.inspectBrk
140
+ ) {
141
+ throw new Error(
142
+ "Managed Vitest supports a finite run, without watch, UI, API or report merging",
143
+ );
144
+ }
145
+ const requested = options.maxWorkers;
146
+ let requestedCeiling = ceiling;
147
+ if (requested !== undefined) {
148
+ if (
149
+ !/^\d+$/.test(String(requested)) ||
150
+ !Number.isSafeInteger(Number(requested)) ||
151
+ Number(requested) < 1 ||
152
+ Number(requested) > ceiling
153
+ ) {
154
+ throw new Error(
155
+ "Managed --maxWorkers must be a positive integer no higher than the launcher ceiling",
156
+ );
157
+ }
158
+ requestedCeiling = Number(requested);
159
+ // A CLI flag must not override the app's lower computed cap. Resolve
160
+ // the app once without this override, then take the minimum below.
161
+ delete options.maxWorkers;
162
+ }
163
+ process.env.TEST = "true";
164
+ process.env.VITEST = "true";
165
+ process.env.NODE_ENV ??= "test";
166
+ Object.assign(options, {
167
+ root: options.root ?? cwd,
168
+ run: true,
169
+ watch: false,
170
+ });
171
+ context =
172
+ major === 4
173
+ ? await api.createVitest("test", options)
174
+ : await api.createVitest(options);
175
+ if (context.projects.length !== 1)
176
+ throw new Error("Managed Vitest requires exactly one resolved project");
177
+ const rootWorkers = clampResolvedTestWorkers(
178
+ context.config,
179
+ requestedCeiling,
180
+ );
181
+ for (const project of context.projects)
182
+ clampResolvedTestWorkers(project.config, rootWorkers);
183
+ // No new unchecked project may appear in an onInit reporter hook.
184
+ Object.freeze(context.projects);
185
+ Object.defineProperty(context, "projects", {
186
+ value: context.projects,
187
+ writable: false,
188
+ configurable: false,
189
+ });
190
+ report(rootWorkers, String(context.config.pool));
191
+ started = true;
192
+ const result = await context.start(parsed.filter);
193
+ outcome =
194
+ result.unhandledErrors.length ||
195
+ result.testModules.some((module) => module.state() === "failed")
196
+ ? 1
197
+ : Number(process.exitCode ?? 0);
198
+ } catch (error) {
199
+ const Missing = api?.TestsNotFoundError ?? api?.FilesNotFoundError;
200
+ if (
201
+ started &&
202
+ context?.config.passWithNoTests &&
203
+ Missing &&
204
+ error instanceof Missing
205
+ )
206
+ outcome = 0;
207
+ else {
208
+ console.error(
209
+ `Loom ${started ? "test runner" : "test preflight"}: ${error instanceof Error ? error.message : String(error)}`,
210
+ );
211
+ outcome = started ? 1 : 120;
212
+ }
213
+ } finally {
214
+ try {
215
+ await context?.close();
216
+ } catch (error) {
217
+ console.error("Loom test cleanup:", error);
218
+ if (outcome === 0) outcome = 1;
219
+ }
220
+ }
221
+ return outcome;
222
+ }