@orkestrel/test 0.0.36 → 0.0.38

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.
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _orkestrel_contract = require("@orkestrel/contract");
2
3
  let node_buffer = require("node:buffer");
3
4
  let node_crypto = require("node:crypto");
4
5
  let node_fs = require("node:fs");
@@ -7,9 +8,10 @@ let node_http = require("node:http");
7
8
  let node_os = require("node:os");
8
9
  let node_path = require("node:path");
9
10
  let node_url = require("node:url");
10
- let _orkestrel_contract = require("@orkestrel/contract");
11
+ let node_util = require("node:util");
11
12
  let _src_core = require("../core/index.cjs");
12
13
  let node_events = require("node:events");
14
+ let node_perf_hooks = require("node:perf_hooks");
13
15
  // src/server/constants.ts
14
16
  /**
15
17
  * Caps the attempts `removeTree` makes before rethrowing a retryable removal error.
@@ -27,6 +29,117 @@ var REMOVE_TREE_RETRYABLE_CODES = Object.freeze([
27
29
  "ENOTEMPTY",
28
30
  "EPERM"
29
31
  ]);
32
+ /**
33
+ * Names the format version a progress file's `init` line carries; a reader refuses any other.
34
+ */
35
+ var PROGRESS_VERSION = 1;
36
+ /**
37
+ * Caps the characters a progress error message keeps.
38
+ */
39
+ var PROGRESS_MESSAGE_LIMIT = 300;
40
+ /**
41
+ * Names the label a rendered progress reading prints for each failure relation.
42
+ */
43
+ var PROGRESS_LABELS = Object.freeze({
44
+ first: "FIRST",
45
+ bail: "AFTER-BAIL",
46
+ later: "FAILED"
47
+ });
48
+ // src/server/validators.ts
49
+ /**
50
+ * Checks whether a value is one error a progress line carries.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * import { isProgressError } from '@orkestrel/test/server'
55
+ *
56
+ * isProgressError({ message: 'Error: refused', location: 'tests/a.test.ts:4:9' }) // true
57
+ * isProgressError({ location: 'tests/a.test.ts:4:9' }) // false
58
+ * ```
59
+ */
60
+ var isProgressError = (0, _orkestrel_contract.recordOf)({
61
+ message: _orkestrel_contract.isString,
62
+ location: _orkestrel_contract.isString
63
+ }, ["location"]);
64
+ /**
65
+ * Checks whether a value is one line of a progress file.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * import { isProgressEvent } from '@orkestrel/test/server'
70
+ *
71
+ * isProgressEvent({ event: 'cancel', reason: 'test-failure', wall: 1, time: 2, pid: 3 }) // true
72
+ * isProgressEvent({ event: 'cancel', reason: 'test-failure' }) // false
73
+ * ```
74
+ */
75
+ var isProgressEvent = (0, _orkestrel_contract.unionOf)((0, _orkestrel_contract.recordOf)({
76
+ event: (0, _orkestrel_contract.literalOf)("init"),
77
+ version: _orkestrel_contract.isNumber,
78
+ wall: _orkestrel_contract.isNumber,
79
+ bail: _orkestrel_contract.isNumber,
80
+ time: _orkestrel_contract.isNumber,
81
+ pid: _orkestrel_contract.isNumber
82
+ }), (0, _orkestrel_contract.recordOf)({
83
+ event: (0, _orkestrel_contract.literalOf)("start"),
84
+ specifications: (0, _orkestrel_contract.arrayOf)((0, _orkestrel_contract.recordOf)({
85
+ project: _orkestrel_contract.isString,
86
+ module: _orkestrel_contract.isString
87
+ })),
88
+ time: _orkestrel_contract.isNumber,
89
+ pid: _orkestrel_contract.isNumber
90
+ }), (0, _orkestrel_contract.recordOf)({
91
+ event: (0, _orkestrel_contract.literalOf)("collected"),
92
+ project: _orkestrel_contract.isString,
93
+ module: _orkestrel_contract.isString,
94
+ planned: _orkestrel_contract.isNumber,
95
+ errors: (0, _orkestrel_contract.arrayOf)(isProgressError),
96
+ time: _orkestrel_contract.isNumber,
97
+ pid: _orkestrel_contract.isNumber
98
+ }), (0, _orkestrel_contract.recordOf)({
99
+ event: (0, _orkestrel_contract.literalOf)("ready"),
100
+ project: _orkestrel_contract.isString,
101
+ id: _orkestrel_contract.isString,
102
+ name: _orkestrel_contract.isString,
103
+ time: _orkestrel_contract.isNumber,
104
+ pid: _orkestrel_contract.isNumber
105
+ }), (0, _orkestrel_contract.recordOf)({
106
+ event: (0, _orkestrel_contract.literalOf)("case"),
107
+ project: _orkestrel_contract.isString,
108
+ module: _orkestrel_contract.isString,
109
+ id: _orkestrel_contract.isString,
110
+ name: _orkestrel_contract.isString,
111
+ state: (0, _orkestrel_contract.literalOf)("passed", "failed", "skipped", "pending"),
112
+ duration: _orkestrel_contract.isNumber,
113
+ start: _orkestrel_contract.isNumber,
114
+ errors: (0, _orkestrel_contract.arrayOf)(isProgressError),
115
+ time: _orkestrel_contract.isNumber,
116
+ pid: _orkestrel_contract.isNumber
117
+ }, [
118
+ "duration",
119
+ "start",
120
+ "errors"
121
+ ]), (0, _orkestrel_contract.recordOf)({
122
+ event: (0, _orkestrel_contract.literalOf)("cancel"),
123
+ reason: _orkestrel_contract.isString,
124
+ wall: _orkestrel_contract.isNumber,
125
+ time: _orkestrel_contract.isNumber,
126
+ pid: _orkestrel_contract.isNumber
127
+ }), (0, _orkestrel_contract.recordOf)({
128
+ event: (0, _orkestrel_contract.literalOf)("module"),
129
+ project: _orkestrel_contract.isString,
130
+ module: _orkestrel_contract.isString,
131
+ state: (0, _orkestrel_contract.literalOf)("passed", "failed", "skipped", "pending", "queued"),
132
+ duration: _orkestrel_contract.isNumber,
133
+ time: _orkestrel_contract.isNumber,
134
+ pid: _orkestrel_contract.isNumber
135
+ }), (0, _orkestrel_contract.recordOf)({
136
+ event: (0, _orkestrel_contract.literalOf)("end"),
137
+ reason: (0, _orkestrel_contract.literalOf)("passed", "interrupted", "failed"),
138
+ overhead: _orkestrel_contract.isNumber,
139
+ unhandled: (0, _orkestrel_contract.arrayOf)(isProgressError),
140
+ time: _orkestrel_contract.isNumber,
141
+ pid: _orkestrel_contract.isNumber
142
+ }));
30
143
  // src/server/helpers.ts
31
144
  /**
32
145
  * Reads the lowercase hexadecimal SHA-256 digest of a captured file's bytes.
@@ -87,22 +200,22 @@ function requireContained(root, target) {
87
200
  /**
88
201
  * Reads the identity of one allocated directory off a host status.
89
202
  *
90
- * @param status - The status read from the directory's path.
91
- * @returns The device, index node, and creation time that together name the allocation.
203
+ * @param status - The bigint status read from the directory's path with `{ bigint: true }`.
204
+ * @returns The device, index node, and creation time in nanoseconds that together name the allocation.
92
205
  *
93
206
  * @example
94
207
  * ```ts
95
208
  * import { statSync } from 'node:fs'
96
209
  * import { readIdentity } from '@orkestrel/test/server'
97
210
  *
98
- * const status = statSync('/scratch')
211
+ * const status = statSync('/scratch', { bigint: true })
99
212
  *
100
- * readIdentity(status) // { birth: status.birthtimeMs, device: status.dev, inode: status.ino }
213
+ * readIdentity(status) // { birth: status.birthtimeNs, device: status.dev, inode: status.ino }
101
214
  * ```
102
215
  */
103
216
  function readIdentity(status) {
104
217
  return {
105
- birth: status.birthtimeMs,
218
+ birth: status.birthtimeNs,
106
219
  device: status.dev,
107
220
  inode: status.ino
108
221
  };
@@ -177,10 +290,10 @@ function readErrorCode(error) {
177
290
  * import { statSync } from 'node:fs'
178
291
  * import { matchesIdentity, readIdentity } from '@orkestrel/test/server'
179
292
  *
180
- * const allocation = readIdentity(statSync('/scratch'))
293
+ * const allocation = readIdentity(statSync('/scratch', { bigint: true }))
181
294
  *
182
- * matchesIdentity(readIdentity(statSync('/scratch')), allocation) // true
183
- * matchesIdentity({ birth: 3, device: 1, inode: 9 }, { birth: 3, device: 1, inode: 2 }) // false
295
+ * matchesIdentity(readIdentity(statSync('/scratch', { bigint: true })), allocation) // true
296
+ * matchesIdentity({ birth: 3n, device: 1n, inode: 9n }, { birth: 3n, device: 1n, inode: 2n }) // false
184
297
  * ```
185
298
  */
186
299
  function matchesIdentity(current, allocation) {
@@ -867,6 +980,351 @@ async function chooseFiles(context, request) {
867
980
  await target.dispose();
868
981
  }
869
982
  }
983
+ /**
984
+ * Normalizes a module or stack-frame path to the form a progress line carries.
985
+ *
986
+ * @param file - The path Vitest reports, a Vite `/@fs/` path included.
987
+ * @param root - The run's root directory.
988
+ * @returns The path relative to the root with `/` separators, or the path unchanged when it resolves
989
+ * outside the root.
990
+ *
991
+ * @example
992
+ * ```ts
993
+ * import { normalizeProgressPath } from '@orkestrel/test/server'
994
+ *
995
+ * normalizeProgressPath('/work/tests/a.test.ts', '/work') // 'tests/a.test.ts'
996
+ * normalizeProgressPath('/elsewhere/b.ts', '/work') // '/elsewhere/b.ts'
997
+ * ```
998
+ */
999
+ function normalizeProgressPath(file, root) {
1000
+ const path = (0, node_path.relative)(root, file.replace(/^\/@fs\//u, "")).replaceAll("\\", "/");
1001
+ return path === ".." || path.startsWith("../") || (0, node_path.isAbsolute)(path) ? file : path;
1002
+ }
1003
+ /**
1004
+ * Extracts the message line and location a progress line keeps from one Vitest error.
1005
+ *
1006
+ * @param error - The serialized error Vitest reports.
1007
+ * @param root - The run's root directory, which the location is relative to.
1008
+ * @returns The error's name and first message line, capped at `PROGRESS_MESSAGE_LIMIT` characters,
1009
+ * and the first stack frame outside `node_modules`, or the first frame when every frame sits there.
1010
+ *
1011
+ * @example
1012
+ * ```ts
1013
+ * import { extractProgressError } from '@orkestrel/test/server'
1014
+ *
1015
+ * extractProgressError(
1016
+ * {
1017
+ * name: 'AssertionError',
1018
+ * message: 'expected 1 to be 2\nfull diff',
1019
+ * stacks: [{ method: '', file: '/work/tests/a.test.ts', line: 4, column: 9 }],
1020
+ * },
1021
+ * '/work',
1022
+ * )
1023
+ * // { message: 'AssertionError: expected 1 to be 2', location: 'tests/a.test.ts:4:9' }
1024
+ * ```
1025
+ */
1026
+ function extractProgressError(error, root) {
1027
+ const [line = ""] = (0, node_util.stripVTControlCharacters)(`${error.name ?? "Error"}: ${error.message}`).split(/\r?\n/u);
1028
+ const message = line.slice(0, 300);
1029
+ const frame = error.stacks?.find((stack) => !stack.file.includes("node_modules")) ?? error.stacks?.[0];
1030
+ return frame === void 0 ? { message } : {
1031
+ message,
1032
+ location: `${normalizeProgressPath(frame.file, root)}:${frame.line}:${frame.column}`
1033
+ };
1034
+ }
1035
+ /**
1036
+ * Reports whether a collected case is one the run plans to report.
1037
+ *
1038
+ * @param test - A Vitest case, or any value carrying its `options.mode`.
1039
+ * @returns True if the case's mode is `run` or `only`; false for a case that `skip`, `todo`, or a
1040
+ * name filter removed.
1041
+ *
1042
+ * @example
1043
+ * ```ts
1044
+ * import { matchesPlannedCase } from '@orkestrel/test/server'
1045
+ *
1046
+ * matchesPlannedCase({ options: { mode: 'run' } }) // true
1047
+ * matchesPlannedCase({ options: { mode: 'skip' } }) // false
1048
+ * ```
1049
+ */
1050
+ function matchesPlannedCase(test) {
1051
+ return test.options.mode === "run" || test.options.mode === "only";
1052
+ }
1053
+ /**
1054
+ * Reads the bytes a file holds when it is opened, leaving out every byte appended during the read.
1055
+ *
1056
+ * @param path - The file to read.
1057
+ * @returns The bytes up to the length the file had at open.
1058
+ * @throws Thrown when the host refuses to open, inspect, or read the file.
1059
+ *
1060
+ * @example
1061
+ * ```ts
1062
+ * import { writeFileSync } from 'node:fs'
1063
+ * import { readFileSnapshot } from '@orkestrel/test/server'
1064
+ *
1065
+ * writeFileSync('progress.jsonl', '{"event":"init"}\n')
1066
+ * readFileSnapshot('progress.jsonl').length // 17
1067
+ * ```
1068
+ */
1069
+ function readFileSnapshot(path) {
1070
+ const descriptor = (0, node_fs.openSync)(path, "r");
1071
+ try {
1072
+ const bytes = node_buffer.Buffer.alloc((0, node_fs.fstatSync)(descriptor).size);
1073
+ return bytes.subarray(0, (0, node_fs.readSync)(descriptor, bytes, 0, bytes.length, 0));
1074
+ } finally {
1075
+ (0, node_fs.closeSync)(descriptor);
1076
+ }
1077
+ }
1078
+ /**
1079
+ * Filters the progress lines of one event.
1080
+ *
1081
+ * @typeParam TName - The event to keep.
1082
+ * @param events - The lines to filter.
1083
+ * @param name - The event to keep.
1084
+ * @returns The matching lines in order.
1085
+ *
1086
+ * @example
1087
+ * ```ts
1088
+ * import { filterProgressEvents } from '@orkestrel/test/server'
1089
+ *
1090
+ * filterProgressEvents(
1091
+ * [
1092
+ * { event: 'cancel', reason: 'test-failure', wall: 1, time: 2, pid: 3 },
1093
+ * { event: 'ready', project: 'unit', id: 'a', name: 'adds', time: 3, pid: 3 },
1094
+ * ],
1095
+ * 'cancel',
1096
+ * ).length // 1
1097
+ * ```
1098
+ */
1099
+ function filterProgressEvents(events, name) {
1100
+ return events.filter((event) => event.event === name);
1101
+ }
1102
+ /**
1103
+ * Extracts the progress lines a text holds, skipping a partial last line.
1104
+ *
1105
+ * @param text - Progress file text, live or finished.
1106
+ * @returns Each complete line's event, in file order. The text after the last line feed is a line
1107
+ * the writer can still be appending, so it is never decoded.
1108
+ * @throws Thrown when a complete line is not valid JSON, is not a progress event, or is an `init`
1109
+ * line of another format version.
1110
+ *
1111
+ * @example
1112
+ * ```ts
1113
+ * import { extractProgressEvents } from '@orkestrel/test/server'
1114
+ *
1115
+ * extractProgressEvents(
1116
+ * '{"event":"cancel","reason":"test-failure","wall":1,"time":2,"pid":3}\n{"event":"ca',
1117
+ * ).length // 1
1118
+ * ```
1119
+ */
1120
+ function extractProgressEvents(text) {
1121
+ return (0, _src_core.decodeJSONLines)(text.slice(0, text.lastIndexOf("\n") + 1)).map((value, index) => {
1122
+ if (!isProgressEvent(value)) throw new Error(`Progress record ${index + 1} is not a progress event: ${JSON.stringify(value)?.slice(0, 200)}`);
1123
+ if (value.event === "init" && value.version !== 1) throw new Error(`Progress record ${index + 1} follows format version ${value.version}; this reader reads version 1`);
1124
+ return value;
1125
+ });
1126
+ }
1127
+ /**
1128
+ * Computes where the run one process wrote stands, from its last `init` line on.
1129
+ *
1130
+ * @param events - The lines one process wrote, in file order. Every line must carry the same `pid`;
1131
+ * lines of several processes read as one run and miscompute it, so pass a whole file to
1132
+ * `computeProgress`, which groups them first.
1133
+ * @param now - The wall-clock time of the reading, in milliseconds since the Unix epoch, which a
1134
+ * live run's elapsed time is measured to.
1135
+ * @returns The run, or `undefined` when no `init` line opens it.
1136
+ *
1137
+ * @example
1138
+ * ```ts
1139
+ * import { computeProgressRun } from '@orkestrel/test/server'
1140
+ *
1141
+ * computeProgressRun(
1142
+ * [{ event: 'init', version: 1, wall: 1_000, bail: 1, time: 0, pid: 7 }],
1143
+ * 4_000,
1144
+ * )?.elapsed // 3000
1145
+ * ```
1146
+ */
1147
+ function computeProgressRun(events, now) {
1148
+ const begin = events.findLastIndex((event) => event.event === "init");
1149
+ const init = events[begin];
1150
+ if (init?.event !== "init") return void 0;
1151
+ const own = events.slice(begin);
1152
+ const specifications = filterProgressEvents(own, "start").flatMap((start) => start.specifications);
1153
+ const collections = filterProgressEvents(own, "collected");
1154
+ const cases = filterProgressEvents(own, "case");
1155
+ const cancel = filterProgressEvents(own, "cancel").at(0);
1156
+ const end = filterProgressEvents(own, "end").at(0);
1157
+ const clock = end?.time ?? now - init.wall + init.time;
1158
+ const projects = [.../* @__PURE__ */ new Set([
1159
+ ...specifications.map((entry) => entry.project),
1160
+ ...collections.map((entry) => entry.project),
1161
+ ...cases.map((entry) => entry.project)
1162
+ ])].map((name) => {
1163
+ const results = cases.filter((entry) => entry.project === name);
1164
+ const collected = collections.filter((entry) => entry.project === name);
1165
+ return {
1166
+ name,
1167
+ planned: collected.reduce((total, entry) => total + entry.planned, 0),
1168
+ done: results.length,
1169
+ passed: results.filter((entry) => entry.state === "passed").length,
1170
+ failed: results.filter((entry) => entry.state === "failed").length + collected.filter((entry) => entry.errors.length > 0).length,
1171
+ skipped: results.filter((entry) => entry.state === "skipped").length,
1172
+ modules: specifications.filter((entry) => entry.project === name).length,
1173
+ collected: collected.length
1174
+ };
1175
+ });
1176
+ const planned = projects.reduce((total, project) => total + project.planned, 0);
1177
+ const exact = specifications.length > 0 && projects.every((project) => project.collected >= project.modules);
1178
+ const first = cases.at(0);
1179
+ const span = first === void 0 ? 0 : clock - (first.time - (first.duration ?? 0));
1180
+ const rate = cases.length > 0 && span > 0 ? cases.length / span * 6e4 : void 0;
1181
+ const finished = new Set(cases.map((entry) => entry.id));
1182
+ const position = cancel === void 0 ? -1 : own.indexOf(cancel);
1183
+ const trigger = own.find((event) => event.event === "case" && event.state === "failed");
1184
+ const failures = own.flatMap((event, index) => event.event === "case" && event.state === "failed" || event.event === "collected" && event.errors.length > 0 ? [{
1185
+ event,
1186
+ index
1187
+ }] : []).map(({ event, index }, order) => {
1188
+ const ended = event.event === "case" ? (event.start ?? 0) + (event.duration ?? 0) : Number.NEGATIVE_INFINITY;
1189
+ return {
1190
+ project: event.project,
1191
+ module: event.module,
1192
+ name: event.event === "case" ? event.name : void 0,
1193
+ time: event.time,
1194
+ relation: order === 0 ? "first" : order < init.bail || init.bail > 0 && event === trigger || cancel === void 0 || index < position && ended <= cancel.wall ? "later" : "bail",
1195
+ error: event.errors?.at(0)
1196
+ };
1197
+ });
1198
+ return {
1199
+ pid: init.pid,
1200
+ wall: init.wall,
1201
+ state: end?.reason ?? "live",
1202
+ bail: init.bail,
1203
+ elapsed: clock,
1204
+ done: cases.length,
1205
+ planned,
1206
+ exact,
1207
+ rate,
1208
+ remaining: end === void 0 && exact && rate !== void 0 ? Math.max(0, (planned - cases.length) / rate * 6e4) : void 0,
1209
+ projects,
1210
+ running: end === void 0 ? filterProgressEvents(own, "ready").filter((ready) => !finished.has(ready.id)).map((ready) => ({
1211
+ project: ready.project,
1212
+ name: ready.name,
1213
+ duration: Math.max(0, clock - ready.time)
1214
+ })) : [],
1215
+ cancel: cancel === void 0 ? void 0 : {
1216
+ reason: cancel.reason,
1217
+ time: cancel.time
1218
+ },
1219
+ failures,
1220
+ overhead: end?.overhead,
1221
+ unhandled: end?.unhandled ?? []
1222
+ };
1223
+ }
1224
+ /**
1225
+ * Computes where every run a progress file holds stands, one run per writing process.
1226
+ *
1227
+ * @param events - The file's lines, in file order, from any number of processes.
1228
+ * @param now - The wall-clock time of the reading, in milliseconds since the Unix epoch.
1229
+ * @returns One run per process id in first-seen order, each computed by `computeProgressRun` from
1230
+ * that process's lines alone. A process whose lines no `init` line opens contributes no run.
1231
+ *
1232
+ * @example
1233
+ * ```ts
1234
+ * import { computeProgress } from '@orkestrel/test/server'
1235
+ *
1236
+ * computeProgress(
1237
+ * [
1238
+ * { event: 'init', version: 1, wall: 1_000, bail: 0, time: 0, pid: 7 },
1239
+ * { event: 'init', version: 1, wall: 1_000, bail: 0, time: 0, pid: 8 },
1240
+ * ],
1241
+ * 4_000,
1242
+ * ).map((run) => [run.pid, run.elapsed]) // [[7, 3000], [8, 3000]]
1243
+ * ```
1244
+ */
1245
+ function computeProgress(events, now) {
1246
+ return [...new Set(events.map((event) => event.pid))].flatMap((pid) => {
1247
+ const run = computeProgressRun(events.filter((event) => event.pid === pid), now);
1248
+ return run === void 0 ? [] : [run];
1249
+ });
1250
+ }
1251
+ /**
1252
+ * Reads where every run a progress file holds stands, live or finished.
1253
+ *
1254
+ * @param path - The progress file.
1255
+ * @param now - The wall-clock time of the reading. Default: `Date.now()`.
1256
+ * @returns One run per writing process.
1257
+ * @throws Thrown when the host refuses to read the file, or when a complete line is not a progress
1258
+ * event of this format version.
1259
+ * @remarks Reads the file once, up to its length at open, decodes complete lines only, holds no
1260
+ * timer, and writes nothing.
1261
+ *
1262
+ * @example
1263
+ * ```ts
1264
+ * import { readProgress } from '@orkestrel/test/server'
1265
+ *
1266
+ * const [run] = readProgress('tmp/runs/journey.progress.jsonl')
1267
+ * run?.state // 'live' while the run writes, then its end reason
1268
+ * ```
1269
+ */
1270
+ function readProgress(path, now = Date.now()) {
1271
+ return computeProgress(extractProgressEvents(readFileSnapshot(path).toString("utf8")), now);
1272
+ }
1273
+ /**
1274
+ * Renders a duration as whole minutes and seconds.
1275
+ *
1276
+ * @param milliseconds - The duration. A negative or non-finite duration renders as zero.
1277
+ * @returns The duration as `<minutes>m<seconds>s`, the seconds padded to two digits.
1278
+ *
1279
+ * @example
1280
+ * ```ts
1281
+ * import { renderDuration } from '@orkestrel/test/server'
1282
+ *
1283
+ * renderDuration(65_400) // '1m05s'
1284
+ * renderDuration(Number.NaN) // '0m00s'
1285
+ * ```
1286
+ */
1287
+ function renderDuration(milliseconds) {
1288
+ const seconds = Number.isFinite(milliseconds) ? Math.max(0, Math.floor(milliseconds / 1e3)) : 0;
1289
+ return `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, "0")}s`;
1290
+ }
1291
+ /**
1292
+ * Renders progress runs as the text a person reads mid-run.
1293
+ *
1294
+ * @param runs - The runs to render.
1295
+ * @returns One block per run: a summary line with done against planned cases, elapsed time, rate, and
1296
+ * estimate; a line per project; the running cases; the cancel; each failure labelled `FIRST`,
1297
+ * `AFTER-BAIL`, or `FAILED` under its module and case, or its module alone when the module failed to
1298
+ * collect, with its first message line and location; each unhandled error; and, after the end, the
1299
+ * reporter's overhead.
1300
+ *
1301
+ * @example
1302
+ * ```ts
1303
+ * import { readProgress, renderProgress } from '@orkestrel/test/server'
1304
+ *
1305
+ * renderProgress(readProgress('tmp/runs/journey.progress.jsonl'))
1306
+ * // 'run 37252 interrupted bail=1: 52/52 cases, elapsed 0m51s, rate 61.2/min, ETA -\n…'
1307
+ * ```
1308
+ */
1309
+ function renderProgress(runs) {
1310
+ return runs.map((run) => {
1311
+ const width = Math.max(0, ...run.projects.map((project) => project.name.length));
1312
+ return [
1313
+ `run ${run.pid} ${run.state} ${run.bail === 0 ? "full" : `bail=${run.bail}`}: ${run.done}/${run.planned}${run.exact ? "" : "+"} cases, elapsed ${renderDuration(run.elapsed)}, rate ${run.rate === void 0 ? "-" : `${run.rate.toFixed(1)}/min`}, ETA ${run.remaining === void 0 ? "-" : renderDuration(run.remaining)}`,
1314
+ ...run.projects.map((project) => ` ${project.name.padEnd(width)} ${project.done}/${project.planned} passed ${project.passed} failed ${project.failed} skipped ${project.skipped}${project.collected < project.modules ? ` (${project.collected}/${project.modules} modules collected)` : ""}`),
1315
+ ...run.running.map((entry) => ` running ${renderDuration(entry.duration)} [${entry.project}] ${entry.name}`),
1316
+ ...run.cancel === void 0 ? [] : [` cancelled (${run.cancel.reason}) at ${renderDuration(run.cancel.time)}`],
1317
+ ...[...run.failures.map((failure) => ({
1318
+ heading: ` ${PROGRESS_LABELS[failure.relation]} ${renderDuration(failure.time)} [${failure.project}] ${failure.name === void 0 ? failure.module : `${failure.module} > ${failure.name}`}`,
1319
+ error: failure.error
1320
+ })), ...run.unhandled.map((error) => ({
1321
+ heading: " UNHANDLED",
1322
+ error
1323
+ }))].flatMap(({ heading, error }) => [heading, ...error === void 0 ? [" (no error recorded)"] : [` ${error.message}`, ...error.location === void 0 ? [] : [` at ${error.location}`]]]),
1324
+ ...run.overhead === void 0 ? [] : [` reporter overhead ${run.overhead} ms`]
1325
+ ].join("\n");
1326
+ }).join("\n");
1327
+ }
870
1328
  // src/server/Loopback.ts
871
1329
  /** Owns the one shutdown promise behind a loopback projection. */
872
1330
  var Loopback = class {
@@ -967,7 +1425,7 @@ function createScratch(options) {
967
1425
  const prefix = options?.prefix ?? "orkestrel-test-";
968
1426
  if (prefix.includes("/") || prefix.includes("\\")) throw new Error("Scratch prefix must be a name fragment");
969
1427
  const path = (0, node_fs.mkdtempSync)(`${parent}${node_path.sep}${prefix}`);
970
- const allocation = readIdentity((0, node_fs.statSync)(path));
1428
+ const allocation = readIdentity((0, node_fs.statSync)(path, { bigint: true }));
971
1429
  const unremovable = "Scratch directory is not a removable target";
972
1430
  try {
973
1431
  for (const [target, text] of Object.entries(options?.files ?? {})) {
@@ -1024,12 +1482,18 @@ function createScratch(options) {
1024
1482
  const candidate = requireContained(path, target);
1025
1483
  if (candidate === path) throw new Error(`${unremovable}: ${target}`);
1026
1484
  if (!hasScratchPath(path, ".")) throw new Error("Scratch directory does not exist");
1027
- const status = (0, node_fs.lstatSync)(candidate, { throwIfNoEntry: false });
1485
+ const status = (0, node_fs.lstatSync)(candidate, {
1486
+ bigint: true,
1487
+ throwIfNoEntry: false
1488
+ });
1028
1489
  if (status !== void 0 && matchesIdentity(readIdentity(status), allocation)) throw new Error(`${unremovable}: ${target}`);
1029
1490
  removeTree(candidate);
1030
1491
  },
1031
1492
  destroy() {
1032
- const status = (0, node_fs.lstatSync)(path, { throwIfNoEntry: false });
1493
+ const status = (0, node_fs.lstatSync)(path, {
1494
+ bigint: true,
1495
+ throwIfNoEntry: false
1496
+ });
1033
1497
  if (status === void 0) return;
1034
1498
  if (!matchesIdentity(readIdentity(status), allocation)) return;
1035
1499
  removeTree(path);
@@ -1089,26 +1553,207 @@ function createCookieJar() {
1089
1553
  }
1090
1554
  };
1091
1555
  }
1556
+ // src/server/reporters/ProgressReporter.ts
1557
+ /**
1558
+ * Appends one JSON line per Vitest run event to the file `--outputFile.progress` names, so a live
1559
+ * run's progress and each failure's first error can be read before the run ends.
1560
+ *
1561
+ * @example
1562
+ * ```ts
1563
+ * import { defineConfig } from 'vitest/config'
1564
+ * import { ProgressReporter } from '@orkestrel/test/server'
1565
+ *
1566
+ * export default defineConfig({
1567
+ * test: {
1568
+ * reporters: ['dot', new ProgressReporter()],
1569
+ * outputFile: { progress: 'tmp/runs/progress.jsonl' },
1570
+ * },
1571
+ * })
1572
+ * ```
1573
+ */
1574
+ var ProgressReporter = class {
1575
+ #origin = node_perf_hooks.performance.now();
1576
+ #listener;
1577
+ #planned = /* @__PURE__ */ new WeakSet();
1578
+ #vitest;
1579
+ #path;
1580
+ #overhead = 0;
1581
+ constructor() {
1582
+ this.#listener = this.#cancel.bind(this);
1583
+ }
1584
+ onInit(vitest) {
1585
+ this.#measure(() => {
1586
+ const output = vitest.config.outputFile;
1587
+ const named = typeof output === "object" ? output.progress : void 0;
1588
+ if (named === void 0) throw new Error("ProgressReporter writes no file: pass --outputFile.progress=<file>, or set outputFile: { progress: <file> } in the test config");
1589
+ this.#vitest = vitest;
1590
+ this.#path = (0, node_path.resolve)(vitest.config.root, named);
1591
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(this.#path), { recursive: true });
1592
+ this.#write({
1593
+ event: "init",
1594
+ version: 1,
1595
+ wall: Date.now(),
1596
+ bail: vitest.config.bail ?? 0,
1597
+ ...this.#stamp()
1598
+ });
1599
+ });
1600
+ }
1601
+ onTestModuleQueued() {
1602
+ this.#vitest?.onCancel(this.#listener);
1603
+ }
1604
+ onTestRunStart(specifications) {
1605
+ this.#measure(() => {
1606
+ this.#write({
1607
+ event: "start",
1608
+ specifications: specifications.map((specification) => ({
1609
+ project: specification.project.name,
1610
+ module: this.#relative(specification.moduleId)
1611
+ })),
1612
+ ...this.#stamp()
1613
+ });
1614
+ });
1615
+ }
1616
+ onTestModuleCollected(module) {
1617
+ this.#measure(() => {
1618
+ const planned = [...module.children.allTests()].filter((test) => matchesPlannedCase(test));
1619
+ for (const test of planned) this.#planned.add(test);
1620
+ this.#write({
1621
+ event: "collected",
1622
+ project: module.project.name,
1623
+ module: this.#relative(module.moduleId),
1624
+ planned: planned.length,
1625
+ errors: module.errors().map((error) => this.#error(error)),
1626
+ ...this.#stamp()
1627
+ });
1628
+ });
1629
+ }
1630
+ onTestCaseReady(test) {
1631
+ this.#measure(() => {
1632
+ if (!this.#planned.has(test)) return;
1633
+ this.#write({
1634
+ event: "ready",
1635
+ project: test.project.name,
1636
+ id: test.id,
1637
+ name: test.fullName,
1638
+ ...this.#stamp()
1639
+ });
1640
+ });
1641
+ }
1642
+ onTestCaseResult(test) {
1643
+ this.#measure(() => {
1644
+ if (!this.#planned.delete(test)) return;
1645
+ const result = test.result();
1646
+ const diagnostic = test.diagnostic();
1647
+ this.#write({
1648
+ event: "case",
1649
+ project: test.project.name,
1650
+ module: this.#relative(test.module.moduleId),
1651
+ id: test.id,
1652
+ name: test.fullName,
1653
+ state: result.state,
1654
+ ...diagnostic === void 0 ? {} : {
1655
+ duration: Math.round(diagnostic.duration),
1656
+ start: Math.round(diagnostic.startTime)
1657
+ },
1658
+ ...result.state === "failed" ? { errors: result.errors.map((error) => this.#error(error)) } : {},
1659
+ ...this.#stamp()
1660
+ });
1661
+ });
1662
+ }
1663
+ onTestModuleEnd(module) {
1664
+ this.#measure(() => {
1665
+ this.#write({
1666
+ event: "module",
1667
+ project: module.project.name,
1668
+ module: this.#relative(module.moduleId),
1669
+ state: module.state(),
1670
+ duration: Math.round(module.diagnostic().duration),
1671
+ ...this.#stamp()
1672
+ });
1673
+ });
1674
+ }
1675
+ onTestRunEnd(_modules, unhandled, reason) {
1676
+ const errors = unhandled.map((error) => this.#error(error));
1677
+ this.#write({
1678
+ event: "end",
1679
+ reason,
1680
+ overhead: Math.round(this.#overhead * 100) / 100,
1681
+ unhandled: errors,
1682
+ ...this.#stamp()
1683
+ });
1684
+ }
1685
+ #cancel(reason) {
1686
+ this.#measure(() => {
1687
+ this.#write({
1688
+ event: "cancel",
1689
+ reason,
1690
+ wall: Date.now(),
1691
+ ...this.#stamp()
1692
+ });
1693
+ });
1694
+ }
1695
+ #error(error) {
1696
+ return extractProgressError(error, this.#vitest?.config.root ?? process.cwd());
1697
+ }
1698
+ #relative(file) {
1699
+ return normalizeProgressPath(file, this.#vitest?.config.root ?? process.cwd());
1700
+ }
1701
+ #stamp() {
1702
+ return {
1703
+ time: Math.round(node_perf_hooks.performance.now() - this.#origin),
1704
+ pid: process.pid
1705
+ };
1706
+ }
1707
+ #measure(work) {
1708
+ const begin = node_perf_hooks.performance.now();
1709
+ try {
1710
+ work();
1711
+ } finally {
1712
+ this.#overhead += node_perf_hooks.performance.now() - begin;
1713
+ }
1714
+ }
1715
+ #write(event) {
1716
+ if (this.#path === void 0) return;
1717
+ (0, node_fs.appendFileSync)(this.#path, `${JSON.stringify(event)}\n`);
1718
+ }
1719
+ };
1720
+ exports.PROGRESS_LABELS = PROGRESS_LABELS;
1721
+ exports.PROGRESS_MESSAGE_LIMIT = PROGRESS_MESSAGE_LIMIT;
1722
+ exports.PROGRESS_VERSION = PROGRESS_VERSION;
1723
+ exports.ProgressReporter = ProgressReporter;
1092
1724
  exports.REMOVE_TREE_MAX_ATTEMPTS = REMOVE_TREE_MAX_ATTEMPTS;
1093
1725
  exports.REMOVE_TREE_RETRYABLE_CODES = REMOVE_TREE_RETRYABLE_CODES;
1094
1726
  exports.REMOVE_TREE_RETRY_DELAY_MS = REMOVE_TREE_RETRY_DELAY_MS;
1095
1727
  exports.alignLoopClock = alignLoopClock;
1096
1728
  exports.chooseFiles = chooseFiles;
1729
+ exports.computeProgress = computeProgress;
1730
+ exports.computeProgressRun = computeProgressRun;
1097
1731
  exports.createCookieJar = createCookieJar;
1098
1732
  exports.createLink = createLink;
1099
1733
  exports.createLoopback = createLoopback;
1100
1734
  exports.createScratch = createScratch;
1101
1735
  exports.destroyScratch = destroyScratch;
1736
+ exports.extractProgressError = extractProgressError;
1737
+ exports.extractProgressEvents = extractProgressEvents;
1738
+ exports.filterProgressEvents = filterProgressEvents;
1102
1739
  exports.hasScratchPath = hasScratchPath;
1103
1740
  exports.isExcluded = isExcluded;
1741
+ exports.isProgressError = isProgressError;
1742
+ exports.isProgressEvent = isProgressEvent;
1104
1743
  exports.isRunning = isRunning;
1105
1744
  exports.matchesIdentity = matchesIdentity;
1745
+ exports.matchesPlannedCase = matchesPlannedCase;
1746
+ exports.normalizeProgressPath = normalizeProgressPath;
1106
1747
  exports.readCapture = readCapture;
1107
1748
  exports.readErrorCode = readErrorCode;
1749
+ exports.readFileSnapshot = readFileSnapshot;
1108
1750
  exports.readIdentity = readIdentity;
1109
1751
  exports.readInventory = readInventory;
1110
1752
  exports.readLoopClock = readLoopClock;
1753
+ exports.readProgress = readProgress;
1111
1754
  exports.removeTree = removeTree;
1755
+ exports.renderDuration = renderDuration;
1756
+ exports.renderProgress = renderProgress;
1112
1757
  exports.requestUpgrade = requestUpgrade;
1113
1758
  exports.requireContained = requireContained;
1114
1759
  exports.resolveContained = resolveContained;