spana-test 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +122 -246
  2. package/LICENSE +0 -0
  3. package/README.md +199 -68
  4. package/dist/{accessibility-audit-RS3VIWRT.js → accessibility-audit-YZOPUY3D.js} +7 -3
  5. package/dist/accessibility-audit-YZOPUY3D.js.map +1 -0
  6. package/dist/agent/index.d.ts +3 -84
  7. package/dist/agent/index.js +11 -10
  8. package/dist/agent/index.js.map +0 -0
  9. package/dist/allure-RNMEYTXS.js +0 -0
  10. package/dist/allure-RNMEYTXS.js.map +0 -0
  11. package/dist/{android-GFW6OXPQ.js → android-4NVTZMHL.js} +6 -2
  12. package/dist/{android-GFW6OXPQ.js.map → android-4NVTZMHL.js.map} +0 -0
  13. package/dist/app-DcLXtpv4.d.ts +908 -0
  14. package/dist/appium-server-66GVUL24.js +0 -0
  15. package/dist/appium-server-66GVUL24.js.map +0 -0
  16. package/dist/baseline-manager-5TIUCNP5.js +0 -0
  17. package/dist/baseline-manager-5TIUCNP5.js.map +0 -0
  18. package/dist/chunk-3FSZNKEF.js +0 -0
  19. package/dist/chunk-3FSZNKEF.js.map +0 -0
  20. package/dist/chunk-3SH5JQF7.js +611 -0
  21. package/dist/chunk-3SH5JQF7.js.map +1 -0
  22. package/dist/chunk-4K3FZTSV.js +179 -0
  23. package/dist/chunk-4K3FZTSV.js.map +1 -0
  24. package/dist/chunk-C4E4XULT.js +540 -0
  25. package/dist/chunk-C4E4XULT.js.map +1 -0
  26. package/dist/{chunk-3J4NG7JU.js → chunk-CY3DKTBZ.js} +8 -2
  27. package/dist/chunk-CY3DKTBZ.js.map +1 -0
  28. package/dist/chunk-DGUM43GV.js +0 -0
  29. package/dist/chunk-DGUM43GV.js.map +0 -0
  30. package/dist/chunk-DTNK54C2.js +127 -0
  31. package/dist/chunk-DTNK54C2.js.map +1 -0
  32. package/dist/{chunk-EWIR2GVV.js → chunk-H27IBIGA.js} +19 -2
  33. package/dist/chunk-H27IBIGA.js.map +1 -0
  34. package/dist/{chunk-PZYZ4O6D.js → chunk-HCG4CJKR.js} +23 -5
  35. package/dist/chunk-HCG4CJKR.js.map +1 -0
  36. package/dist/{chunk-YGHDMA6D.js → chunk-HYSTRWYN.js} +142 -41
  37. package/dist/chunk-HYSTRWYN.js.map +1 -0
  38. package/dist/chunk-IHVZKQQW.js +0 -0
  39. package/dist/chunk-IHVZKQQW.js.map +0 -0
  40. package/dist/{chunk-7VOWF42B.js → chunk-KBRLIQRA.js} +89 -8
  41. package/dist/chunk-KBRLIQRA.js.map +1 -0
  42. package/dist/chunk-KEUZLBQS.js +2935 -0
  43. package/dist/chunk-KEUZLBQS.js.map +1 -0
  44. package/dist/chunk-KJPHH2TW.js +0 -0
  45. package/dist/chunk-KJPHH2TW.js.map +0 -0
  46. package/dist/chunk-LAMTF4LX.js +89 -0
  47. package/dist/chunk-LAMTF4LX.js.map +1 -0
  48. package/dist/chunk-LCV673G3.js +3050 -0
  49. package/dist/chunk-LCV673G3.js.map +1 -0
  50. package/dist/chunk-OBCFACUW.js +0 -0
  51. package/dist/chunk-OBCFACUW.js.map +0 -0
  52. package/dist/{chunk-3TRMQCUT.js → chunk-PLE7RFQE.js} +31 -2
  53. package/dist/chunk-PLE7RFQE.js.map +1 -0
  54. package/dist/chunk-PWUJT5HE.js +5679 -0
  55. package/dist/chunk-PWUJT5HE.js.map +1 -0
  56. package/dist/{chunk-FJAJ4YNC.js → chunk-S4JVAHBR.js} +2 -2
  57. package/dist/{chunk-FJAJ4YNC.js.map → chunk-S4JVAHBR.js.map} +0 -0
  58. package/dist/chunk-S5JNNDXS.js +0 -0
  59. package/dist/chunk-S5JNNDXS.js.map +0 -0
  60. package/dist/{chunk-KYPLYRKW.js → chunk-WBBMEAHU.js} +122 -15
  61. package/dist/chunk-WBBMEAHU.js.map +1 -0
  62. package/dist/chunk-X2TJP7LB.js +0 -0
  63. package/dist/chunk-X2TJP7LB.js.map +0 -0
  64. package/dist/{chunk-5245YBLL.js → chunk-Y2RZNOKU.js} +2 -2
  65. package/dist/{chunk-5245YBLL.js.map → chunk-Y2RZNOKU.js.map} +0 -0
  66. package/dist/cli.js +62 -22
  67. package/dist/cli.js.map +1 -1
  68. package/dist/compiler-X6WTFMYF.js +0 -0
  69. package/dist/compiler-X6WTFMYF.js.map +0 -0
  70. package/dist/config-loader-J4Z2PMUQ.js +9 -0
  71. package/dist/{config-loader-QM72GKEL.js.map → config-loader-J4Z2PMUQ.js.map} +0 -0
  72. package/dist/{console-7UW7VROK.js → console-MI2XB5RG.js} +8 -2
  73. package/dist/console-MI2XB5RG.js.map +1 -0
  74. package/dist/daemon-manager-FBISTX24.js +28 -0
  75. package/dist/{discover-CAQY6EG6.js.map → daemon-manager-FBISTX24.js.map} +0 -0
  76. package/dist/{discover-CAQY6EG6.js → discover-LHEBSUIP.js} +3 -3
  77. package/dist/{installer-PVBSX7UC.js.map → discover-LHEBSUIP.js.map} +0 -0
  78. package/dist/doctor-command-WEHFANT7.js +378 -0
  79. package/dist/doctor-command-WEHFANT7.js.map +1 -0
  80. package/dist/filters-MQG2RMPX.js +26 -0
  81. package/dist/{runner-6HK62Q7B.js.map → filters-MQG2RMPX.js.map} +0 -0
  82. package/dist/flow-C2JQ7gUu.d.ts +95 -0
  83. package/dist/gherkin/steps.d.ts +2 -2
  84. package/dist/gherkin/steps.js +0 -0
  85. package/dist/gherkin/steps.js.map +0 -0
  86. package/dist/github-pr-YMWIPCCZ.js +10 -0
  87. package/dist/{session-2MZVGYAC.js.map → github-pr-YMWIPCCZ.js.map} +0 -0
  88. package/dist/html-F3X3XPSX.js +0 -0
  89. package/dist/html-F3X3XPSX.js.map +0 -0
  90. package/dist/index.d.ts +1323 -6
  91. package/dist/index.js +742 -6
  92. package/dist/index.js.map +1 -1
  93. package/dist/{init-command-U66XCM66.js → init-command-Z3QREABL.js} +60 -1
  94. package/dist/init-command-Z3QREABL.js.map +1 -0
  95. package/dist/{init-flow-command-PR7J5FBM.js → init-flow-command-4EKRVTNT.js} +2 -2
  96. package/dist/{init-flow-command-PR7J5FBM.js.map → init-flow-command-4EKRVTNT.js.map} +0 -0
  97. package/dist/{installer-PVBSX7UC.js → installer-VUPFWP5X.js} +7 -2
  98. package/dist/{validator-HZ2A3NEI.js.map → installer-VUPFWP5X.js.map} +0 -0
  99. package/dist/ios-JPK43TFZ.js +0 -0
  100. package/dist/ios-JPK43TFZ.js.map +0 -0
  101. package/dist/json-JMRPUVY2.js +0 -0
  102. package/dist/json-JMRPUVY2.js.map +0 -0
  103. package/dist/junit-HLC62MK6.js +0 -0
  104. package/dist/junit-HLC62MK6.js.map +0 -0
  105. package/dist/machine-6H25TRTU.js +0 -0
  106. package/dist/machine-6H25TRTU.js.map +0 -0
  107. package/dist/provider-YIPU5K42.js +0 -0
  108. package/dist/provider-YIPU5K42.js.map +0 -0
  109. package/dist/redact-U72BUBBR.js +0 -0
  110. package/dist/redact-U72BUBBR.js.map +0 -0
  111. package/dist/{runner-6HK62Q7B.js → runner-TF4OKPYP.js} +2 -2
  112. package/dist/runner-TF4OKPYP.js.map +1 -0
  113. package/dist/screenshot-compare-5NINZVOK.js +136 -0
  114. package/dist/screenshot-compare-5NINZVOK.js.map +1 -0
  115. package/dist/server-3MGZNK67.js +14 -0
  116. package/dist/server-3MGZNK67.js.map +1 -0
  117. package/dist/{server-PZBRGU7P.js → server-OANRDAHN.js} +15 -14
  118. package/dist/{server-PZBRGU7P.js.map → server-OANRDAHN.js.map} +1 -1
  119. package/dist/session-Daq0mE_a.d.ts +140 -0
  120. package/dist/session-Q3QYHT4Q.js +18 -0
  121. package/dist/session-Q3QYHT4Q.js.map +1 -0
  122. package/dist/{studio-command-YDWQOMRX.js → studio-command-RJYLJT4I.js} +2 -2
  123. package/dist/{studio-command-YDWQOMRX.js.map → studio-command-RJYLJT4I.js.map} +0 -0
  124. package/dist/{test-command-B2VLWGDK.js → test-command-ALH5ZQY5.js} +247 -1343
  125. package/dist/test-command-ALH5ZQY5.js.map +1 -0
  126. package/dist/{validator-HZ2A3NEI.js → validator-BLOLIHUY.js} +3 -3
  127. package/dist/validator-BLOLIHUY.js.map +1 -0
  128. package/package.json +7 -3
  129. package/studio-dist/assets/index-C-Io44gy.js +0 -0
  130. package/studio-dist/assets/index-DfM9lK4p.css +0 -0
  131. package/studio-dist/index.html +0 -0
  132. package/dist/accessibility-audit-RS3VIWRT.js.map +0 -1
  133. package/dist/chunk-3J4NG7JU.js.map +0 -1
  134. package/dist/chunk-3TRMQCUT.js.map +0 -1
  135. package/dist/chunk-7VOWF42B.js.map +0 -1
  136. package/dist/chunk-EWIR2GVV.js.map +0 -1
  137. package/dist/chunk-KYPLYRKW.js.map +0 -1
  138. package/dist/chunk-LC3QJIHY.js +0 -440
  139. package/dist/chunk-LC3QJIHY.js.map +0 -1
  140. package/dist/chunk-MCT4DYDK.js +0 -2671
  141. package/dist/chunk-MCT4DYDK.js.map +0 -1
  142. package/dist/chunk-PZYZ4O6D.js.map +0 -1
  143. package/dist/chunk-YAV6KBSW.js +0 -1318
  144. package/dist/chunk-YAV6KBSW.js.map +0 -1
  145. package/dist/chunk-YGHDMA6D.js.map +0 -1
  146. package/dist/config-loader-QM72GKEL.js +0 -9
  147. package/dist/console-7UW7VROK.js.map +0 -1
  148. package/dist/doctor-command-YGQPO7GH.js +0 -71
  149. package/dist/doctor-command-YGQPO7GH.js.map +0 -1
  150. package/dist/element-DZ0HyJ3C.d.ts +0 -25
  151. package/dist/flow-thjUxXXx.d.ts +0 -168
  152. package/dist/init-command-U66XCM66.js.map +0 -1
  153. package/dist/screenshot-compare-JFHH2WR4.js +0 -75
  154. package/dist/screenshot-compare-JFHH2WR4.js.map +0 -1
  155. package/dist/session-2MZVGYAC.js +0 -17
  156. package/dist/storybook-pBOPe_1D.d.ts +0 -451
  157. package/dist/test-command-B2VLWGDK.js.map +0 -1
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -0,0 +1,611 @@
1
+ // src/core/filters.ts
2
+ import { execFileSync } from "child_process";
3
+ import { readFileSync, existsSync, statSync } from "fs";
4
+ import { basename, dirname, relative, resolve } from "path";
5
+ var DEFAULT_LOCKFILES = /* @__PURE__ */ new Set([
6
+ "bun.lock",
7
+ "bun.lockb",
8
+ "package.json",
9
+ "package-lock.json",
10
+ "pnpm-lock.yaml",
11
+ "yarn.lock"
12
+ ]);
13
+ var DEFAULT_MAX_DIFF_BYTES = 60 * 1024;
14
+ function normalizePath(p) {
15
+ return p.replaceAll("\\", "/").replace(/^\.\//, "");
16
+ }
17
+ function isConfigOrLockfile(filePath, configPath) {
18
+ const norm = normalizePath(filePath);
19
+ const name = basename(norm);
20
+ if (DEFAULT_LOCKFILES.has(name)) return true;
21
+ if (/^spana\.config(\.[^.]+)?\.(ts|mts|js|mjs|cjs)$/.test(name)) return true;
22
+ if (configPath && normalizePath(configPath).endsWith(norm)) return true;
23
+ return false;
24
+ }
25
+ function collectGitChanges(baseRef, cwd = process.cwd(), maxDiffBytes = DEFAULT_MAX_DIFF_BYTES, runGit) {
26
+ const execGit = runGit ?? ((args, workdir) => execFileSync("git", args, {
27
+ cwd: workdir,
28
+ encoding: "utf-8",
29
+ maxBuffer: 16 * 1024 * 1024,
30
+ stdio: ["ignore", "pipe", "pipe"]
31
+ }));
32
+ let mergeBase;
33
+ try {
34
+ mergeBase = execGit(["merge-base", baseRef, "HEAD"], cwd).trim() || void 0;
35
+ } catch {
36
+ mergeBase = void 0;
37
+ }
38
+ const diffRange = mergeBase ? `${mergeBase}...HEAD` : baseRef;
39
+ const nameStatusRaw = execGit(["diff", "--name-status", diffRange], cwd);
40
+ const entries = [];
41
+ const files = [];
42
+ for (const line of nameStatusRaw.split("\n")) {
43
+ const trimmed = line.trim();
44
+ if (!trimmed) continue;
45
+ const parts = trimmed.split(/\t+/);
46
+ const status = parts[0]?.[0] ?? "M";
47
+ const filePath = normalizePath(parts[parts.length - 1] ?? "");
48
+ if (!filePath) continue;
49
+ entries.push({ path: filePath, status });
50
+ files.push(filePath);
51
+ }
52
+ const rawDiff = execGit(["diff", "--unified=3", diffRange], cwd);
53
+ const diffBytes = Buffer.byteLength(rawDiff, "utf-8");
54
+ const truncated = diffBytes > maxDiffBytes;
55
+ const diff = truncated ? rawDiff.slice(0, maxDiffBytes) : rawDiff;
56
+ return {
57
+ baseRef,
58
+ mergeBase,
59
+ files,
60
+ entries,
61
+ diff,
62
+ diffBytes,
63
+ truncated
64
+ };
65
+ }
66
+ function buildFilterCandidates(loaded, cwd = process.cwd()) {
67
+ const sourceCache = /* @__PURE__ */ new Map();
68
+ return loaded.map((entry, idx) => {
69
+ const rel = normalizePath(relative(cwd, resolve(cwd, entry.sourcePath)));
70
+ if (!sourceCache.has(entry.sourcePath)) {
71
+ let src;
72
+ if (existsSync(entry.sourcePath)) {
73
+ try {
74
+ src = readFileSync(entry.sourcePath, "utf-8");
75
+ } catch {
76
+ src = void 0;
77
+ }
78
+ }
79
+ sourceCache.set(entry.sourcePath, src);
80
+ }
81
+ return {
82
+ id: `${rel}::${entry.flow.name}#${idx}`,
83
+ name: entry.flow.name,
84
+ file: rel,
85
+ tags: entry.flow.config.tags ?? [],
86
+ platforms: entry.flow.config.platforms,
87
+ source: sourceCache.get(entry.sourcePath)
88
+ };
89
+ });
90
+ }
91
+ function decisionFilter(options) {
92
+ const filterName = options.name ?? "decision";
93
+ const threshold = options.threshold ?? 0.2;
94
+ const maxDiffBytes = options.maxDiffBytes ?? DEFAULT_MAX_DIFF_BYTES;
95
+ const maxFileBytes = options.maxFileBytes ?? 32 * 1024;
96
+ const alwaysRunTags = new Set(options.alwaysRunTags ?? []);
97
+ const runAllOnPaths = (options.runAllOnPaths ?? []).map(normalizePath);
98
+ return {
99
+ name: filterName,
100
+ async filter(flows, context) {
101
+ const { changes, configPath } = context;
102
+ if (changes.files.length === 0) {
103
+ return { exclude: {}, note: "no git changes detected" };
104
+ }
105
+ if (changes.files.some((f) => isConfigOrLockfile(f, configPath))) {
106
+ return { exclude: {}, note: "config or lockfile changed \u2014 running all flows" };
107
+ }
108
+ const matchedGlobalPath = changes.files.find(
109
+ (f) => runAllOnPaths.some((prefix) => normalizePath(f).startsWith(prefix))
110
+ );
111
+ if (matchedGlobalPath) {
112
+ return {
113
+ exclude: {},
114
+ note: `global path changed (${matchedGlobalPath}) \u2014 running all flows`
115
+ };
116
+ }
117
+ if (changes.truncated || changes.diffBytes > maxDiffBytes) {
118
+ return {
119
+ exclude: {},
120
+ note: `diff exceeds ${Math.round(maxDiffBytes / 1024)}kB cap \u2014 failing open`
121
+ };
122
+ }
123
+ const changedSet = new Set(changes.files.map(normalizePath));
124
+ const exclude = {};
125
+ let calls = 0;
126
+ let tokens = 0;
127
+ let costUsd = 0;
128
+ const eligible = [];
129
+ for (const candidate of flows) {
130
+ if (changedSet.has(normalizePath(candidate.file))) continue;
131
+ if (candidate.tags.some((t) => alwaysRunTags.has(t))) continue;
132
+ if (candidate.source && Buffer.byteLength(candidate.source, "utf-8") > maxFileBytes) {
133
+ continue;
134
+ }
135
+ eligible.push(candidate);
136
+ }
137
+ if (eligible.length === 0) {
138
+ return { exclude };
139
+ }
140
+ if (options.batchJudge) {
141
+ try {
142
+ const batch = await options.batchJudge({ candidates: eligible, changes });
143
+ calls += batch.usage?.calls ?? 1;
144
+ tokens += batch.usage?.tokens ?? 0;
145
+ costUsd += batch.usage?.costUsd ?? 0;
146
+ for (const candidate of eligible) {
147
+ const prob = batch.probabilities[candidate.id];
148
+ if (typeof prob === "number" && !Number.isNaN(prob) && prob >= 0 && prob < threshold) {
149
+ const pct = Math.round(prob * 100);
150
+ exclude[candidate.id] = batch.reasons?.[candidate.id] ?? `rated ${pct}% likely affected (< ${Math.round(threshold * 100)}%)`;
151
+ }
152
+ }
153
+ } catch {
154
+ return { exclude: {}, note: "decision model error \u2014 failed open" };
155
+ }
156
+ return {
157
+ exclude,
158
+ usage: calls > 0 ? { calls, tokens, costUsd } : void 0
159
+ };
160
+ }
161
+ if (!options.judge) {
162
+ return { exclude: {}, note: "no judge configured \u2014 failed open" };
163
+ }
164
+ for (const candidate of eligible) {
165
+ try {
166
+ const verdict = await options.judge({ candidate, changes });
167
+ calls += verdict.usage?.calls ?? 1;
168
+ tokens += verdict.usage?.tokens ?? 0;
169
+ costUsd += verdict.usage?.costUsd ?? 0;
170
+ if (typeof verdict.probability === "number" && !Number.isNaN(verdict.probability) && verdict.probability >= 0 && verdict.probability < threshold) {
171
+ const pct = Math.round(verdict.probability * 100);
172
+ exclude[candidate.id] = verdict.reason ?? `rated ${pct}% likely affected (< ${Math.round(threshold * 100)}%)`;
173
+ }
174
+ } catch {
175
+ continue;
176
+ }
177
+ }
178
+ return {
179
+ exclude,
180
+ usage: calls > 0 ? { calls, tokens, costUsd } : void 0
181
+ };
182
+ }
183
+ };
184
+ }
185
+ function createOllamaDecisionJudge(options) {
186
+ const baseUrl = (options.baseUrl ?? "http://127.0.0.1:11434").replace(/\/$/, "");
187
+ const timeoutMs = options.timeoutMs ?? 15e3;
188
+ const fetchFn = options.fetchFn ?? fetch;
189
+ return async ({ candidates, changes }) => {
190
+ const flowList = candidates.map((c, i) => `${i}: file="${c.file}", name="${c.name}", tags=[${c.tags.join(",")}]`).join("\n");
191
+ const prompt = [
192
+ "You are a conservative CI test-impact classifier. Err on the side of RUNNING tests (high recall).",
193
+ "For each E2E flow below, output a probability from 0.0 to 1.0 that the git diff could affect it.",
194
+ "Rules:",
195
+ "- If a flow's file path, name, or tags share the same feature/module/domain as ANY changed file, rate it 0.9.",
196
+ "- If unsure or possibly connected via shared UI/state/API, rate it 0.5.",
197
+ "- Rate 0.05 ONLY if the flow is clearly in a completely unrelated module.",
198
+ `Changed files: ${changes.files.join(", ")}`,
199
+ `Diff:
200
+ ${changes.diff.slice(0, 3e3)}`,
201
+ `Flows:
202
+ ${flowList}`,
203
+ 'Output compact single-line JSON mapping each index string to a number, e.g. {"0":0.9,"1":0.05}'
204
+ ].join("\n");
205
+ const res = await fetchFn(`${baseUrl}/api/generate`, {
206
+ method: "POST",
207
+ headers: { "Content-Type": "application/json" },
208
+ body: JSON.stringify({
209
+ model: options.model,
210
+ prompt,
211
+ format: "json",
212
+ stream: false,
213
+ options: { temperature: 0, num_predict: 256 }
214
+ }),
215
+ signal: AbortSignal.timeout(timeoutMs)
216
+ });
217
+ if (!res.ok) {
218
+ throw new Error(`Ollama returned HTTP ${res.status}`);
219
+ }
220
+ const payload = await res.json();
221
+ const rawJson = (payload.response ?? "{}").trim();
222
+ const parsed = JSON.parse(rawJson);
223
+ const probabilities = {};
224
+ for (let i = 0; i < candidates.length; i++) {
225
+ const cand = candidates[i];
226
+ const val = parsed[String(i)] ?? parsed[cand.id] ?? parsed[cand.name];
227
+ if (typeof val === "number" && !Number.isNaN(val)) {
228
+ probabilities[cand.id] = Math.max(0, Math.min(1, val));
229
+ } else {
230
+ probabilities[cand.id] = 1;
231
+ }
232
+ }
233
+ return {
234
+ probabilities,
235
+ usage: {
236
+ calls: 1,
237
+ tokens: (payload.prompt_eval_count ?? 0) + (payload.eval_count ?? 0),
238
+ costUsd: 0
239
+ }
240
+ };
241
+ };
242
+ }
243
+ function probabilityFromTopLogprobs(topLogprobs) {
244
+ let yesProb = 0;
245
+ let noProb = 0;
246
+ for (const entry of topLogprobs) {
247
+ const norm = entry.token.trim().toLowerCase();
248
+ const p = Math.exp(entry.logprob);
249
+ if (norm === "yes" || norm === "y" || norm === "true" || norm === "1") {
250
+ yesProb += p;
251
+ } else if (norm === "no" || norm === "n" || norm === "false" || norm === "0") {
252
+ noProb += p;
253
+ }
254
+ }
255
+ const total = yesProb + noProb;
256
+ if (total <= 0) return null;
257
+ return Math.max(0, Math.min(1, yesProb / total));
258
+ }
259
+ function createLogprobDecisionJudge(options) {
260
+ const baseUrl = (options.baseUrl ?? (options.provider === "ollama" ? "http://127.0.0.1:11434" : "http://127.0.0.1:8000/v1")).replace(/\/$/, "");
261
+ const timeoutMs = options.timeoutMs ?? 15e3;
262
+ const fetchFn = options.fetchFn ?? fetch;
263
+ return async ({ candidate, changes }) => {
264
+ const prompt = [
265
+ "You are a binary CI test-impact classifier. Answer strictly YES or NO.",
266
+ `Changed files: ${changes.files.join(", ")}`,
267
+ `Git diff:
268
+ ${changes.diff.slice(0, 3500)}`,
269
+ `Question: Could this change affect or break the E2E flow below?`,
270
+ `Flow file: ${candidate.file}`,
271
+ `Flow name: ${candidate.name}`,
272
+ `Flow tags: ${candidate.tags.join(", ") || "(none)"}`,
273
+ "Answer (YES or NO):"
274
+ ].join("\n");
275
+ if (options.provider === "ollama") {
276
+ const res2 = await fetchFn(`${baseUrl}/api/generate`, {
277
+ method: "POST",
278
+ headers: { "Content-Type": "application/json" },
279
+ body: JSON.stringify({
280
+ model: options.model,
281
+ prompt,
282
+ stream: false,
283
+ logprobs: true,
284
+ top_logprobs: 10,
285
+ options: { temperature: 0, num_predict: 1 }
286
+ }),
287
+ signal: AbortSignal.timeout(timeoutMs)
288
+ });
289
+ if (!res2.ok) throw new Error(`Ollama returned HTTP ${res2.status}`);
290
+ const data2 = await res2.json();
291
+ const top2 = data2.logprobs?.[0]?.top_logprobs;
292
+ let probability2 = top2 ? probabilityFromTopLogprobs(top2) : null;
293
+ if (probability2 === null) {
294
+ const tok = (data2.response ?? "").trim().toLowerCase();
295
+ if (tok.startsWith("n") || tok === "0" || tok === "false") probability2 = 0.05;
296
+ else probability2 = 0.95;
297
+ }
298
+ return {
299
+ probability: probability2,
300
+ usage: {
301
+ calls: 1,
302
+ tokens: (data2.prompt_eval_count ?? 0) + (data2.eval_count ?? 0),
303
+ costUsd: 0
304
+ }
305
+ };
306
+ }
307
+ const res = await fetchFn(`${baseUrl}/chat/completions`, {
308
+ method: "POST",
309
+ headers: {
310
+ "Content-Type": "application/json",
311
+ ...options.apiKey ? { Authorization: `Bearer ${options.apiKey}` } : {}
312
+ },
313
+ body: JSON.stringify({
314
+ model: options.model,
315
+ temperature: 0,
316
+ max_tokens: 1,
317
+ logprobs: true,
318
+ top_logprobs: 10,
319
+ messages: [{ role: "user", content: prompt }]
320
+ }),
321
+ signal: AbortSignal.timeout(timeoutMs)
322
+ });
323
+ if (!res.ok) throw new Error(`Decision endpoint returned HTTP ${res.status}`);
324
+ const data = await res.json();
325
+ const top = data.choices?.[0]?.logprobs?.content?.[0]?.top_logprobs;
326
+ let probability = top ? probabilityFromTopLogprobs(top) : null;
327
+ if (probability === null) {
328
+ const tok = (data.choices?.[0]?.message?.content ?? "").trim().toLowerCase();
329
+ if (tok.startsWith("n") || tok === "0" || tok === "false") probability = 0.05;
330
+ else probability = 0.95;
331
+ }
332
+ return {
333
+ probability,
334
+ usage: {
335
+ calls: 1,
336
+ tokens: (data.usage?.prompt_tokens ?? 0) + (data.usage?.completion_tokens ?? 0),
337
+ costUsd: 0
338
+ }
339
+ };
340
+ };
341
+ }
342
+ function pathRuleFilter(options) {
343
+ const filterName = options.name ?? "path-rules";
344
+ const alwaysRunTags = new Set(options.alwaysRunTags ?? []);
345
+ const runAllOnPaths = (options.runAllOnPaths ?? []).map(normalizePath);
346
+ return {
347
+ name: filterName,
348
+ filter(flows, context) {
349
+ const { changes, configPath } = context;
350
+ if (changes.files.length === 0) {
351
+ return { exclude: {}, note: "no git changes detected" };
352
+ }
353
+ if (changes.files.some((f) => isConfigOrLockfile(f, configPath))) {
354
+ return { exclude: {}, note: "config or lockfile changed \u2014 running all flows" };
355
+ }
356
+ const matchedGlobal = changes.files.find(
357
+ (f) => runAllOnPaths.some((prefix) => normalizePath(f).startsWith(prefix))
358
+ );
359
+ if (matchedGlobal) {
360
+ return { exclude: {}, note: `global path changed (${matchedGlobal}) \u2014 running all flows` };
361
+ }
362
+ const changedFiles = changes.files.map(normalizePath);
363
+ const changedSet = new Set(changedFiles);
364
+ const exclude = {};
365
+ for (const candidate of flows) {
366
+ if (changedSet.has(normalizePath(candidate.file))) continue;
367
+ if (candidate.tags.some((t) => alwaysRunTags.has(t))) continue;
368
+ const matchedRules = options.rules.filter((rule) => {
369
+ const tagOk = rule.matchFlow.tag ? candidate.tags.includes(rule.matchFlow.tag) : true;
370
+ const fileOk = rule.matchFlow.filePrefix ? normalizePath(candidate.file).startsWith(normalizePath(rule.matchFlow.filePrefix)) : true;
371
+ return (rule.matchFlow.tag || rule.matchFlow.filePrefix) && tagOk && fileOk;
372
+ });
373
+ if (matchedRules.length === 0) continue;
374
+ const watchedPrefixes = matchedRules.flatMap((r) => r.watchPaths.map(normalizePath));
375
+ const affected = changedFiles.some(
376
+ (cf) => watchedPrefixes.some((prefix) => cf.startsWith(prefix))
377
+ );
378
+ if (!affected) {
379
+ exclude[candidate.id] = `no changed files matched [${watchedPrefixes.join(", ")}]`;
380
+ }
381
+ }
382
+ return { exclude };
383
+ }
384
+ };
385
+ }
386
+ var IMPORT_SPECIFIER_RE = /(?:import|export)\s+(?:[^'"]*?\s+from\s+)?["'](\.{1,2}\/[^"']+)["']|require\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)|import\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)/g;
387
+ var RESOLVE_EXTENSIONS = [
388
+ "",
389
+ ".ts",
390
+ ".tsx",
391
+ ".mts",
392
+ ".js",
393
+ ".jsx",
394
+ ".mjs",
395
+ ".cjs",
396
+ "/index.ts",
397
+ "/index.tsx",
398
+ "/index.js",
399
+ "/index.mjs"
400
+ ];
401
+ function resolveLocalImport(fromFileAbs, specifier) {
402
+ const baseDir = dirname(fromFileAbs);
403
+ const rawTarget = resolve(baseDir, specifier);
404
+ const withoutJs = rawTarget.replace(/\.m?js$/, "");
405
+ const candidates = rawTarget !== withoutJs ? [withoutJs + ".ts", withoutJs + ".tsx", withoutJs + ".mts", rawTarget] : [rawTarget];
406
+ for (const base of candidates) {
407
+ for (const ext of RESOLVE_EXTENSIONS) {
408
+ const full = ext ? base + ext : base;
409
+ try {
410
+ if (existsSync(full) && statSync(full).isFile()) {
411
+ return full;
412
+ }
413
+ } catch {
414
+ }
415
+ }
416
+ }
417
+ return null;
418
+ }
419
+ function collectTransitiveImports(entryAbs, cwd, maxDepth, fileCache) {
420
+ const visited = /* @__PURE__ */ new Set();
421
+ const queue = [{ abs: entryAbs, depth: 0 }];
422
+ while (queue.length > 0) {
423
+ const { abs, depth } = queue.shift();
424
+ const normRel = normalizePath(relative(cwd, abs));
425
+ if (visited.has(normRel)) continue;
426
+ visited.add(normRel);
427
+ if (depth >= maxDepth) continue;
428
+ let specs = fileCache.get(abs);
429
+ if (!specs) {
430
+ specs = [];
431
+ try {
432
+ if (existsSync(abs) && statSync(abs).isFile()) {
433
+ const content = readFileSync(abs, "utf-8");
434
+ IMPORT_SPECIFIER_RE.lastIndex = 0;
435
+ let match;
436
+ while ((match = IMPORT_SPECIFIER_RE.exec(content)) !== null) {
437
+ const spec = match[1] ?? match[2] ?? match[3];
438
+ if (spec) specs.push(spec);
439
+ }
440
+ }
441
+ } catch {
442
+ }
443
+ fileCache.set(abs, specs);
444
+ }
445
+ for (const spec of specs) {
446
+ const resolved = resolveLocalImport(abs, spec);
447
+ if (resolved) {
448
+ queue.push({ abs: resolved, depth: depth + 1 });
449
+ }
450
+ }
451
+ }
452
+ return visited;
453
+ }
454
+ function deterministicImpactFilter(options = {}) {
455
+ const filterName = options.name ?? "deterministic-impact";
456
+ const alwaysRunTags = new Set(options.alwaysRunTags ?? []);
457
+ const runAllOnPaths = (options.runAllOnPaths ?? []).map(normalizePath);
458
+ const pathMappings = options.pathMappings ?? [];
459
+ const failOpenOnUnmapped = options.failOpenOnUnmappedChange ?? true;
460
+ const maxDepth = options.maxDepth ?? 12;
461
+ return {
462
+ name: filterName,
463
+ filter(flows, context) {
464
+ const { changes, configPath, cwd } = context;
465
+ if (changes.files.length === 0) {
466
+ return { exclude: {}, note: "no git changes detected" };
467
+ }
468
+ if (changes.files.some((f) => isConfigOrLockfile(f, configPath))) {
469
+ return { exclude: {}, note: "config or lockfile changed \u2014 running all flows" };
470
+ }
471
+ const matchedGlobal = changes.files.find(
472
+ (f) => runAllOnPaths.some((prefix) => normalizePath(f).startsWith(prefix))
473
+ );
474
+ if (matchedGlobal) {
475
+ return { exclude: {}, note: `global path changed (${matchedGlobal}) \u2014 running all flows` };
476
+ }
477
+ const changedFiles = changes.files.map(normalizePath);
478
+ const changedSet = new Set(changedFiles);
479
+ const fileCache = /* @__PURE__ */ new Map();
480
+ const flowDeps = /* @__PURE__ */ new Map();
481
+ const allKnownFiles = /* @__PURE__ */ new Set();
482
+ for (const candidate of flows) {
483
+ const entryAbs = resolve(cwd, candidate.file);
484
+ const deps = collectTransitiveImports(entryAbs, cwd, maxDepth, fileCache);
485
+ deps.add(normalizePath(candidate.file));
486
+ flowDeps.set(candidate.id, deps);
487
+ for (const d of deps) allKnownFiles.add(d);
488
+ }
489
+ const allWatchedPrefixes = pathMappings.flatMap((r) => r.watchPaths.map(normalizePath));
490
+ if (failOpenOnUnmapped) {
491
+ const unmapped = changedFiles.find(
492
+ (cf) => !allKnownFiles.has(cf) && !allWatchedPrefixes.some((prefix) => cf.startsWith(prefix))
493
+ );
494
+ if (unmapped) {
495
+ return {
496
+ exclude: {},
497
+ note: `unmapped file changed (${unmapped}) \u2014 failing open and running all flows`
498
+ };
499
+ }
500
+ }
501
+ const exclude = {};
502
+ for (const candidate of flows) {
503
+ if (changedSet.has(normalizePath(candidate.file))) continue;
504
+ if (candidate.tags.some((t) => alwaysRunTags.has(t))) continue;
505
+ const deps = flowDeps.get(candidate.id);
506
+ const touchedByImport = deps ? changedFiles.some((cf) => deps.has(cf)) : false;
507
+ if (touchedByImport) continue;
508
+ const matchedRules = pathMappings.filter((rule) => {
509
+ const tagOk = rule.matchFlow.tag ? candidate.tags.includes(rule.matchFlow.tag) : true;
510
+ const fileOk = rule.matchFlow.filePrefix ? normalizePath(candidate.file).startsWith(normalizePath(rule.matchFlow.filePrefix)) : true;
511
+ return (rule.matchFlow.tag || rule.matchFlow.filePrefix) && tagOk && fileOk;
512
+ });
513
+ const touchedByRule = matchedRules.some(
514
+ (rule) => changedFiles.some(
515
+ (cf) => rule.watchPaths.some((prefix) => cf.startsWith(normalizePath(prefix)))
516
+ )
517
+ );
518
+ if (touchedByRule) continue;
519
+ exclude[candidate.id] = "unaffected by changed imports or path mappings";
520
+ }
521
+ return { exclude };
522
+ }
523
+ };
524
+ }
525
+ async function applyTestFilters(items, candidates, filters, context) {
526
+ let remainingIndices = items.map((_, i) => i);
527
+ const excluded = [];
528
+ const reports = [];
529
+ for (const filter of filters) {
530
+ const activeCandidates = remainingIndices.map((idx) => candidates[idx]);
531
+ const totalBefore = activeCandidates.length;
532
+ try {
533
+ const output = await filter.filter(activeCandidates, context);
534
+ const excludeMap = output.exclude ?? {};
535
+ const nextRemaining = [];
536
+ let excludedCount = 0;
537
+ for (const idx of remainingIndices) {
538
+ const cand = candidates[idx];
539
+ const reason = excludeMap[cand.id];
540
+ if (reason !== void 0) {
541
+ excludedCount += 1;
542
+ excluded.push({
543
+ item: items[idx],
544
+ candidate: cand,
545
+ filterName: filter.name,
546
+ reason
547
+ });
548
+ } else {
549
+ nextRemaining.push(idx);
550
+ }
551
+ }
552
+ remainingIndices = nextRemaining;
553
+ reports.push({
554
+ filterName: filter.name,
555
+ total: totalBefore,
556
+ kept: remainingIndices.length,
557
+ excluded: excludedCount,
558
+ note: output.note,
559
+ usage: output.usage
560
+ });
561
+ } catch (err) {
562
+ reports.push({
563
+ filterName: filter.name,
564
+ total: totalBefore,
565
+ kept: totalBefore,
566
+ excluded: 0,
567
+ failedOpen: true,
568
+ note: `filter error (${err instanceof Error ? err.message : String(err)}) \u2014 failed open`
569
+ });
570
+ }
571
+ }
572
+ return {
573
+ kept: remainingIndices.map((idx) => items[idx]),
574
+ excluded,
575
+ reports
576
+ };
577
+ }
578
+ function formatFilterSummary(reports) {
579
+ return reports.map((r) => {
580
+ const parts = [];
581
+ if (r.usage?.calls) {
582
+ parts.push(`${r.usage.calls} call${r.usage.calls === 1 ? "" : "s"}`);
583
+ }
584
+ if (r.usage?.tokens) {
585
+ const tok = r.usage.tokens >= 1e3 ? `${(r.usage.tokens / 1e3).toFixed(1)}k` : String(r.usage.tokens);
586
+ parts.push(`${tok} tokens`);
587
+ }
588
+ if (r.usage?.costUsd !== void 0 && r.usage.costUsd > 0) {
589
+ parts.push(`$${r.usage.costUsd.toFixed(4)}`);
590
+ }
591
+ if (r.note) {
592
+ parts.push(r.note);
593
+ }
594
+ const detail = parts.length > 0 ? ` (${parts.join(", ")})` : "";
595
+ return `${r.filterName} kept ${r.kept} of ${r.total} flows, left out ${r.excluded}${detail}`;
596
+ });
597
+ }
598
+
599
+ export {
600
+ collectGitChanges,
601
+ buildFilterCandidates,
602
+ decisionFilter,
603
+ createOllamaDecisionJudge,
604
+ probabilityFromTopLogprobs,
605
+ createLogprobDecisionJudge,
606
+ pathRuleFilter,
607
+ deterministicImpactFilter,
608
+ applyTestFilters,
609
+ formatFilterSummary
610
+ };
611
+ //# sourceMappingURL=chunk-3SH5JQF7.js.map