@crewhaus/tool-buildperf 0.7.0 → 0.8.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ CrewHaus Factory
2
+ Copyright 2026 Max Meier
3
+
4
+ This product includes software developed by Max Meier
5
+ (operating as StudioMax — https://studiomax.io) and contributors.
6
+
7
+ The CrewHaus name and logo are trademarks of Max Meier. See
8
+ https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
9
+ use-of-marks policy.
package/README.md CHANGED
@@ -139,6 +139,15 @@ failure went ungrouped. One group among the failures that said something is not
139
139
  an answer about the failures that did not, and answering `true` from that
140
140
  subset is what sends someone after a single root cause for two different bugs.
141
141
 
142
+ A mask, and `BundleSizeCheck`'s `joinPattern`, is a regular expression the
143
+ caller writes. Each is screened before it is accepted: a shape that
144
+ backtracks catastrophically (`(a+)+`, `(\w+\s?)*`, `(a|a)*`) is refused with
145
+ the reason. It then runs in `@crewhaus/tool-safety`'s regex worker under a
146
+ deadline, never on the harness's own thread. A text or path the worker could
147
+ not answer (the engine gave up, or the deadline passed) fails the call with
148
+ the reason: a failure grouped by an unmasked text, or an artifact joined by an
149
+ unnormalised key, would be a confident wrong answer.
150
+
142
151
  There are deliberately no built-in masks. `ErrorCluster` in
143
152
  `@crewhaus/tool-obs` already owns shape-based masking of error text (URLs,
144
153
  uuids, timestamps, paths, prefixed ids, hex blobs, numbers). A second set here
package/dist/index.js CHANGED
@@ -24,15 +24,17 @@
24
24
  * filesystem packages use. Nothing here runs a build, a benchmark or a test:
25
25
  * the measurements come in, the honest reading of them comes out.
26
26
  */
27
- import { readFileSync, readdirSync, statSync } from "node:fs";
27
+ import { readdirSync, statSync } from "node:fs";
28
28
  import { join } from "node:path";
29
29
  import { buildTool } from "@crewhaus/tool-builder";
30
30
  import { statsKernel } from "@crewhaus/tool-math";
31
+ import { openForReadSync } from "@crewhaus/tool-safety/fs";
32
+ import { describeRegexOutcome, openRegexSession, runRegex, screenUserRegex, } from "@crewhaus/tool-safety/regex";
31
33
  import { z } from "zod";
32
34
  import { MIN_SAMPLES_FOR_SIGNIFICANCE, compareBenchmarks } from "./lib/bench";
33
- import { TEST_STATUSES, detectFlaky } from "./lib/flaky";
35
+ import { TEST_STATUSES, detectFlaky, foldWhitespace, maskSubjects, } from "./lib/flaky";
34
36
  import { COMPRESSION_ALGORITHMS, JOIN_MODES, MAX_GLOB_LENGTH, baselineBasisMismatch, comparabilityKey, compileGlob, compressedSize, compressionParameters, joinKey, parametersMismatch, } from "./lib/size";
35
- import { resolveSafe, toPosix } from "./paths";
37
+ import { resolveSafe, toPosix, workspaceRoot } from "./paths";
36
38
  const json = (value) => JSON.stringify(value);
37
39
  /** Ceilings that keep one pathological input from becoming a hang. */
38
40
  const LIMITS = {
@@ -40,6 +42,8 @@ const LIMITS = {
40
42
  entries: 2_000,
41
43
  /** Compressing a file this big to weigh it is not the intended use. */
42
44
  fileBytes: 512 * 1024 * 1024,
45
+ /** A stored size report: entries and totals, never the bundle itself. */
46
+ baselineBytes: 64 * 1024 * 1024,
43
47
  budgets: 200,
44
48
  benchmarks: 500,
45
49
  samplesPerSide: 10_000,
@@ -50,6 +54,8 @@ const LIMITS = {
50
54
  /** The zlib build that produced these numbers; see `runtime` in the report. */
51
55
  const ZLIB_VERSION = process.versions.zlib ?? "unknown";
52
56
  // --- BundleSizeCheck --------------------------------------------------------
57
+ /** Longest artifact path accepted in a baseline row. */
58
+ const MAX_PATH_CHARS = 4_096;
53
59
  // Not `.strict()`: a stored baseline is a previous REPORT, which carries the
54
60
  // derived `comparabilityKey` alongside the parameters. Rejecting the report
55
61
  // this tool just produced would make "store it and pass it back" a lie.
@@ -65,13 +71,67 @@ const baselineSchema = z.object({
65
71
  parameters: parametersSchema.optional(),
66
72
  entries: z
67
73
  .array(z.object({
68
- path: z.string().min(1),
74
+ // A baseline path is a file path: longer than any PATH_MAX is not
75
+ // one, and it is also a subject for the caller's joinPattern.
76
+ path: z.string().min(1).max(MAX_PATH_CHARS),
69
77
  bytes: z.number().int().nonnegative(),
70
78
  compressedBytes: z.number().int().nonnegative().nullable().optional(),
71
79
  }))
72
80
  .max(LIMITS.entries),
73
81
  runtime: z.object({ zlib: z.string() }).optional(),
74
82
  });
83
+ /**
84
+ * The screen a caller-supplied regex gets before it is accepted: length,
85
+ * flags, syntax and the catastrophic-backtracking shapes, with a reason the
86
+ * model can act on (C073). `g` is what a join or mask applies.
87
+ */
88
+ function patternIssue(pattern, flags) {
89
+ const verdict = screenUserRegex(pattern, flags);
90
+ return verdict.ok ? undefined : verdict.reason;
91
+ }
92
+ /**
93
+ * Normalise paths with the caller's joinPattern (every match becomes
94
+ * `[hash]`), in @crewhaus/tool-safety's regex worker under a deadline — never
95
+ * with a synchronous `replace` on this thread, which a pathological pattern
96
+ * could hold for seconds per path, and which JavaScriptCore can abandon and
97
+ * report as "no match". Any path whose key could not be determined fails the
98
+ * whole call: a size gate that joined some rows by an unnormalised key would
99
+ * report a renamed chunk as removed-and-added.
100
+ */
101
+ async function customJoinKeys(pattern, paths, ctx) {
102
+ const distinct = [...new Set(paths)];
103
+ const keys = new Map();
104
+ if (distinct.length === 0)
105
+ return { ok: true, keys };
106
+ const outcome = await runRegex({
107
+ op: "replaceEach",
108
+ pattern,
109
+ flags: "g",
110
+ inputs: distinct,
111
+ replacement: "[hash]",
112
+ onGiveUp: "skip",
113
+ deadlineMs: 2_000,
114
+ ...(ctx?.signal !== undefined ? { signal: ctx.signal } : {}),
115
+ ...(ctx?.runContext !== undefined ? { runawayKey: ctx.runContext.sessionId } : {}),
116
+ });
117
+ if (outcome.status !== "ok") {
118
+ return {
119
+ ok: false,
120
+ message: `BundleSizeCheck could not normalise the artifact paths with joinPattern /${pattern}/: ${describeRegexOutcome(outcome)}. No comparison was made.`,
121
+ };
122
+ }
123
+ const { outputs, undetermined } = outcome.result;
124
+ if (undetermined.length > 0) {
125
+ const first = distinct[undetermined[0]] ?? "";
126
+ return {
127
+ ok: false,
128
+ message: `BundleSizeCheck could not determine the joinPattern key of ${undetermined.length} path(s) (first: "${first}") — the pattern engine gave up on them. Simplify joinPattern; no comparison was made.`,
129
+ };
130
+ }
131
+ for (const [i, path] of distinct.entries())
132
+ keys.set(path, outputs[i]);
133
+ return { ok: true, keys };
134
+ }
75
135
  /** Every file under a directory, workspace-relative, sorted, capped. */
76
136
  function filesUnder(root, rel, out) {
77
137
  for (const entry of readdirSync(join(root, rel), { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
@@ -97,7 +157,7 @@ function filesUnder(root, rel, out) {
97
157
  }
98
158
  return out;
99
159
  }
100
- function measure(paths, parameters, mode, custom) {
160
+ function measure(paths, parameters, mode) {
101
161
  return paths.map((path) => {
102
162
  const at = resolveSafe("BundleSizeCheck", path);
103
163
  const stats = statSync(at.real);
@@ -106,10 +166,19 @@ function measure(paths, parameters, mode, custom) {
106
166
  if (stats.size > LIMITS.fileBytes) {
107
167
  throw new Error(`"${path}" is ${stats.size} bytes, over the ${LIMITS.fileBytes}-byte limit`);
108
168
  }
109
- const bytes = readFileSync(at.real);
169
+ // Opened as the regular file the stat saw, without blocking: a name
170
+ // swapped for a FIFO after the stat is refused, not waited on.
171
+ const read = openForReadSync(workspaceRoot(), path, { maxBytes: LIMITS.fileBytes });
172
+ if (!read.ok)
173
+ throw new Error(`BundleSizeCheck: ${read.reason}`);
174
+ if (read.truncated) {
175
+ throw new Error(`"${path}" is ${read.size} bytes, over the ${LIMITS.fileBytes}-byte limit`);
176
+ }
177
+ const bytes = Buffer.from(read.bytes.buffer, read.bytes.byteOffset, read.bytes.byteLength);
110
178
  return {
111
179
  path: at.rel,
112
- key: joinKey(at.rel, mode, custom).key,
180
+ // A custom join is keyed afterwards, in the regex worker.
181
+ key: mode === "custom" ? at.rel : joinKey(at.rel, mode).key,
113
182
  bytes: bytes.byteLength,
114
183
  compressedBytes: parameters.algorithm === "none" ? null : compressedSize(bytes, parameters),
115
184
  };
@@ -126,6 +195,11 @@ function percentDelta(before, after) {
126
195
  }
127
196
  export const bundleSizeCheck = buildTool({
128
197
  name: "BundleSizeCheck",
198
+ operativeArgs: [
199
+ { field: "files", kind: "path" },
200
+ { field: "directory", kind: "path", beneath: "all" },
201
+ { field: "baselineFile", kind: "path" },
202
+ ],
129
203
  description: "Weigh build artifacts — raw and gzip or brotli — against declared budgets and a stored baseline, and report what actually grew. Use it as the size gate on a pull request, instead of a model comparing two numbers whose provenance it cannot see. The compression parameters are part of the measurement and travel with the report: a baseline produced at a different level, with a different algorithm, or with no declared parameters at all is REFUSED rather than differenced, because the gap between gzip level 6 and level 9 is the same few percent a regression is, and subtracting them produces a confident number about nothing. Hashed filenames (app-4f2a1c.js) can be joined on a normalised key so a content-hash change is not reported as every file being new, and two artifacts that normalise to the same key are reported as ambiguous rather than silently paired. The report is itself a baseline: store it and pass it back next time.",
130
204
  inputSchema: z
131
205
  .object({
@@ -158,6 +232,13 @@ export const bundleSizeCheck = buildTool({
158
232
  joinPattern: z
159
233
  .string()
160
234
  .optional()
235
+ .superRefine((pattern, ctx) => {
236
+ if (pattern === undefined)
237
+ return;
238
+ const issue = patternIssue(pattern, "g");
239
+ if (issue !== undefined)
240
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: issue });
241
+ })
161
242
  .describe("with join=custom: a regex whose matches are replaced by [hash]"),
162
243
  baseline: baselineSchema.optional().describe("a previous report, inline"),
163
244
  baselineFile: z
@@ -198,7 +279,7 @@ export const bundleSizeCheck = buildTool({
198
279
  }),
199
280
  readOnly: true,
200
281
  concurrencySafe: true,
201
- execute: async (input) => {
282
+ execute: async (input, ctx) => {
202
283
  const warnings = [];
203
284
  let parameters;
204
285
  try {
@@ -208,13 +289,11 @@ export const bundleSizeCheck = buildTool({
208
289
  return err.message;
209
290
  }
210
291
  const mode = input.join ?? "exact";
211
- let custom;
212
292
  if (input.joinPattern !== undefined) {
213
- try {
214
- custom = new RegExp(input.joinPattern, "g");
215
- }
216
- catch (err) {
217
- return `joinPattern /${input.joinPattern}/ is not a valid regular expression: ${err.message}`;
293
+ // Screened here too: the schema's refine is skipped by a direct call.
294
+ const issue = patternIssue(input.joinPattern, "g");
295
+ if (issue !== undefined) {
296
+ return `joinPattern /${input.joinPattern}/ was refused: ${issue}`;
218
297
  }
219
298
  }
220
299
  let paths;
@@ -247,7 +326,14 @@ export const bundleSizeCheck = buildTool({
247
326
  if (paths.length === 0) {
248
327
  return "no files matched — there is nothing to weigh, which is not the same as a build of zero bytes";
249
328
  }
250
- const entries = measure(paths, parameters, mode, custom);
329
+ const entries = measure(paths, parameters, mode);
330
+ if (mode === "custom") {
331
+ const keyed = await customJoinKeys(input.joinPattern, entries.map((e) => e.path), ctx);
332
+ if (!keyed.ok)
333
+ return keyed.message;
334
+ for (const entry of entries)
335
+ entry.key = keyed.keys.get(entry.path);
336
+ }
251
337
  const totals = entries.reduce((acc, e) => ({
252
338
  bytes: acc.bytes + e.bytes,
253
339
  compressedBytes: e.compressedBytes === null
@@ -311,9 +397,21 @@ export const bundleSizeCheck = buildTool({
311
397
  let baseline = input.baseline;
312
398
  if (input.baselineFile !== undefined) {
313
399
  const at = resolveSafe("BundleSizeCheck", input.baselineFile);
400
+ // Opened without blocking, and only as a regular file: a FIFO with no
401
+ // writer blocks an ordinary open for ever, and this read was
402
+ // synchronous, so a named pipe named as the baseline stopped the whole
403
+ // harness (C074). A baseline is a size report, so it is capped too.
404
+ const read = openForReadSync(workspaceRoot(), input.baselineFile, {
405
+ maxBytes: LIMITS.baselineBytes,
406
+ });
407
+ if (!read.ok)
408
+ return `baseline file could not be read: ${read.reason}`;
409
+ if (read.truncated) {
410
+ return `baseline file "${at.rel}" is over the ${LIMITS.baselineBytes}-byte limit for a size report, so it was not read`;
411
+ }
314
412
  let parsed;
315
413
  try {
316
- parsed = JSON.parse(readFileSync(at.real, "utf-8"));
414
+ parsed = JSON.parse(read.text);
317
415
  }
318
416
  catch (err) {
319
417
  return `baseline file "${at.rel}" is not valid JSON: ${err.message}`;
@@ -386,8 +484,17 @@ export const bundleSizeCheck = buildTool({
386
484
  // the baseline happened to list first, which is the arbitrary pairing
387
485
  // the head-side check already refuses to make.
388
486
  const baselineGroups = new Map();
487
+ let baselineKeys;
488
+ if (mode === "custom") {
489
+ const keyed = await customJoinKeys(input.joinPattern, baseline.entries.map((e) => e.path), ctx);
490
+ if (!keyed.ok)
491
+ return keyed.message;
492
+ baselineKeys = keyed.keys;
493
+ }
389
494
  for (const entry of baseline.entries) {
390
- const key = joinKey(entry.path, mode, custom).key;
495
+ const key = baselineKeys !== undefined
496
+ ? baselineKeys.get(entry.path)
497
+ : joinKey(entry.path, mode).key;
391
498
  baselineGroups.set(key, [
392
499
  ...(baselineGroups.get(key) ?? []),
393
500
  { path: entry.path, bytes: entry.bytes, compressed: entry.compressedBytes ?? null },
@@ -631,6 +738,69 @@ export const benchmarkCompare = buildTool({
631
738
  },
632
739
  });
633
740
  // --- FlakyTestDetect --------------------------------------------------------
741
+ /** A mask always replaces every match, so `g` is added to its flags. */
742
+ const maskFlags = (mask) => {
743
+ const flags = mask.flags ?? "";
744
+ return flags.includes("g") ? flags : `${flags}g`;
745
+ };
746
+ /** Total failure text the masks may run over in one call. */
747
+ const MAX_MASKED_CHARS = 16_000_000;
748
+ /**
749
+ * Apply the caller's masks to every failure text in @crewhaus/tool-safety's
750
+ * regex worker, in order, each mask over what the previous one left (C073).
751
+ * One text per failing observation, so each mask's hit count is summed over
752
+ * every failure, exactly as the synchronous path counted. A mask that could
753
+ * not be applied to every text fails the call: grouping some failures by a
754
+ * masked key and others by a raw one would split one failure mode in two,
755
+ * which reads as "it fails different ways".
756
+ */
757
+ async function applyMasksOffThread(runs, masks, ctx) {
758
+ for (const mask of masks) {
759
+ const issue = patternIssue(mask.pattern, maskFlags(mask));
760
+ if (issue !== undefined)
761
+ return `mask /${mask.pattern}/ was refused: ${issue}`;
762
+ }
763
+ const raw = maskSubjects(runs);
764
+ let texts = [...raw];
765
+ const counts = {};
766
+ const session = openRegexSession();
767
+ try {
768
+ for (const mask of masks) {
769
+ if (texts.length === 0)
770
+ break;
771
+ const outcome = await session.run({
772
+ op: "replaceEach",
773
+ pattern: mask.pattern,
774
+ flags: maskFlags(mask),
775
+ inputs: texts,
776
+ replacement: mask.with ?? "<masked>",
777
+ onGiveUp: "skip",
778
+ deadlineMs: 2_000,
779
+ maxInputChars: MAX_MASKED_CHARS,
780
+ maxOutputChars: MAX_MASKED_CHARS,
781
+ ...(ctx?.signal !== undefined ? { signal: ctx.signal } : {}),
782
+ ...(ctx?.runContext !== undefined ? { runawayKey: ctx.runContext.sessionId } : {}),
783
+ });
784
+ if (outcome.status !== "ok") {
785
+ return `FlakyTestDetect could not apply mask /${mask.pattern}/: ${describeRegexOutcome(outcome)}. The failures were not grouped; simplify the mask, or pass a precomputed \`signature\` per failure.`;
786
+ }
787
+ if (outcome.result.undetermined.length > 0) {
788
+ return `FlakyTestDetect could not apply mask /${mask.pattern}/ to ${outcome.result.undetermined.length} failure text(s): the pattern engine gave up on them. The failures were not grouped; simplify the mask, or pass a precomputed \`signature\` per failure.`;
789
+ }
790
+ if (outcome.result.replacements > 0) {
791
+ counts[mask.pattern] = (counts[mask.pattern] ?? 0) + outcome.result.replacements;
792
+ }
793
+ texts = outcome.result.outputs;
794
+ }
795
+ }
796
+ finally {
797
+ session.close();
798
+ }
799
+ const keys = new Map();
800
+ for (const [i, text] of raw.entries())
801
+ keys.set(text, foldWhitespace(texts[i] ?? text));
802
+ return { keys, counts };
803
+ }
634
804
  export const flakyTestDetect = buildTool({
635
805
  name: "FlakyTestDetect",
636
806
  description: "Classify each test across repeated runs as passing, flaky, failing every run or never observed, with a Wilson interval on its failure rate rather than a fail/run ratio. Use it on the results of running a suite several times, to decide what to quarantine. Three failures in five runs is not '60% flaky' — the interval is 23%-88%, which does not distinguish annoying from broken — so the quarantine recommendation keys on the interval's lower bound and says 'run it more' when that bound is not yet clear of the floor. It separates nondeterminism from order dependence when the input carries execution order: for a test that both passed and failed it names the tests that ran before it in every failure and in none of the passes. When every run used the SAME order it reports that the question is undecidable rather than answering 'nondeterministic', and a skipped test is never counted as a pass. One run is always inconclusive.",
@@ -681,7 +851,13 @@ export const flakyTestDetect = buildTool({
681
851
  with: z.string().optional(),
682
852
  flags: z.string().max(8).optional(),
683
853
  })
684
- .strict())
854
+ .strict()
855
+ .superRefine((mask, ctx) => {
856
+ const issue = patternIssue(mask.pattern, maskFlags(mask));
857
+ if (issue !== undefined) {
858
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["pattern"], message: issue });
859
+ }
860
+ }))
685
861
  .max(LIMITS.masks)
686
862
  .optional()
687
863
  .describe("substitutions applied to failure text before grouping; each one's hit count is reported"),
@@ -689,10 +865,17 @@ export const flakyTestDetect = buildTool({
689
865
  .strict(),
690
866
  readOnly: true,
691
867
  concurrencySafe: true,
692
- execute: async (input) => {
868
+ execute: async (input, ctx) => {
693
869
  // The kernel's table is the only place a confidence level is defined in
694
870
  // this repository; a literal 1.96 here would be a fourth copy.
695
871
  const z = statsKernel.TWO_SIDED_Z[input.confidence ?? "0.95"];
872
+ let maskedText;
873
+ if (input.masks !== undefined && input.masks.length > 0) {
874
+ const applied = await applyMasksOffThread(input.runs, input.masks, ctx);
875
+ if (typeof applied === "string")
876
+ return applied;
877
+ maskedText = applied;
878
+ }
696
879
  try {
697
880
  return json(detectFlaky(input.runs, {
698
881
  z,
@@ -700,6 +883,7 @@ export const flakyTestDetect = buildTool({
700
883
  ? {}
701
884
  : { quarantineLowerBound: input.quarantineLowerBound }),
702
885
  ...(input.masks === undefined ? {} : { masks: input.masks }),
886
+ ...(maskedText === undefined ? {} : { maskedText }),
703
887
  }));
704
888
  }
705
889
  catch (err) {
@@ -33,6 +33,17 @@ export type FlakyOptions = {
33
33
  readonly quarantineLowerBound?: number;
34
34
  /** Caller-declared substitutions applied to failure text before grouping. */
35
35
  readonly masks?: ReadonlyArray<Mask>;
36
+ /**
37
+ * The masks already applied, off this thread: each failure text's
38
+ * grouping key, and each mask's hit count over every failure. The tool
39
+ * computes these in @crewhaus/tool-safety's regex worker under a deadline
40
+ * (C073), so a caller's pattern never runs synchronously here; `masks`
41
+ * is then only named, not run. A text missing from `keys` is an error.
42
+ */
43
+ readonly maskedText?: {
44
+ readonly keys: ReadonlyMap<string, string>;
45
+ readonly counts: Readonly<Record<string, number>>;
46
+ };
36
47
  };
37
48
  export type FailureGroup = {
38
49
  readonly signature: string;
@@ -86,6 +97,15 @@ export type FlakyReport = {
86
97
  readonly verdict: "clean" | "flaky" | "failing" | "inconclusive";
87
98
  readonly note: string;
88
99
  };
100
+ /**
101
+ * The failure texts masks are applied to, one per failing observation that
102
+ * carries text and no signature, in input order: exactly the texts
103
+ * `groupFailures` would mask, so a hit count summed over them is the count
104
+ * `applyMasks` reports.
105
+ */
106
+ export declare function maskSubjects(runs: ReadonlyArray<RunInput>): string[];
107
+ /** The whitespace fold every grouping key gets after the masks. */
108
+ export declare const foldWhitespace: (text: string) => string;
89
109
  /**
90
110
  * Apply the caller's substitutions and report how many times each fired.
91
111
  *
package/dist/lib/flaky.js CHANGED
@@ -19,12 +19,34 @@
19
19
  * whole reason a team spends a week chasing the wrong test.
20
20
  */
21
21
  import { statsKernel } from "@crewhaus/tool-math";
22
+ import { compileUserRegex } from "@crewhaus/tool-safety/regex";
22
23
  export const TEST_STATUSES = ["pass", "fail", "error", "skip"];
23
24
  export class FlakyError extends Error {
24
25
  name = "FlakyError";
25
26
  }
26
27
  /** A failure is a failure; `error` is one that did not reach an assertion. */
27
28
  const isFailure = (status) => status === "fail" || status === "error";
29
+ /**
30
+ * The failure texts masks are applied to, one per failing observation that
31
+ * carries text and no signature, in input order: exactly the texts
32
+ * `groupFailures` would mask, so a hit count summed over them is the count
33
+ * `applyMasks` reports.
34
+ */
35
+ export function maskSubjects(runs) {
36
+ const out = [];
37
+ for (const run of runs) {
38
+ for (const test of run.tests) {
39
+ if (!isFailure(test.status) || test.signature !== undefined)
40
+ continue;
41
+ const raw = test.error ?? "";
42
+ if (raw !== "")
43
+ out.push(raw);
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ /** The whitespace fold every grouping key gets after the masks. */
49
+ export const foldWhitespace = (text) => text.replace(/\s+/g, " ").trim();
28
50
  /**
29
51
  * Apply the caller's substitutions and report how many times each fired.
30
52
  *
@@ -44,20 +66,21 @@ export function applyMasks(text, masks, counts) {
44
66
  let out = text;
45
67
  for (const mask of masks) {
46
68
  const flags = mask.flags ?? "";
47
- let re;
48
- try {
49
- re = new RegExp(mask.pattern, flags.includes("g") ? flags : `${flags}g`);
50
- }
51
- catch (err) {
52
- throw new FlakyError(`mask /${mask.pattern}/ is not a valid regular expression: ${err.message}`);
69
+ // Screened for the catastrophic shapes even here, where the caller is
70
+ // this package's own code: FlakyTestDetect itself never gets this far
71
+ // with a caller's mask (see `maskedText`).
72
+ const compiled = compileUserRegex(mask.pattern, flags.includes("g") ? flags : `${flags}g`);
73
+ if (!compiled.ok) {
74
+ throw new FlakyError(`mask /${mask.pattern}/ was refused: ${compiled.reason}`);
53
75
  }
76
+ const re = compiled.regex;
54
77
  const fired = out.match(re)?.length ?? 0;
55
78
  if (fired > 0) {
56
79
  out = out.replace(re, mask.with ?? "<masked>");
57
80
  counts[mask.pattern] = (counts[mask.pattern] ?? 0) + fired;
58
81
  }
59
82
  }
60
- return out.replace(/\s+/g, " ").trim();
83
+ return foldWhitespace(out);
61
84
  }
62
85
  /**
63
86
  * The smallest run count whose all-failing Wilson lower bound clears
@@ -147,7 +170,7 @@ function orderAnalysis(occurrences, orderVaried, suiteSize) {
147
170
  : `${suspects.length} test(s) ran before this one in every failing run and in none of the passing runs; re-run this test after each of them alone to confirm`,
148
171
  };
149
172
  }
150
- function groupFailures(occurrences, masks, counts) {
173
+ function groupFailures(occurrences, masks, counts, maskedText) {
151
174
  const groups = new Map();
152
175
  for (const occurrence of occurrences) {
153
176
  if (!isFailure(occurrence.status))
@@ -157,7 +180,7 @@ function groupFailures(occurrences, masks, counts) {
157
180
  // saying anything about it; that is not a group of one, it is an unknown.
158
181
  if (occurrence.signature === undefined && raw === "")
159
182
  continue;
160
- const key = occurrence.signature ?? applyMasks(raw, masks, counts);
183
+ const key = occurrence.signature ?? maskedKey(raw, masks, counts, maskedText);
161
184
  const row = groups.get(key);
162
185
  if (row === undefined) {
163
186
  groups.set(key, { count: 1, example: raw, runs: [occurrence.runId] });
@@ -175,6 +198,15 @@ function groupFailures(occurrences, masks, counts) {
175
198
  }))
176
199
  .sort((a, b) => b.count - a.count || (a.signature < b.signature ? -1 : 1));
177
200
  }
201
+ function maskedKey(raw, masks, counts, maskedText) {
202
+ if (maskedText === undefined)
203
+ return applyMasks(raw, masks, counts);
204
+ const key = maskedText.keys.get(raw);
205
+ if (key === undefined) {
206
+ throw new FlakyError("a failure text has no precomputed mask key; its failures cannot be grouped");
207
+ }
208
+ return key;
209
+ }
178
210
  export function detectFlaky(runs, options = {}) {
179
211
  if (runs.length === 0)
180
212
  throw new FlakyError("no runs were given; there is nothing to classify");
@@ -237,7 +269,7 @@ export function detectFlaky(runs, options = {}) {
237
269
  z,
238
270
  };
239
271
  const order = orderAnalysis(list, orderVaried, suiteSize);
240
- const failureGroups = groupFailures(list, masks, maskCounts);
272
+ const failureGroups = groupFailures(list, masks, maskCounts, options.maskedText);
241
273
  // A failure that recorded no text and no signature is in no group, so one
242
274
  // group does not mean one failure mode — it means one failure mode among
243
275
  // the failures that said anything. Answering "yes, always the same way"
@@ -336,7 +368,7 @@ export function detectFlaky(runs, options = {}) {
336
368
  },
337
369
  tests,
338
370
  summary,
339
- masksApplied: maskCounts,
371
+ masksApplied: options.maskedText?.counts ?? maskCounts,
340
372
  runsForDeterminismClaim: runsForLowerBound(0.9, z),
341
373
  verdict,
342
374
  note: runs.length < 2
package/dist/paths.d.ts CHANGED
@@ -1,10 +1,29 @@
1
1
  import { CrewhausError } from "@crewhaus/errors";
2
- /** Raised when a caller-supplied path resolves outside the workspace root. */
2
+ /**
3
+ * The longest path this resolves, in UTF-16 code units; a longer one is
4
+ * refused before it is walked. Nothing that long can be opened or created:
5
+ * PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
6
+ * 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
7
+ * UTF-16 one. The limit is twice that because the part of a path that exists
8
+ * is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
9
+ * own: no spelling of the place reaches it, not even one through a symlink
10
+ * that shortens the part that exists.
11
+ */
12
+ export declare const MAX_PATH_CHARS: number;
13
+ /**
14
+ * Raised when a caller-supplied path resolves outside the workspace root, or
15
+ * is longer than any path can be.
16
+ */
3
17
  export declare class ToolPermissionError extends CrewhausError {
4
18
  readonly name = "ToolPermissionError";
5
19
  readonly toolName: string;
6
20
  readonly path: string;
7
- constructor(toolName: string, attemptedPath: string);
21
+ /**
22
+ * Why, when it is not that the location escapes the workspace root: a path
23
+ * longer than any path can be. A caller that rewords the refusal says this.
24
+ */
25
+ readonly reason: string | undefined;
26
+ constructor(toolName: string, attemptedPath: string, reason?: string);
8
27
  }
9
28
  /**
10
29
  * A validated path, in both forms the tools need.
package/dist/paths.js CHANGED
@@ -11,15 +11,45 @@
11
11
  import { lstatSync, readlinkSync, realpathSync } from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import { CrewhausError } from "@crewhaus/errors";
14
- /** Raised when a caller-supplied path resolves outside the workspace root. */
14
+ /**
15
+ * The longest path this resolves, in UTF-16 code units; a longer one is
16
+ * refused before it is walked. Nothing that long can be opened or created:
17
+ * PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
18
+ * 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
19
+ * UTF-16 one. The limit is twice that because the part of a path that exists
20
+ * is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
21
+ * own: no spelling of the place reaches it, not even one through a symlink
22
+ * that shortens the part that exists.
23
+ */
24
+ export const MAX_PATH_CHARS = 2 * (process.platform === "darwin" ? 1_024 : process.platform === "win32" ? 32_767 : 4_096);
25
+ /** A path as a refusal quotes it: whole, unless it is past {@link MAX_PATH_CHARS}. */
26
+ function shownPath(given) {
27
+ return given.length > MAX_PATH_CHARS ? `${given.slice(0, 64)}…` : given;
28
+ }
29
+ /** Why a path past {@link MAX_PATH_CHARS} is refused: its length and the limit. */
30
+ function tooLong(abs) {
31
+ return `it is ${abs.length} characters once resolved, over the ${MAX_PATH_CHARS}-character limit: no path that long can be opened or created`;
32
+ }
33
+ /**
34
+ * Raised when a caller-supplied path resolves outside the workspace root, or
35
+ * is longer than any path can be.
36
+ */
15
37
  export class ToolPermissionError extends CrewhausError {
16
38
  name = "ToolPermissionError";
17
39
  toolName;
18
40
  path;
19
- constructor(toolName, attemptedPath) {
20
- super("tool", `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`);
41
+ /**
42
+ * Why, when it is not that the location escapes the workspace root: a path
43
+ * longer than any path can be. A caller that rewords the refusal says this.
44
+ */
45
+ reason;
46
+ constructor(toolName, attemptedPath, reason) {
47
+ super("tool", reason === undefined
48
+ ? `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`
49
+ : `tool "${toolName}" rejected path "${shownPath(attemptedPath)}": ${reason}`);
21
50
  this.toolName = toolName;
22
51
  this.path = attemptedPath;
52
+ this.reason = reason;
23
53
  }
24
54
  }
25
55
  /** The workspace root, resolved. Every path is contained within it. */
@@ -67,15 +97,7 @@ function nameExists(p) {
67
97
  function resolveLocation(target, depth = 0) {
68
98
  if (depth > 40)
69
99
  throw new Error(`symlink chain at "${target}" is too long to resolve`);
70
- let probe = target;
71
- const tail = [];
72
- while (!nameExists(probe)) {
73
- tail.unshift(path.basename(probe));
74
- const parent = path.dirname(probe);
75
- if (parent === probe)
76
- break; // reached the filesystem root
77
- probe = parent;
78
- }
100
+ const { probe, tail } = deepestName(target);
79
101
  let probeReal;
80
102
  try {
81
103
  probeReal = realpathSync(probe);
@@ -97,7 +119,41 @@ function resolveLocation(target, depth = 0) {
97
119
  const base = realpathSync(path.dirname(probe));
98
120
  probeReal = resolveLocation(path.resolve(base, link), depth + 1);
99
121
  }
100
- return tail.length > 0 ? path.join(probeReal, ...tail) : probeReal;
122
+ // One string, not one argument per name: Bun's `path.join` keeps only
123
+ // (argument count mod 65,536) of its arguments.
124
+ return tail.length > 0 ? path.join(probeReal, tail) : probeReal;
125
+ }
126
+ /**
127
+ * `target`, an absolute path, split where its deepest prefix that exists as
128
+ * a NAME ends: that prefix, and the names below it, which do not exist, as
129
+ * one string ("" when `target` itself exists). This is `path.dirname` and
130
+ * `path.basename` worked by index on `target` itself: handing them each
131
+ * shorter prefix in turn copied the rest of the path once per missing name,
132
+ * the square of a count the caller picks.
133
+ */
134
+ function deepestName(target) {
135
+ const top = path.parse(target).root.length;
136
+ const isSep = (i) => target[i] === "/" || target[i] === path.sep;
137
+ let probe = target;
138
+ let start = target.length;
139
+ let stop = -1;
140
+ while (!nameExists(probe)) {
141
+ // `path.basename(probe)` is `target.slice(start, end)`, and
142
+ // `path.dirname(probe)` is `target.slice(0, up)`.
143
+ let end = probe.length;
144
+ while (end > top && isSep(end - 1))
145
+ end--;
146
+ if (stop < 0)
147
+ stop = end;
148
+ start = end;
149
+ while (start > top && !isSep(start - 1))
150
+ start--;
151
+ const up = start > top ? start - 1 : top;
152
+ if (up === probe.length)
153
+ break; // reached the filesystem root
154
+ probe = target.slice(0, up);
155
+ }
156
+ return { probe, tail: stop < 0 ? "" : target.slice(start, stop) };
101
157
  }
102
158
  export function resolveSafe(toolName, rel, root = workspaceRoot()) {
103
159
  const rootResolved = path.resolve(root);
@@ -107,6 +163,9 @@ export function resolveSafe(toolName, rel, root = workspaceRoot()) {
107
163
  if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
108
164
  throw new ToolPermissionError(toolName, rel);
109
165
  }
166
+ // Longer than any path can be: refused before the walk below reads it.
167
+ if (abs.length > MAX_PATH_CHARS)
168
+ throw new ToolPermissionError(toolName, rel, tooLong(abs));
110
169
  let real;
111
170
  try {
112
171
  const rootReal = realpathSync(rootResolved);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/tool-buildperf",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Deterministic build-performance gates: bundle size, benchmark comparison and flaky-test detection against a baseline",
6
6
  "main": "dist/index.js",
@@ -8,17 +8,19 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
12
13
  }
13
14
  },
14
15
  "scripts": {
15
16
  "test": "bun test src"
16
17
  },
17
18
  "dependencies": {
18
- "@crewhaus/errors": "0.7.0",
19
- "@crewhaus/tool-builder": "0.7.0",
20
- "@crewhaus/tool-catalog": "0.7.0",
21
- "@crewhaus/tool-math": "0.7.0",
19
+ "@crewhaus/errors": "0.8.0",
20
+ "@crewhaus/tool-builder": "0.8.0",
21
+ "@crewhaus/tool-catalog": "0.8.0",
22
+ "@crewhaus/tool-math": "0.8.0",
23
+ "@crewhaus/tool-safety": "0.8.0",
22
24
  "zod": "^3.23.8"
23
25
  },
24
26
  "devDependencies": {
@@ -42,5 +44,8 @@
42
44
  "publishConfig": {
43
45
  "access": "public"
44
46
  },
45
- "files": ["dist", "README.md", "LICENSE", "NOTICE"]
47
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"],
48
+ "engines": {
49
+ "bun": ">=1.3.14"
50
+ }
46
51
  }