@granular-software/fractory 0.0.0-stage → 0.1.24

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 (273) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +28 -2
  3. package/dist/activity-volume.d.ts +18 -0
  4. package/dist/activity-volume.js +94 -0
  5. package/dist/annotations.d.ts +118 -0
  6. package/dist/annotations.js +304 -0
  7. package/dist/benchmark-cli.d.ts +1 -0
  8. package/dist/benchmark-cli.js +95 -0
  9. package/dist/benchmark-worker.d.ts +2 -0
  10. package/dist/benchmark-worker.js +22 -0
  11. package/dist/benchmarks.d.ts +19 -0
  12. package/dist/benchmarks.js +414 -0
  13. package/dist/bin.d.ts +2 -0
  14. package/dist/bin.js +63 -0
  15. package/dist/block-cli.d.ts +1 -0
  16. package/dist/block-cli.js +88 -0
  17. package/dist/block-documents.d.ts +35 -0
  18. package/dist/block-documents.js +84 -0
  19. package/dist/change-impact.d.ts +55 -0
  20. package/dist/change-impact.js +223 -0
  21. package/dist/check-source.d.ts +2 -0
  22. package/dist/check-source.js +66 -0
  23. package/dist/checks-model.d.ts +64 -0
  24. package/dist/checks-model.js +36 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +359 -0
  27. package/dist/code-model.d.ts +38 -0
  28. package/dist/code-model.js +94 -0
  29. package/dist/code-store.d.ts +9 -0
  30. package/dist/code-store.js +79 -0
  31. package/dist/compare-artifact.d.ts +6 -0
  32. package/dist/compare-artifact.js +277 -0
  33. package/dist/compare.d.ts +81 -0
  34. package/dist/compare.js +291 -0
  35. package/dist/compiler.d.ts +10 -0
  36. package/dist/compiler.js +1083 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +86 -0
  40. package/dist/core.js +206 -0
  41. package/dist/coverage-cli.d.ts +1 -0
  42. package/dist/coverage-cli.js +42 -0
  43. package/dist/declaration-sources.d.ts +3 -0
  44. package/dist/declaration-sources.js +51 -0
  45. package/dist/declared-graph.d.ts +3 -0
  46. package/dist/declared-graph.js +66 -0
  47. package/dist/display-name.d.ts +2 -0
  48. package/dist/display-name.js +8 -0
  49. package/dist/error-heat.d.ts +58 -0
  50. package/dist/error-heat.js +96 -0
  51. package/dist/evidence.d.ts +3 -0
  52. package/dist/evidence.js +68 -0
  53. package/dist/factory-graph.d.ts +4 -0
  54. package/dist/factory-graph.js +318 -0
  55. package/dist/factory-model.d.ts +97 -0
  56. package/dist/factory-model.js +1 -0
  57. package/dist/git-code.d.ts +47 -0
  58. package/dist/git-code.js +352 -0
  59. package/dist/git-refs.d.ts +4 -0
  60. package/dist/git-refs.js +37 -0
  61. package/dist/history-activity.d.ts +4 -0
  62. package/dist/history-activity.js +129 -0
  63. package/dist/history-churn.d.ts +36 -0
  64. package/dist/history-churn.js +302 -0
  65. package/dist/history-git.d.ts +21 -0
  66. package/dist/history-git.js +125 -0
  67. package/dist/history-ledger.d.ts +43 -0
  68. package/dist/history-ledger.js +450 -0
  69. package/dist/history-ownership.d.ts +10 -0
  70. package/dist/history-ownership.js +75 -0
  71. package/dist/history-source.d.ts +13 -0
  72. package/dist/history-source.js +100 -0
  73. package/dist/integrations-cli.d.ts +2 -0
  74. package/dist/integrations-cli.js +159 -0
  75. package/dist/issue-cache.d.ts +9 -0
  76. package/dist/issue-cache.js +68 -0
  77. package/dist/issue-cli.d.ts +1 -0
  78. package/dist/issue-cli.js +89 -0
  79. package/dist/issue-links.d.ts +15 -0
  80. package/dist/issue-links.js +125 -0
  81. package/dist/linear-issues.d.ts +19 -0
  82. package/dist/linear-issues.js +124 -0
  83. package/dist/local-runtime.d.ts +8 -0
  84. package/dist/local-runtime.js +59 -0
  85. package/dist/map-activity.d.ts +73 -0
  86. package/dist/map-activity.js +234 -0
  87. package/dist/map-model.d.ts +5 -0
  88. package/dist/map-model.js +166 -0
  89. package/dist/map-quality.d.ts +14 -0
  90. package/dist/map-quality.js +56 -0
  91. package/dist/mapping-coverage.d.ts +87 -0
  92. package/dist/mapping-coverage.js +404 -0
  93. package/dist/model.d.ts +182 -0
  94. package/dist/model.js +66 -0
  95. package/dist/operation-benchmark-worker.d.ts +2 -0
  96. package/dist/operation-benchmark-worker.js +60 -0
  97. package/dist/operation-benchmark.d.ts +29 -0
  98. package/dist/operation-benchmark.js +1 -0
  99. package/dist/otel-metrics.d.ts +21 -0
  100. package/dist/otel-metrics.js +146 -0
  101. package/dist/performance-model.d.ts +185 -0
  102. package/dist/performance-model.js +396 -0
  103. package/dist/product-map.d.ts +69 -0
  104. package/dist/product-map.js +168 -0
  105. package/dist/provider-access.cjs +207 -0
  106. package/dist/provider-access.d.cts +14 -0
  107. package/dist/reports-cli.d.ts +1 -0
  108. package/dist/reports-cli.js +111 -0
  109. package/dist/reports-model.d.ts +27 -0
  110. package/dist/reports-model.js +39 -0
  111. package/dist/reports.d.ts +23 -0
  112. package/dist/reports.js +223 -0
  113. package/dist/repository-map.d.ts +22 -0
  114. package/dist/repository-map.js +151 -0
  115. package/dist/resource-cache.d.ts +17 -0
  116. package/dist/resource-cache.js +65 -0
  117. package/dist/review-cli.d.ts +19 -0
  118. package/dist/review-cli.js +224 -0
  119. package/dist/review.d.ts +48 -0
  120. package/dist/review.js +289 -0
  121. package/dist/runtime-metrics.d.ts +26 -0
  122. package/dist/runtime-metrics.js +290 -0
  123. package/dist/scope.d.ts +12 -0
  124. package/dist/scope.js +94 -0
  125. package/dist/sentry-activity.d.ts +39 -0
  126. package/dist/sentry-activity.js +174 -0
  127. package/dist/sentry.d.ts +130 -0
  128. package/dist/sentry.js +369 -0
  129. package/dist/service-release.d.ts +16 -0
  130. package/dist/service-release.js +14 -0
  131. package/dist/setup-cli.d.ts +2 -0
  132. package/dist/setup-cli.js +52 -0
  133. package/dist/setup-kit.cjs +163 -0
  134. package/dist/setup-kit.d.cts +32 -0
  135. package/dist/source-index.d.ts +37 -0
  136. package/dist/source-index.js +166 -0
  137. package/dist/source-review-git.d.ts +7 -0
  138. package/dist/source-review-git.js +103 -0
  139. package/dist/source-review.d.ts +16 -0
  140. package/dist/source-review.js +493 -0
  141. package/dist/telemetry.d.ts +17 -0
  142. package/dist/telemetry.js +51 -0
  143. package/dist/time-window.d.ts +9 -0
  144. package/dist/time-window.js +35 -0
  145. package/dist/trace-evidence.d.ts +23 -0
  146. package/dist/trace-evidence.js +55 -0
  147. package/dist/trace-model.d.ts +26 -0
  148. package/dist/trace-model.js +1 -0
  149. package/dist/tracing.d.ts +44 -0
  150. package/dist/tracing.js +123 -0
  151. package/dist/work-check.d.ts +17 -0
  152. package/dist/work-check.js +110 -0
  153. package/dist/work-cli.d.ts +1 -0
  154. package/dist/work-cli.js +148 -0
  155. package/dist/work-context.d.ts +57 -0
  156. package/dist/work-context.js +568 -0
  157. package/dist/work-intents.d.ts +6 -0
  158. package/dist/work-intents.js +140 -0
  159. package/dist/work-items.d.ts +58 -0
  160. package/dist/work-items.js +86 -0
  161. package/dist/work-model.d.ts +110 -0
  162. package/dist/work-model.js +261 -0
  163. package/dist/work-review-git.d.ts +8 -0
  164. package/dist/work-review-git.js +111 -0
  165. package/dist/work-review.d.ts +26 -0
  166. package/dist/work-review.js +426 -0
  167. package/dist/work-switcher-model.d.ts +43 -0
  168. package/dist/work-switcher-model.js +79 -0
  169. package/dist/work-switcher.d.ts +6 -0
  170. package/dist/work-switcher.js +171 -0
  171. package/dist/working-cli.d.ts +1 -0
  172. package/dist/working-cli.js +33 -0
  173. package/dist/working-code.d.ts +74 -0
  174. package/dist/working-code.js +421 -0
  175. package/dist/workspace-notes.d.ts +71 -0
  176. package/dist/workspace-notes.js +177 -0
  177. package/dist/workspace-tests.d.ts +21 -0
  178. package/dist/workspace-tests.js +573 -0
  179. package/package.json +547 -4
  180. package/src/activity-volume.ts +149 -0
  181. package/src/annotations.ts +481 -0
  182. package/src/benchmark-cli.ts +118 -0
  183. package/src/benchmark-worker.ts +22 -0
  184. package/src/benchmarks.ts +493 -0
  185. package/src/bin.ts +54 -0
  186. package/src/block-cli.ts +106 -0
  187. package/src/block-documents.ts +117 -0
  188. package/src/change-impact.ts +280 -0
  189. package/src/check-source.ts +82 -0
  190. package/src/checks-model.ts +108 -0
  191. package/src/cli.ts +440 -0
  192. package/src/code-model.ts +159 -0
  193. package/src/code-store.ts +98 -0
  194. package/src/compare-artifact.ts +314 -0
  195. package/src/compare.ts +440 -0
  196. package/src/compiler.ts +1326 -0
  197. package/src/compose.ts +94 -0
  198. package/src/core.ts +357 -0
  199. package/src/coverage-cli.ts +52 -0
  200. package/src/declaration-sources.ts +69 -0
  201. package/src/declared-graph.ts +74 -0
  202. package/src/display-name.ts +8 -0
  203. package/src/error-heat.ts +161 -0
  204. package/src/evidence.ts +94 -0
  205. package/src/factory-graph.ts +378 -0
  206. package/src/factory-model.ts +73 -0
  207. package/src/git-code.ts +461 -0
  208. package/src/git-refs.ts +43 -0
  209. package/src/history-activity.ts +146 -0
  210. package/src/history-churn.ts +416 -0
  211. package/src/history-git.ts +163 -0
  212. package/src/history-ledger.ts +636 -0
  213. package/src/history-ownership.ts +116 -0
  214. package/src/history-source.ts +117 -0
  215. package/src/integrations-cli.ts +187 -0
  216. package/src/issue-cache.ts +96 -0
  217. package/src/issue-cli.ts +137 -0
  218. package/src/issue-links.ts +153 -0
  219. package/src/linear-issues.ts +154 -0
  220. package/src/local-runtime.ts +70 -0
  221. package/src/map-activity.ts +309 -0
  222. package/src/map-model.ts +213 -0
  223. package/src/map-quality.ts +61 -0
  224. package/src/mapping-coverage.ts +570 -0
  225. package/src/model.ts +221 -0
  226. package/src/operation-benchmark-worker.ts +60 -0
  227. package/src/operation-benchmark.ts +28 -0
  228. package/src/otel-metrics.ts +176 -0
  229. package/src/performance-model.ts +575 -0
  230. package/src/product-map.ts +236 -0
  231. package/src/provider-access.cjs +207 -0
  232. package/src/provider-access.d.cts +14 -0
  233. package/src/reports-cli.ts +125 -0
  234. package/src/reports-model.ts +73 -0
  235. package/src/reports.ts +276 -0
  236. package/src/repository-map.ts +189 -0
  237. package/src/resource-cache.ts +76 -0
  238. package/src/review-cli.ts +256 -0
  239. package/src/review.ts +376 -0
  240. package/src/runtime-metrics.ts +386 -0
  241. package/src/scope.ts +103 -0
  242. package/src/sentry-activity.ts +234 -0
  243. package/src/sentry.ts +545 -0
  244. package/src/service-release.ts +18 -0
  245. package/src/setup-cli.ts +58 -0
  246. package/src/setup-kit.cjs +163 -0
  247. package/src/setup-kit.d.cts +32 -0
  248. package/src/source-index.ts +205 -0
  249. package/src/source-review-git.ts +129 -0
  250. package/src/source-review.ts +637 -0
  251. package/src/telemetry.ts +68 -0
  252. package/src/time-window.ts +51 -0
  253. package/src/trace-evidence.ts +80 -0
  254. package/src/trace-model.ts +26 -0
  255. package/src/tracing.ts +165 -0
  256. package/src/work-check.ts +143 -0
  257. package/src/work-cli.ts +195 -0
  258. package/src/work-context.ts +713 -0
  259. package/src/work-intents.ts +196 -0
  260. package/src/work-items.ts +151 -0
  261. package/src/work-model.ts +400 -0
  262. package/src/work-review-git.ts +130 -0
  263. package/src/work-review.ts +573 -0
  264. package/src/work-switcher-model.ts +121 -0
  265. package/src/work-switcher.ts +191 -0
  266. package/src/working-cli.ts +38 -0
  267. package/src/working-code.ts +582 -0
  268. package/src/workspace-notes.ts +203 -0
  269. package/src/workspace-tests.ts +654 -0
  270. package/toolkit/GUIDE.md +305 -0
  271. package/toolkit/SKILL.md +131 -0
  272. package/toolkit/bin/fractory +2 -0
  273. package/toolkit/build.json +1 -0
@@ -0,0 +1,573 @@
1
+ import { readGit, resolveComparisonRef } from "./git-refs.js";
2
+ import { desktopRuntime } from "./local-runtime.js";
3
+ import { createHash } from "node:crypto";
4
+ import { spawn } from "node:child_process";
5
+ import { existsSync, readFileSync, readdirSync, statSync, realpathSync, mkdirSync, writeFileSync, renameSync, rmSync, } from "node:fs";
6
+ import { dirname, join, relative, resolve } from "node:path";
7
+ import { relatedTests } from "./model.js";
8
+ import { checkedPath } from "./workspace-notes.js";
9
+ import { testDefinitions } from "./check-source.js";
10
+ const digest = (body) => createHash("sha256").update(body).digest("hex");
11
+ export function checkPlan(root, graph, block) {
12
+ root = realpathSync(root);
13
+ if (!graph.elements.some((n) => n.id === block))
14
+ throw Error("Unknown block");
15
+ const tests = relatedTests(graph, block), files = [...new Set(tests.map((t) => t.source.file))];
16
+ return files
17
+ .map((file) => {
18
+ const base = {
19
+ file,
20
+ runner: null,
21
+ package: "",
22
+ associations: [
23
+ ...new Set(tests
24
+ .filter((t) => t.source.file === file)
25
+ .map((t) => t.association)),
26
+ ],
27
+ };
28
+ try {
29
+ const path = checkedPath(root, file), text = readFileSync(path, "utf8");
30
+ const revision = digest(text);
31
+ if (!/\.(test|spec|vitest)\.[cm]?[jt]sx?$/.test(file))
32
+ return { ...base, reason: "Not a recognized test suite" };
33
+ let cwd = dirname(path);
34
+ while (cwd !== resolve(root) && !existsSync(join(cwd, "package.json")))
35
+ cwd = dirname(cwd);
36
+ base.package = relative(root, cwd) || ".";
37
+ const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
38
+ const scripts = Object.values(pkg.scripts || {}).join(" ");
39
+ if (/(?:from\s*|require\()['"]bun:test['"]/.test(text))
40
+ return { ...base, sourceRevision: revision, runner: "bun" };
41
+ // Vitest supports a package without a config file. Suite imports and
42
+ // the package's declared runner are evidence; a config is not required.
43
+ if (/['"]vitest['"]/.test(text) || /\bvitest\b/.test(scripts))
44
+ return {
45
+ ...base,
46
+ sourceRevision: revision,
47
+ runner: "vitest",
48
+ };
49
+ if (/bun test/.test(scripts) && !/playwright|node:test/.test(text))
50
+ return { ...base, sourceRevision: revision, runner: "bun" };
51
+ return {
52
+ ...base,
53
+ reason: "No supported Bun or Vitest runner in this package",
54
+ };
55
+ }
56
+ catch {
57
+ return {
58
+ ...base,
59
+ reason: "Test file or package is unavailable in this checkout",
60
+ };
61
+ }
62
+ })
63
+ .sort((a, b) => a.file.localeCompare(b.file));
64
+ }
65
+ function fingerprints(root, graph, block, files) {
66
+ const ids = new Set([block]);
67
+ let changed = true;
68
+ while (changed) {
69
+ changed = false;
70
+ for (const n of graph.elements)
71
+ if (n.parent && ids.has(n.parent) && !ids.has(n.id)) {
72
+ ids.add(n.id);
73
+ changed = true;
74
+ }
75
+ }
76
+ // Include declared dependencies and the test owners, without reparsing the repository.
77
+ for (const t of graph.tests)
78
+ if (files.includes(t.source.file))
79
+ for (const id of t.targets)
80
+ ids.add(id);
81
+ const sources = new Set([...files, "bun.lock", "package.json"]);
82
+ for (const n of graph.elements)
83
+ if (ids.has(n.id))
84
+ for (const s of n.sources || (n.source ? [n.source] : []))
85
+ sources.add(s.file);
86
+ for (const file of files) {
87
+ let path = dirname(resolve(root, file));
88
+ while (path !== resolve(root)) {
89
+ if (existsSync(join(path, "package.json"))) {
90
+ sources.add(relative(root, join(path, "package.json")));
91
+ for (const name of [
92
+ "vitest.config.ts",
93
+ "vitest.config.mts",
94
+ "vitest.config.mjs",
95
+ "bunfig.toml",
96
+ ])
97
+ if (existsSync(join(path, name)))
98
+ sources.add(relative(root, join(path, name)));
99
+ break;
100
+ }
101
+ path = dirname(path);
102
+ }
103
+ }
104
+ return Object.fromEntries([...sources].map((file) => {
105
+ try {
106
+ return [file, digest(readFileSync(checkedPath(root, file), "utf8"))];
107
+ }
108
+ catch {
109
+ return [file, "missing"];
110
+ }
111
+ }));
112
+ }
113
+ // Source is available only for suites associated with the requested logical block.
114
+ export function readTestSource(root, graph, block, file, ref) {
115
+ if (!graph.elements.some((n) => n.id === block) ||
116
+ !relatedTests(graph, block).some((test) => test.source.file === file))
117
+ throw Error("This test suite is not associated with the block");
118
+ const path = ref ? undefined : checkedPath(root, file);
119
+ if (path && statSync(path).size > 256000)
120
+ throw Error("This suite is too large to preview (256 KB limit)");
121
+ const body = ref
122
+ ? readGit(root, ["show", `${resolveComparisonRef(root, ref)}:${file}`])
123
+ : readFileSync(path, "utf8");
124
+ if (Buffer.byteLength(body) > 256000)
125
+ throw Error("This suite is too large to preview (256 KB limit)");
126
+ return {
127
+ file,
128
+ revision: digest(body),
129
+ body,
130
+ definitions: testDefinitions(body, file),
131
+ };
132
+ }
133
+ const decodeXml = (text) => text
134
+ .replace(/"/g, '"')
135
+ .replace(/'/g, "'")
136
+ .replace(/&lt;/g, "<")
137
+ .replace(/&gt;/g, ">")
138
+ .replace(/&#(x[0-9a-f]+|[0-9]+);/gi, (_, code) => {
139
+ const value = code[0].toLowerCase() === "x"
140
+ ? parseInt(code.slice(1), 16)
141
+ : Number(code);
142
+ return value <= 0x10ffff ? String.fromCodePoint(value) : "";
143
+ })
144
+ .replace(/&amp;/g, "&");
145
+ const xmlAttribute = (tag, name) => decodeXml(new RegExp(`\\b${name}="([^"]*)"`).exec(tag)?.[1] || "");
146
+ const caseLimit = 1000;
147
+ const cleanText = (text) => text.replace(/\x1b\[[0-9;]*m/g, "").slice(0, 8000);
148
+ export function bunReport(body, cwd, root) {
149
+ const results = new Map();
150
+ const stack = [];
151
+ // Bun emits nested suites for describe(). Count each testcase once, keeping
152
+ // the outer file totals rather than duplicating nested suite totals.
153
+ const tokens = /<testsuite\b([^>]*)>|<\/testsuite>|<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g;
154
+ for (const match of body.matchAll(tokens)) {
155
+ if (match[0] === "</testsuite>") {
156
+ stack.pop();
157
+ continue;
158
+ }
159
+ if (match[1] !== undefined) {
160
+ const file = xmlAttribute(match[1], "file") || stack.at(-1)?.file;
161
+ if (!file)
162
+ continue;
163
+ stack.push({ file, name: xmlAttribute(match[1], "name") });
164
+ const path = relative(root, resolve(cwd, file));
165
+ if (!results.has(path)) {
166
+ const total = Number(xmlAttribute(match[1], "tests") || 0), failed = Number(xmlAttribute(match[1], "failures") || 0) +
167
+ Number(xmlAttribute(match[1], "errors") || 0), skipped = Number(xmlAttribute(match[1], "skipped") || 0);
168
+ results.set(path, {
169
+ file: path,
170
+ status: failed
171
+ ? "failed"
172
+ : !total
173
+ ? "blocked"
174
+ : total === skipped
175
+ ? "skipped"
176
+ : "passed",
177
+ passed: Math.max(0, total - failed - skipped),
178
+ failed,
179
+ skipped,
180
+ duration: Number(xmlAttribute(match[1], "time") || 0) * 1000,
181
+ cases: [],
182
+ });
183
+ }
184
+ continue;
185
+ }
186
+ const attrs = match[2], contents = match[3] || "", file = xmlAttribute(attrs, "file") || stack.at(-1)?.file;
187
+ if (!file)
188
+ continue;
189
+ const result = results.get(relative(root, resolve(cwd, file)));
190
+ if (!result)
191
+ continue;
192
+ if (result.cases.length >= caseLimit) {
193
+ result.casesTruncated = true;
194
+ continue;
195
+ }
196
+ const failed = /<(failure|error)\b/.test(contents), failureTag = /<(?:failure|error)\b([^>]*)(?:\/>|>([\s\S]*?)<\/(?:failure|error)>)/.exec(contents);
197
+ const failure = failureTag
198
+ ? decodeXml((failureTag[2] || "")
199
+ .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
200
+ .replace(/<[^>]*>/g, "")) ||
201
+ xmlAttribute(failureTag[1], "message") ||
202
+ xmlAttribute(failureTag[1], "type")
203
+ : undefined;
204
+ const line = Number(xmlAttribute(attrs, "line"));
205
+ result.cases.push({
206
+ name: xmlAttribute(attrs, "name"),
207
+ groups: stack.slice(1).map((s) => s.name),
208
+ status: failed
209
+ ? "failed"
210
+ : /<skipped\b/.test(contents)
211
+ ? "skipped"
212
+ : "passed",
213
+ duration: Number(xmlAttribute(attrs, "time") || 0) * 1000,
214
+ line: line > 0 ? line : undefined,
215
+ failure: failure ? cleanText(failure) : undefined,
216
+ });
217
+ }
218
+ return [...results.values()];
219
+ }
220
+ export function vitestReport(body, root) {
221
+ const report = JSON.parse(body);
222
+ return (report.testResults || []).map((suite) => {
223
+ const values = suite.assertionResults || [], passed = values.filter((t) => t.status === "passed").length, failed = values.filter((t) => t.status === "failed").length, skipped = values.length - passed - failed;
224
+ const cases = values.slice(0, caseLimit).map((t) => ({
225
+ name: t.title || t.fullName || "Unnamed test",
226
+ groups: (t.ancestorTitles || []).filter(Boolean),
227
+ status: t.status === "passed"
228
+ ? "passed"
229
+ : t.status === "failed"
230
+ ? "failed"
231
+ : t.status === "todo"
232
+ ? "todo"
233
+ : "skipped",
234
+ duration: t.duration,
235
+ line: t.location?.line,
236
+ failure: t.failureMessages?.length
237
+ ? cleanText(t.failureMessages.join("\n\n"))
238
+ : undefined,
239
+ }));
240
+ return {
241
+ file: relative(root, suite.name),
242
+ status: suite.status === "failed" || failed
243
+ ? "failed"
244
+ : passed
245
+ ? "passed"
246
+ : skipped
247
+ ? "skipped"
248
+ : "blocked",
249
+ passed,
250
+ failed,
251
+ skipped,
252
+ duration: Math.max(0, suite.endTime - suite.startTime),
253
+ cases,
254
+ casesTruncated: values.length > caseLimit || undefined,
255
+ reason: !values.length && suite.message
256
+ ? cleanText(suite.message)
257
+ : undefined,
258
+ };
259
+ });
260
+ }
261
+ export class WorkspaceTestRunner {
262
+ root;
263
+ graph;
264
+ directory;
265
+ fileHashes = new Map();
266
+ currentHash(file) {
267
+ try {
268
+ const path = checkedPath(this.root, file), stat = statSync(path), key = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
269
+ const cached = this.fileHashes.get(file);
270
+ if (cached?.key === key)
271
+ return cached.hash;
272
+ const hash = digest(readFileSync(path, "utf8"));
273
+ this.fileHashes.set(file, { key, hash });
274
+ return hash;
275
+ }
276
+ catch {
277
+ return "missing";
278
+ }
279
+ }
280
+ active;
281
+ constructor(root, graph, directory = join(root, ".fractal", "checks")) {
282
+ this.root = root;
283
+ this.graph = graph;
284
+ this.directory = directory;
285
+ this.root = realpathSync(root);
286
+ }
287
+ save(run) {
288
+ mkdirSync(this.directory, { recursive: true });
289
+ const file = join(this.directory, `${run.id}.json`), temp = file + ".tmp";
290
+ writeFileSync(temp, JSON.stringify(run), { mode: 0o600 });
291
+ renameSync(temp, file);
292
+ }
293
+ list() {
294
+ if (!existsSync(this.directory))
295
+ return [];
296
+ const runs = readdirSync(this.directory)
297
+ .filter((f) => /^[a-f0-9-]{36}\.json$/.test(f))
298
+ .map((file) => {
299
+ try {
300
+ return JSON.parse(readFileSync(join(this.directory, file), "utf8"));
301
+ }
302
+ catch {
303
+ return null;
304
+ }
305
+ })
306
+ .filter((r) => !!r)
307
+ .sort((a, b) => b.startedAt.localeCompare(a.startedAt))
308
+ .slice(0, 20);
309
+ const hashes = new Map();
310
+ return runs.map((run) => {
311
+ if (["running", "queued"].includes(run.status) &&
312
+ this.active?.run.id !== run.id) {
313
+ run.status = "blocked";
314
+ run.finishedAt = new Date().toISOString();
315
+ run.output += "\nRunner restarted; run these suites again.";
316
+ for (const r of run.results)
317
+ if (["running", "queued"].includes(r.status))
318
+ r.status = "blocked";
319
+ this.save(run);
320
+ }
321
+ const stale = run.definition !== this.graph.revision ||
322
+ Object.entries(run.fingerprints).some(([file, hash]) => {
323
+ if (!hashes.has(file)) {
324
+ try {
325
+ hashes.set(file, this.currentHash(file));
326
+ }
327
+ catch {
328
+ hashes.set(file, "missing");
329
+ }
330
+ }
331
+ return hashes.get(file) !== hash;
332
+ });
333
+ return { ...run, stale };
334
+ });
335
+ }
336
+ start(block, files) {
337
+ if (this.active)
338
+ throw Error("A test run is already active. Wait or cancel it first.");
339
+ if (!files.length)
340
+ throw Error("Choose at least one suite");
341
+ if (new Set(files).size !== files.length)
342
+ throw Error("Choose each suite only once");
343
+ const plan = checkPlan(this.root, this.graph, block), selected = files.map((file) => plan.find((p) => p.file === file));
344
+ if (selected.some((p) => !p?.runner))
345
+ throw Error("Choose runnable suites attached to this block");
346
+ const run = {
347
+ id: crypto.randomUUID(),
348
+ block,
349
+ definition: this.graph.revision,
350
+ startedAt: new Date().toISOString(),
351
+ status: "queued",
352
+ results: files.map((file) => ({
353
+ file,
354
+ status: "queued",
355
+ passed: 0,
356
+ failed: 0,
357
+ skipped: 0,
358
+ })),
359
+ output: "",
360
+ fingerprints: fingerprints(this.root, this.graph, block, files),
361
+ pid: process.pid,
362
+ };
363
+ const active = { run, cancelled: false };
364
+ this.active = active;
365
+ this.save(run);
366
+ void this.execute(active, selected);
367
+ return run;
368
+ }
369
+ stop(child, signal) {
370
+ if (!child?.pid)
371
+ return;
372
+ try {
373
+ if (process.platform !== "win32")
374
+ process.kill(-child.pid, signal);
375
+ else
376
+ child.kill(signal);
377
+ }
378
+ catch {
379
+ child.kill(signal);
380
+ }
381
+ }
382
+ cancel(id) {
383
+ if (this.active?.run.id !== id)
384
+ throw Error("This run is no longer active");
385
+ const active = this.active;
386
+ active.cancelled = true;
387
+ this.stop(active.child, "SIGTERM");
388
+ setTimeout(() => this.stop(active.child, "SIGKILL"), 1500).unref();
389
+ return this.active.run;
390
+ }
391
+ async execute(active, files) {
392
+ const { run } = active;
393
+ const groups = new Map();
394
+ for (const f of files) {
395
+ const key = f.package + ":" + f.runner;
396
+ groups.set(key, [...(groups.get(key) || []), f]);
397
+ }
398
+ // Bound each subprocess, not the user's selection. Every selected suite is
399
+ // queued; packages run sequentially and cancellation stops future batches.
400
+ const batches = [...groups.values()].flatMap((group) => {
401
+ const result = [];
402
+ for (let at = 0; at < group.length; at += 32)
403
+ result.push(group.slice(at, at + 32));
404
+ return result;
405
+ });
406
+ const secrets = Object.entries(process.env)
407
+ .filter(([key, value]) => /TOKEN|SECRET|PASSWORD|API_KEY|DSN/.test(key) &&
408
+ value &&
409
+ value.length >= 8)
410
+ .map(([, value]) => value);
411
+ const output = (text) => {
412
+ text = (run.output + text).replace(/\x1b\[[0-9;]*m/g, "");
413
+ for (const secret of secrets)
414
+ text = text.split(secret).join("[redacted]");
415
+ run.output = text.slice(-64000);
416
+ };
417
+ try {
418
+ run.status = "running";
419
+ this.save(run);
420
+ for (const group of batches) {
421
+ if (active.cancelled)
422
+ break;
423
+ const cwd = group[0].package === "."
424
+ ? this.root
425
+ : checkedPath(this.root, group[0].package), report = join(this.directory, `${run.id}.report`);
426
+ for (const item of run.results)
427
+ if (group.some((f) => f.file === item.file))
428
+ item.status = "running";
429
+ this.save(run);
430
+ const paths = group.map((f) => "./" + relative(cwd, resolve(this.root, f.file)));
431
+ const bun = group[0].runner === "bun";
432
+ const command = bun ? "bun" : "node", args = bun
433
+ ? [
434
+ "test",
435
+ ...paths,
436
+ "--reporter=junit",
437
+ `--reporter-outfile=${report}`,
438
+ ]
439
+ : [
440
+ "--input-type=module",
441
+ "-e",
442
+ `const input=JSON.parse(process.argv[1]);const {createRequire}=await import('node:module');const {pathToFileURL}=await import('node:url');const entry=createRequire(process.cwd()+'/package.json').resolve('vitest/node');const {startVitest}=await import(pathToFileURL(entry).href);const ctx=await startVitest('test',input.files,{watch:false,minWorkers:1,maxWorkers:2,includeTaskLocation:true,include:input.files,reporters:['json'],outputFile:input.report});if(!ctx){process.exitCode=1;}else{const errors=ctx.state.getUnhandledErrors();for(const error of errors)console.error(error.stack||error.message||String(error));if(!ctx.state.getFiles().length||ctx.state.getFiles().some(file=>file.result?.state==='fail')||errors.length)process.exitCode=1;await ctx.close();}`,
443
+ JSON.stringify({
444
+ files: paths.map((path) => path.replace(/^\.\//, "")),
445
+ report,
446
+ }),
447
+ ];
448
+ output(`\n${relative(this.root, cwd)} · ${group[0].runner} · ${group.length} suite${group.length === 1 ? "" : "s"}\n`);
449
+ let timedOut = false;
450
+ const code = await new Promise((done) => {
451
+ // Desktop checks run as tests without inheriting the parent's session.
452
+ const environment = desktopRuntime()
453
+ ? {
454
+ ...process.env,
455
+ CI: "1",
456
+ FORCE_COLOR: "0",
457
+ NODE_ENV: "test",
458
+ FRACTORY_DESKTOP: undefined,
459
+ FRACTORY_DESKTOP_TOKEN: undefined,
460
+ FRACTORY_DESKTOP_ORIGIN: undefined,
461
+ }
462
+ : { ...process.env, CI: "1", FORCE_COLOR: "0" };
463
+ const child = spawn(command, args, {
464
+ cwd,
465
+ detached: process.platform !== "win32",
466
+ env: environment,
467
+ stdio: ["ignore", "pipe", "pipe"],
468
+ });
469
+ active.child = child;
470
+ child.stdout?.on("data", (chunk) => output(String(chunk)));
471
+ child.stderr?.on("data", (chunk) => output(String(chunk)));
472
+ const timeout = setTimeout(() => {
473
+ timedOut = true;
474
+ this.stop(child, "SIGTERM");
475
+ setTimeout(() => this.stop(child, "SIGKILL"), 1500).unref();
476
+ }, 120000);
477
+ timeout.unref();
478
+ child.on("error", (error) => {
479
+ output(error.message);
480
+ clearTimeout(timeout);
481
+ done(null);
482
+ });
483
+ child.on("close", (exit) => {
484
+ clearTimeout(timeout);
485
+ done(exit);
486
+ });
487
+ });
488
+ let results = [];
489
+ try {
490
+ if (!active.cancelled && !timedOut)
491
+ results = bun
492
+ ? bunReport(readFileSync(report, "utf8"), cwd, this.root)
493
+ : vitestReport(readFileSync(report, "utf8"), this.root);
494
+ }
495
+ catch {
496
+ output("\nNo readable test report was produced.");
497
+ }
498
+ finally {
499
+ rmSync(report, { force: true });
500
+ }
501
+ for (const item of run.results)
502
+ if (group.some((f) => f.file === item.file)) {
503
+ const actual = results.find((r) => r.file === item.file);
504
+ if (active.cancelled)
505
+ item.status = "cancelled";
506
+ else if (timedOut) {
507
+ item.status = "blocked";
508
+ item.reason = "This test batch exceeded two minutes";
509
+ }
510
+ else if (actual) {
511
+ Object.assign(item, actual, {
512
+ sourceRevision: run.fingerprints[item.file],
513
+ });
514
+ for (const test of item.cases || [])
515
+ if (test.failure) {
516
+ for (const secret of secrets)
517
+ test.failure = test.failure
518
+ .split(secret)
519
+ .join("[redacted]");
520
+ }
521
+ if (item.reason)
522
+ for (const secret of secrets)
523
+ item.reason = item.reason.split(secret).join("[redacted]");
524
+ }
525
+ else {
526
+ item.status = "blocked";
527
+ item.reason =
528
+ "Runner did not produce a result for this suite. Open runner output.";
529
+ }
530
+ }
531
+ if (timedOut)
532
+ output("\nThis batch exceeded two minutes; continuing with the remaining suites.\n");
533
+ if (code !== 0 &&
534
+ !active.cancelled &&
535
+ !run.results.some((r) => group.some((f) => f.file === r.file) &&
536
+ (r.status === "failed" || r.status === "blocked")))
537
+ for (const item of run.results)
538
+ if (group.some((f) => f.file === item.file)) {
539
+ item.status = "blocked";
540
+ item.reason =
541
+ "Runner exited unsuccessfully outside the suite assertions. Open runner output.";
542
+ }
543
+ this.save(run);
544
+ }
545
+ if (active.cancelled)
546
+ for (const item of run.results)
547
+ if (["queued", "running"].includes(item.status))
548
+ item.status = "cancelled";
549
+ run.status = active.cancelled
550
+ ? "cancelled"
551
+ : run.results.some((r) => r.status === "failed")
552
+ ? "failed"
553
+ : run.results.some((r) => r.status === "blocked")
554
+ ? "blocked"
555
+ : run.results.some((r) => r.status === "passed")
556
+ ? "passed"
557
+ : "skipped";
558
+ }
559
+ catch (error) {
560
+ run.status = "blocked";
561
+ output(error instanceof Error ? error.message : "Runner unavailable");
562
+ for (const item of run.results)
563
+ if (["queued", "running"].includes(item.status))
564
+ item.status = "blocked";
565
+ }
566
+ finally {
567
+ run.finishedAt = new Date().toISOString();
568
+ this.save(run);
569
+ if (this.active === active)
570
+ this.active = undefined;
571
+ }
572
+ }
573
+ }