sedum-cli 0.1.0-alpha.0 → 0.1.0-alpha.11

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,14 +1,30 @@
1
1
  import {
2
2
  MAX_PARALLEL,
3
3
  clearLocatorCache,
4
- parseParallel,
4
+ parseParallel
5
+ } from "./chunk-EFRMSNBD.js";
6
+ import {
7
+ configDiagnostic,
8
+ createCliProvider,
5
9
  renderDiagnostic
6
- } from "./chunk-BEV24G7S.js";
10
+ } from "./chunk-S7OB3JEF.js";
7
11
  import {
8
12
  ProjectConfigError,
9
13
  discoverConfiguredTests,
10
- loadProjectConfig
11
- } from "./chunk-TZGSCV23.js";
14
+ loadProjectConfig,
15
+ validAffectedGlob
16
+ } from "./chunk-FAGJCNV7.js";
17
+
18
+ // src/invocation.ts
19
+ function sedumCommand(env = process.env, script = process.argv[1] ?? "") {
20
+ if (env.npm_command === "exec" || env.npm_lifecycle_event === "npx")
21
+ return "npx sedum";
22
+ return /[\\/]node_modules[\\/]/.test(script) ? "npx sedum" : "sedum";
23
+ }
24
+ var SUBCOMMAND = /(?<![\w./-]|npx )sedum (?=(?:run|browsers|doctor|validate|init|list)\b|--help\b|--version\b)/g;
25
+ function withCommand(text, command) {
26
+ return command === "sedum" ? text : text.replace(SUBCOMMAND, `${command} `);
27
+ }
12
28
 
13
29
  // src/exit-policy.ts
14
30
  import {
@@ -33,6 +49,7 @@ function listExitCode(listing, failedBeforeListing) {
33
49
 
34
50
  // src/output.ts
35
51
  import { validateRunResult as validateRunResult2 } from "@sedum-dev/core";
52
+ import { testLabel, usageLines, visionSummary } from "@sedum-dev/reporters";
36
53
  var ansi = {
37
54
  green: "\x1B[32m",
38
55
  red: "\x1B[31m",
@@ -50,16 +67,16 @@ function stateLabel(state, verdict) {
50
67
  if (state === "running") return { text: "INCOMPLETE", color: "yellow" };
51
68
  return { text: "ERROR", color: "red" };
52
69
  }
53
- function executionLines(value) {
54
- const lines = [];
55
- const execution = value.execution;
56
- if (execution && (execution.parallel.lanes > 1 || execution.shard)) {
57
- const shard = execution.shard ? `, shard ${execution.shard.index}/${execution.shard.count} of ${execution.shard.globalSelectedTests} selected` : "";
58
- lines.push(
59
- `lanes ${execution.parallel.lanes}, provider concurrency ${execution.providerConcurrency}${shard}`
60
- );
61
- }
62
- const calls = [
70
+ function compact(lines) {
71
+ return lines.filter((line) => line !== null);
72
+ }
73
+ function resultSteps(value) {
74
+ return value.tests.flatMap(
75
+ (test) => test.attempts.flatMap((attempt) => attempt.steps)
76
+ );
77
+ }
78
+ function resultCalls(value) {
79
+ return [
63
80
  ...value.setupCalls,
64
81
  ...value.tests.flatMap(
65
82
  (test) => test.attempts.flatMap((attempt) => [
@@ -68,92 +85,180 @@ function executionLines(value) {
68
85
  ])
69
86
  )
70
87
  ];
88
+ }
89
+ function reportsExecutionPlan(execution) {
90
+ if (execution.parallel.lanes > 1) return true;
91
+ return execution.shard !== null;
92
+ }
93
+ function executionPlanLine(value) {
94
+ const execution = value.execution;
95
+ if (!execution) return null;
96
+ if (!reportsExecutionPlan(execution)) return null;
97
+ const shard = execution.shard ? `, shard ${execution.shard.index}/${execution.shard.count} of ${execution.shard.globalSelectedTests} selected` : "";
98
+ return `lanes ${execution.parallel.lanes}, provider concurrency ${execution.providerConcurrency}${shard}`;
99
+ }
100
+ function visionOutcomeLine(model, attempts) {
101
+ if (attempts.length === 0)
102
+ return `vision ${model}: enabled, no fallback attempted`;
103
+ const selected = attempts.filter(
104
+ (attempt) => attempt.outcome === "selected"
105
+ ).length;
106
+ const abstained = attempts.filter(
107
+ (attempt) => attempt.outcome === "abstained"
108
+ ).length;
109
+ const failed = attempts.filter(
110
+ (attempt) => attempt.outcome === "failed" || !attempt.outcome && attempt.failure
111
+ ).length;
112
+ const unrecorded = attempts.length - selected - abstained - failed;
113
+ const unrecordedText = unrecorded ? `, ${unrecorded} outcome unrecorded` : "";
114
+ return `vision ${model}: attempted on ${attempts.length} step(s); ${selected} selected, ${abstained} abstained, ${failed} failed${unrecordedText}`;
115
+ }
116
+ function failedClickVisionLine(steps) {
117
+ const failedClicks = steps.filter(
118
+ (step) => step.operation === "click" && (step.verdict === "failed" || step.state === "error") && !step.locator?.vision
119
+ ).length;
120
+ return failedClicks ? `vision not attempted on ${failedClicks} failed click step(s); see step errors for details` : null;
121
+ }
122
+ function visionExecutionLines(value, steps) {
123
+ const vision = value.execution?.vision;
124
+ if (!vision) return [];
125
+ const attempts = steps.flatMap(
126
+ (step) => step.locator?.vision ? [step.locator.vision] : []
127
+ );
128
+ const warnings = {
129
+ accepted: null,
130
+ rejected: "vision warning: OpenRouter rejected OPEN_ROUTER_API_KEY, so vision fallback cannot work. Check it with `sedum doctor --vision`.",
131
+ unreachable: "vision warning: OpenRouter could not be reached to check OPEN_ROUTER_API_KEY."
132
+ };
133
+ return compact([
134
+ visionOutcomeLine(vision.model, attempts),
135
+ failedClickVisionLine(steps),
136
+ warnings[vision.key]
137
+ ]);
138
+ }
139
+ function rateLimitLine(value) {
140
+ const calls = resultCalls(value);
71
141
  const limited = calls.filter((call) => call.rateLimited).length;
142
+ if (limited === 0) return null;
72
143
  const waitMs = calls.reduce(
73
144
  (sum, call) => sum + (call.rateLimitWaitMs ?? 0),
74
145
  0
75
146
  );
76
- if (limited > 0)
77
- lines.push(
78
- `provider rate limited ${limited} call(s), waited ${(waitMs / 1e3).toFixed(1)}s in shared cooldowns`
79
- );
80
- const conflicts = value.tests.flatMap((test) => test.attempts).flatMap((attempt) => attempt.steps).filter((step) => step.locator?.cache?.reason === "conflict").length;
81
- if (conflicts > 0)
82
- lines.push(
83
- `cache ${conflicts} locator cache write conflict(s); the model result was used`
84
- );
85
- return lines;
147
+ return `provider rate limited ${limited} call(s), waited ${(waitMs / 1e3).toFixed(1)}s in shared cooldowns`;
148
+ }
149
+ function cacheConflictLine(steps) {
150
+ const conflicts = steps.filter(
151
+ (step) => step.locator?.cache?.reason === "conflict"
152
+ ).length;
153
+ return conflicts > 0 ? `cache ${conflicts} locator cache write conflict(s); the model result was used` : null;
154
+ }
155
+ function executionLines(value) {
156
+ const steps = resultSteps(value);
157
+ return [
158
+ ...compact([executionPlanLine(value)]),
159
+ ...visionExecutionLines(value, steps),
160
+ ...compact([rateLimitLine(value), cacheConflictLine(steps)])
161
+ ];
162
+ }
163
+ function cacheLine(step) {
164
+ const cache = step.locator?.cache;
165
+ if (!cache) return null;
166
+ const reason = cache.reason ? ` (${cache.reason})` : "";
167
+ const fallback = cache.fallbackCalledModel ? ", model fallback" : "";
168
+ const changed = cache.targetChanged ? ", target changed" : "";
169
+ return ` step ${step.index}: cache ${cache.outcome}${reason}${fallback}${changed}`;
170
+ }
171
+ function testDetailLines(test, flagCounts) {
172
+ const retry = test.attempts.length > 1 ? ` attempts ${test.attempts.length} (${test.attempts.map((attempt) => attempt.verdict ?? attempt.state).join(" -> ")})` : null;
173
+ const selected = test.attempts.find(
174
+ (attempt) => attempt.id === test.selectedAttemptId
175
+ );
176
+ const caches = (selected?.steps ?? []).flatMap((step) => {
177
+ for (const flag of step.flags) flagCounts[flag] += 1;
178
+ const line = cacheLine(step);
179
+ return line ? [line] : [];
180
+ });
181
+ const details = [...compact([retry]), ...caches];
182
+ return details.length ? [testLabel(test), ...details] : [];
183
+ }
184
+ function hasOutsideGitStep(value) {
185
+ return resultSteps(value).some(
186
+ (step) => step.locator?.cache?.reason === "outside_git"
187
+ );
188
+ }
189
+ function discoveryLine(problem) {
190
+ const location = problem.line === void 0 ? "" : `:${problem.line}:${problem.col ?? 1}`;
191
+ return `discovery ${problem.file}${location}: ${problem.message} Fix: ${problem.fix}`;
192
+ }
193
+ function testCountLine(value) {
194
+ const errored = value.tests.filter((test) => test.state === "error").length;
195
+ const errorCount = errored ? `, ${errored} could not run` : "";
196
+ return `tests ${value.totals.selectedTests} selected, ${value.totals.executedTests} executed, ${value.totals.passedTests} passed, ${value.totals.failedTests} failed${errorCount}`;
197
+ }
198
+ function flagCountLine(value, counts) {
199
+ const flaky = value.tests.filter(
200
+ (test) => test.flags.includes("flaky")
201
+ ).length;
202
+ return `flags ${value.totals.flaggedSteps} flagged step(s), low_confidence ${counts.low_confidence}, contradiction ${counts.contradiction}, flaky ${flaky} test(s)`;
203
+ }
204
+ function visionDetailLines(value) {
205
+ return value.tests.flatMap(
206
+ (test) => test.attempts.flatMap(
207
+ (attempt) => attempt.steps.flatMap((step) => {
208
+ const vision = visionSummary(step);
209
+ if (!vision) return [];
210
+ return [
211
+ `${test.file} \xB7 attempt ${attempt.ordinal} \xB7 step ${step.index}: ${vision}`.replace(
212
+ // Strip terminal control characters from provider metadata.
213
+ // eslint-disable-next-line no-control-regex
214
+ /[\u0000-\u001f\u007f-\u009f]/g,
215
+ " "
216
+ )
217
+ ];
218
+ })
219
+ )
220
+ );
221
+ }
222
+ function artifactLines(artifacts) {
223
+ if (!artifacts.authoritative)
224
+ return [`result unavailable (intended ${artifacts.resultPath})`];
225
+ return compact([
226
+ `result ${artifacts.resultPath}`,
227
+ artifacts.htmlPath ? `html ${artifacts.htmlPath}` : null,
228
+ artifacts.markdownPath ? `markdown ${artifacts.markdownPath}` : null,
229
+ artifacts.junitPath ? `junit ${artifacts.junitPath}` : null,
230
+ artifacts.reporterPath ? `reporter ${artifacts.reporterPath}` : null
231
+ ]);
232
+ }
233
+ function costLines(value) {
234
+ const unknown = !value.totals.costComplete || value.totals.costUsd === null ? "cost unknown or incomplete" : null;
235
+ return [...usageLines(value), ...compact([unknown])];
86
236
  }
87
237
  function renderRunSummary(result, capabilities, artifacts, showCosts) {
88
238
  const value = validateRunResult2(result);
89
239
  const color = capabilities.stdoutIsTTY && capabilities.color;
90
240
  const lines = [];
91
241
  const flagCounts = { low_confidence: 0, contradiction: 0 };
92
- for (const test of value.tests) {
93
- const label = stateLabel(test.state, test.verdict);
94
- const flags = test.flags.length ? ` [${test.flags.join(", ")}]` : "";
242
+ for (const test of value.tests)
243
+ lines.push(...testDetailLines(test, flagCounts));
244
+ if (hasOutsideGitStep(value))
95
245
  lines.push(
96
- `test ${paint(label.text, label.color, color)} ${test.file}${flags}`
246
+ "cache off: this project is not a Git checkout; run `git init` to cache locator results"
97
247
  );
98
- if (test.attempts.length > 1)
99
- lines.push(
100
- ` attempts ${test.attempts.length} (${test.attempts.map((attempt) => attempt.verdict ?? attempt.state).join(" -> ")})`
101
- );
102
- const selected = test.attempts.find(
103
- (attempt) => attempt.id === test.selectedAttemptId
104
- );
105
- for (const step of selected?.steps ?? []) {
106
- for (const flag of step.flags) flagCounts[flag] += 1;
107
- const cache = step.locator?.cache;
108
- if (cache) {
109
- const reason = cache.reason ? ` (${cache.reason})` : "";
110
- const fallback = cache.fallbackCalledModel ? ", model fallback" : "";
111
- const changed = cache.targetChanged ? ", target changed" : "";
112
- lines.push(
113
- ` step ${step.index}: cache ${cache.outcome}${reason}${fallback}${changed}`
114
- );
115
- }
116
- }
117
- }
118
248
  const runLabel = stateLabel(value.state, value.verdict);
119
249
  lines.push(`run ${paint(runLabel.text, runLabel.color, color)}`);
120
250
  for (const problem of value.discoveryProblems ?? [])
121
- lines.push(
122
- `discovery ${problem.file}${problem.line === void 0 ? "" : `:${problem.line}:${problem.col ?? 1}`}: ${problem.message} Fix: ${problem.fix}`
123
- );
124
- lines.push(
125
- `tests ${value.totals.selectedTests} selected, ${value.totals.executedTests} executed, ${value.totals.passedTests} passed, ${value.totals.failedTests} failed`
126
- );
127
- lines.push(
128
- `flags ${value.totals.flaggedSteps} flagged step(s), low_confidence ${flagCounts.low_confidence}, contradiction ${flagCounts.contradiction}`
129
- );
251
+ lines.push(discoveryLine(problem));
252
+ lines.push(testCountLine(value), flagCountLine(value, flagCounts));
130
253
  lines.push(...executionLines(value));
131
- if (artifacts.authoritative) {
132
- lines.push(`progress ${artifacts.progressPath}`);
133
- lines.push(`result ${artifacts.resultPath}`);
134
- if (artifacts.htmlPath) lines.push(`html ${artifacts.htmlPath}`);
135
- if (artifacts.markdownPath)
136
- lines.push(`markdown ${artifacts.markdownPath}`);
137
- if (artifacts.junitPath) lines.push(`junit ${artifacts.junitPath}`);
138
- if (artifacts.reporterPath)
139
- lines.push(`reporter ${artifacts.reporterPath}`);
140
- } else {
141
- lines.push(`result unavailable (intended ${artifacts.resultPath})`);
142
- }
143
- if (capabilities.stdoutIsTTY || showCosts) {
144
- lines.push(
145
- `model ${value.totals.modelCalls} call(s), ${value.totals.inputTokens} input tokens, ${value.totals.outputTokens} output tokens`
146
- );
147
- lines.push(
148
- value.totals.costComplete && value.totals.costUsd !== null ? `cost $${value.totals.costUsd.toFixed(6)}` : "cost unknown or incomplete"
149
- );
150
- }
254
+ lines.push(...visionDetailLines(value), ...artifactLines(artifacts));
255
+ if (capabilities.stdoutIsTTY || showCosts) lines.push(...costLines(value));
151
256
  return `${lines.join("\n")}
152
257
  `;
153
258
  }
154
259
 
155
260
  // src/run-cli.ts
156
- import { Command, CommanderError, InvalidArgumentError } from "commander";
261
+ import { Command as Command2, CommanderError } from "commander";
157
262
  import {
158
263
  createTerminalReporter,
159
264
  ReporterLifecycle
@@ -162,7 +267,7 @@ import {
162
267
  // src/list-command.ts
163
268
  import {
164
269
  listTests,
165
- loadFlowFile
270
+ loadListingEntries
166
271
  } from "@sedum-dev/core";
167
272
 
168
273
  // src/project-context.ts
@@ -265,12 +370,9 @@ async function executeListCommand(options) {
265
370
  const { discovery } = context;
266
371
  if (discovery.problems.length)
267
372
  return { discovery, configErrors: [], listing: null };
268
- const parsed = [];
269
- for (const file of discovery.tests)
270
- parsed.push({
271
- file,
272
- result: await loadFlowFile(file, { repoRoot: discovery.root })
273
- });
373
+ const parsed = await loadListingEntries(discovery.tests, {
374
+ repoRoot: discovery.root
375
+ });
274
376
  return {
275
377
  discovery,
276
378
  configErrors: [],
@@ -285,32 +387,37 @@ import {
285
387
  validateProject
286
388
  } from "@sedum-dev/core";
287
389
  import path2 from "path";
288
- var CLASSIFICATION_MODEL = "jev-latest";
289
- var createTypeSafeClassifier = async ({
290
- apiKey
291
- }) => {
292
- const { TypeSafeAdapter } = await import("@sedum-dev/provider-typesafe");
293
- return new TypeSafeAdapter(apiKey ? { apiKey } : {});
294
- };
295
390
  function emptyProjectProblem(paths, testDirectory) {
296
391
  const shown = paths.length ? paths.join(", ") : testDirectory || ".";
297
392
  return {
298
393
  code: "missing_path",
299
394
  path: shown,
300
- message: `No *.test.yaml or *.module.yaml files were found under ${shown}.`,
395
+ message: `No *.test.ts, *.test.yaml, or *.module.yaml files were found under ${shown}.`,
301
396
  fix: paths.length ? "Pass paths relative to the project root that contain tests or modules." : "Add tests under tests.directory, or correct tests.directory/include/exclude in sedum.config.yaml."
302
397
  };
303
398
  }
304
399
  var missingKey = {
305
400
  code: "missing_key",
306
- message: "`sedum validate --online` needs a configured TypeSafe provider.",
307
- fix: "Set TYPESAFE_API_KEY in the environment or the project-root .env and rerun, or omit --online to validate offline."
401
+ message: "`sedum validate --online` needs a configured model provider.",
402
+ fix: "Set the selected provider's credentials (TYPESAFE_API_KEY, or CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_AUTH_TOKEN/CLOUDFLARE_API_TOKEN) and rerun; otherwise omit --online."
308
403
  };
309
404
  async function onlineProvider(options) {
310
405
  try {
311
- const { apiKey } = await loadProjectConfig(options.cwd);
312
- return await options.createProvider(apiKey ? { apiKey } : {});
406
+ const config = await loadProjectConfig(options.cwd);
407
+ return {
408
+ provider: await options.createProvider({
409
+ ...config.apiKey ? { apiKey: config.apiKey } : {},
410
+ baseURL: config.providerBaseUrl,
411
+ model: config.providerModel,
412
+ ...config.providerName === "clef" ? {
413
+ providerName: config.providerName,
414
+ ...config.cloudflareAccountId ? { accountId: config.cloudflareAccountId } : {}
415
+ } : {}
416
+ }),
417
+ model: config.providerModel
418
+ };
313
419
  } catch (error) {
420
+ if (error instanceof ProjectConfigError) return configDiagnostic(error);
314
421
  if (error instanceof ProviderError && error.code === "configuration")
315
422
  return missingKey;
316
423
  return {
@@ -320,6 +427,13 @@ async function onlineProvider(options) {
320
427
  };
321
428
  }
322
429
  }
430
+ var createSelectedClassifier = (options) => createCliProvider({
431
+ providerName: options.providerName ?? "typesafe",
432
+ apiKey: options.apiKey,
433
+ cloudflareAccountId: options.accountId,
434
+ providerModel: options.model,
435
+ providerBaseUrl: options.baseURL
436
+ });
323
437
  async function executeValidateCommand(options) {
324
438
  const context = await loadProjectContext(options.paths, options.cwd);
325
439
  if (!context.config)
@@ -351,14 +465,17 @@ async function executeValidateCommand(options) {
351
465
  null
352
466
  );
353
467
  let provider;
468
+ let classificationModel = config.providerModel;
354
469
  if (options.online) {
355
470
  const prepared = await onlineProvider(options);
356
471
  if ("code" in prepared) return stop(discovery, prepared);
357
- provider = prepared;
472
+ provider = prepared.provider;
473
+ classificationModel = prepared.model;
358
474
  }
359
475
  const cache = await FileClassificationCache.load(
360
476
  path2.join(discovery.root, ".sedum", "classifications.json"),
361
- CLASSIFICATION_MODEL
477
+ classificationModel,
478
+ config.providerName
362
479
  );
363
480
  const result = await validateProject(discovery, {
364
481
  repoRoot: discovery.root,
@@ -393,7 +510,7 @@ function renderValidation(result, root, capabilities) {
393
510
  for (const item of result.diagnostics) {
394
511
  const where = `${displayPath(root, item.source.file)}:${item.source.line}:${item.source.col}`;
395
512
  const label = item.severity === "warning" ? paint2(`warning ${item.code}`, "yellow", capabilities) : item.code === NOT_CHECKED_OFFLINE_CODE ? paint2("not checked offline", "yellow", capabilities) : paint2(`error ${item.code}`, "red", capabilities);
396
- const fix = item.code === NOT_CHECKED_OFFLINE_CODE ? "Rephrase with a supported verb, or run `sedum validate --online` with TYPESAFE_API_KEY set and commit .sedum/classifications.json." : item.fix;
513
+ const fix = item.code === NOT_CHECKED_OFFLINE_CODE ? "Rephrase with a supported verb, or run `sedum validate --online` with a provider API key configured and commit .sedum/classifications.json." : item.fix;
397
514
  lines.push(`${where}: ${label}: ${item.message}`, ` Fix: ${fix}`);
398
515
  }
399
516
  const { counts } = result;
@@ -478,90 +595,180 @@ function renderListJson(listing) {
478
595
  `;
479
596
  }
480
597
 
481
- // src/run-cli.ts
482
- var plainOutput = {
483
- stdoutIsTTY: false,
484
- stderrIsTTY: false,
485
- color: false
598
+ // src/cli-arguments.ts
599
+ import { InvalidArgumentError } from "commander";
600
+ var RawOptionText = class {
601
+ constructor(value) {
602
+ this.value = value;
603
+ }
604
+ value;
605
+ get trimmed() {
606
+ return this.value.trim();
607
+ }
608
+ get number() {
609
+ return Number(this.value);
610
+ }
611
+ get projectRelativeGlob() {
612
+ return [
613
+ this.trimmed.length > 0,
614
+ !this.value.startsWith("/"),
615
+ !/^[A-Za-z]:[/\\]/u.test(this.value),
616
+ !this.value.split(/[/\\]/u).includes("..")
617
+ ].every(Boolean);
618
+ }
486
619
  };
487
- function collectOrigin(value, previous) {
488
- try {
489
- return [...previous, new URL(value).origin];
490
- } catch {
491
- throw new InvalidArgumentError(
492
- `Invalid origin ${JSON.stringify(value)}. Use an absolute URL such as https://example.com.`
493
- );
620
+ var CommanderScalarParser = class {
621
+ callback;
622
+ constructor(parser) {
623
+ this.callback = (value) => parser.parse(new RawOptionText(value));
494
624
  }
625
+ };
626
+ var CommanderCollector = class {
627
+ callback;
628
+ constructor(parser) {
629
+ this.callback = (value, previous) => parser.parse(new RawOptionText(value), previous);
630
+ }
631
+ };
632
+ function invalid(message) {
633
+ throw new InvalidArgumentError(message);
495
634
  }
496
- function collectValue(value, previous) {
497
- if (!value.trim()) throw new InvalidArgumentError("Value must not be blank.");
498
- return [...previous, value];
499
- }
500
- var REPORTERS = ["list", "steps", "terminal", "json", "markdown", "junit"];
501
- function collectReporter(value, previous) {
502
- const selected = [...previous];
503
- for (const item of value.split(",").map((name) => name.trim())) {
504
- if (!REPORTERS.includes(item))
505
- throw new InvalidArgumentError(
506
- `Unknown reporter ${JSON.stringify(item)}. Use list or steps for terminal output, or terminal, json, markdown, or junit.`
635
+ var OriginCollector = class {
636
+ parse(text, previous) {
637
+ try {
638
+ return [...previous, new URL(text.value).origin];
639
+ } catch {
640
+ return invalid(
641
+ `Invalid origin ${JSON.stringify(text.value)}. Use an absolute URL such as https://example.com.`
507
642
  );
508
- if (!selected.includes(item)) selected.push(item);
643
+ }
644
+ }
645
+ };
646
+ var ValueCollector = class {
647
+ parse(text, previous) {
648
+ if (!text.trimmed) invalid("Value must not be blank.");
649
+ return [...previous, text.value];
650
+ }
651
+ };
652
+ var REPORTERS = ["list", "steps", "terminal", "json", "markdown", "junit"];
653
+ var ReporterCollector = class {
654
+ parse(text, previous) {
655
+ const selected = [...previous];
656
+ for (const item of text.value.split(",").map((name) => name.trim())) {
657
+ if (!REPORTERS.includes(item))
658
+ invalid(
659
+ `Unknown reporter ${JSON.stringify(item)}. Use list or steps for terminal output, or terminal, json, markdown, or junit.`
660
+ );
661
+ if (!selected.includes(item)) selected.push(item);
662
+ }
663
+ return selected;
664
+ }
665
+ };
666
+ var GlobCollector = class {
667
+ parse(text, previous) {
668
+ if (!text.projectRelativeGlob)
669
+ invalid("Glob must be a nonempty project-relative path without '..'.");
670
+ return [...previous, text.value];
671
+ }
672
+ };
673
+ var LabelCollector = class {
674
+ parse(text, previous) {
675
+ const labels = text.value.split(",").map((item) => item.trim());
676
+ if (labels.some((item) => !item))
677
+ invalid("Labels must be nonempty comma-separated tags.");
678
+ return [...previous, ...labels];
679
+ }
680
+ };
681
+ var RangedNumberParser = class {
682
+ constructor(range) {
683
+ this.range = range;
684
+ }
685
+ range;
686
+ parse(text) {
687
+ const { number } = text;
688
+ const minimumSatisfied = this.range.minimumInclusive ? number >= this.range.minimum : number > this.range.minimum;
689
+ const valid = [
690
+ Number.isFinite(number),
691
+ minimumSatisfied,
692
+ number <= this.range.maximum,
693
+ !this.range.safeInteger || Number.isSafeInteger(number),
694
+ !this.range.digitsOnly || /^[1-9]\d*$/u.test(text.value),
695
+ !this.range.nonblank || text.trimmed.length > 0
696
+ ];
697
+ return valid.every(Boolean) ? number : invalid(this.range.error);
698
+ }
699
+ };
700
+ var ParallelParser = class {
701
+ parse(text) {
702
+ return parseParallel(text.value) ?? invalid(`Expected auto or an integer from 1 to ${MAX_PARALLEL}.`);
509
703
  }
510
- return selected;
704
+ };
705
+ function scalar(parser) {
706
+ return new CommanderScalarParser(parser).callback;
511
707
  }
512
- function collectGlob(value, previous) {
513
- if (!value.trim() || value.startsWith("/") || /^[A-Za-z]:[/\\]/u.test(value) || value.split(/[/\\]/u).includes(".."))
514
- throw new InvalidArgumentError(
515
- "Glob must be a nonempty project-relative path without '..'."
516
- );
517
- return [...previous, value];
708
+ function collector(parser) {
709
+ return new CommanderCollector(parser).callback;
518
710
  }
519
- function collectLabels(value, previous) {
520
- const labels = value.split(",").map((item) => item.trim());
521
- if (labels.some((item) => !item))
522
- throw new InvalidArgumentError(
523
- "Labels must be nonempty comma-separated tags."
524
- );
525
- return [...previous, ...labels];
526
- }
527
- function nonnegativeInteger(value) {
528
- const number = Number(value);
529
- if (!Number.isSafeInteger(number) || number < 0 || number > 20)
530
- throw new InvalidArgumentError("Expected an integer from 0 to 20.");
531
- return number;
532
- }
533
- function nonnegativeSlow(value) {
534
- const number = Number(value);
535
- if (!Number.isSafeInteger(number) || number < 0 || number > 3e4)
536
- throw new InvalidArgumentError("Expected milliseconds from 0 to 30000.");
537
- return number;
538
- }
539
- function parallelValue(value) {
540
- const parsed = parseParallel(value);
541
- if (parsed === null)
542
- throw new InvalidArgumentError(
543
- `Expected auto or an integer from 1 to ${MAX_PARALLEL}.`
544
- );
545
- return parsed;
711
+ function rangedNumber(range) {
712
+ return scalar(new RangedNumberParser(range));
546
713
  }
547
- function positiveCount(maximum) {
548
- return (value) => {
549
- const number = Number(value);
550
- if (!/^[1-9]\d*$/u.test(value) || !Number.isSafeInteger(number) || number > maximum)
551
- throw new InvalidArgumentError(
552
- `Expected an integer from 1 to ${maximum}.`
553
- );
554
- return number;
555
- };
714
+ var collectOrigin = collector(new OriginCollector());
715
+ var collectValue = collector(new ValueCollector());
716
+ var collectReporter = collector(new ReporterCollector());
717
+ var collectGlob = collector(new GlobCollector());
718
+ function collectAffectedGlob(value, previous) {
719
+ if (!validAffectedGlob(value))
720
+ invalid("Affected ignore must be a valid repository-relative POSIX glob.");
721
+ return [...previous, value];
556
722
  }
557
- function positiveMinutes(value) {
558
- const number = Number(value);
559
- if (!Number.isFinite(number) || number <= 0 || number > 1440)
560
- throw new InvalidArgumentError(
561
- "Expected minutes greater than 0 and at most 1440."
562
- );
563
- return number;
723
+ var collectLabels = collector(new LabelCollector());
724
+ var nonnegativeInteger = rangedNumber({
725
+ minimum: 0,
726
+ maximum: 20,
727
+ minimumInclusive: true,
728
+ safeInteger: true,
729
+ digitsOnly: false,
730
+ nonblank: false,
731
+ error: "Expected an integer from 0 to 20."
732
+ });
733
+ var nonnegativeSlow = rangedNumber({
734
+ minimum: 0,
735
+ maximum: 3e4,
736
+ minimumInclusive: true,
737
+ safeInteger: true,
738
+ digitsOnly: false,
739
+ nonblank: false,
740
+ error: "Expected milliseconds from 0 to 30000."
741
+ });
742
+ var parallelValue = scalar(new ParallelParser());
743
+ function positiveCount(maximum) {
744
+ return rangedNumber({
745
+ minimum: 1,
746
+ maximum,
747
+ minimumInclusive: true,
748
+ safeInteger: true,
749
+ digitsOnly: true,
750
+ nonblank: false,
751
+ error: `Expected an integer from 1 to ${maximum}.`
752
+ });
564
753
  }
754
+ var positiveMinutes = rangedNumber({
755
+ minimum: 0,
756
+ maximum: 1440,
757
+ minimumInclusive: false,
758
+ safeInteger: false,
759
+ digitsOnly: false,
760
+ nonblank: false,
761
+ error: "Expected minutes greater than 0 and at most 1440."
762
+ });
763
+ var relevanceThreshold = rangedNumber({
764
+ minimum: 0,
765
+ maximum: 1,
766
+ minimumInclusive: true,
767
+ safeInteger: false,
768
+ digitsOnly: false,
769
+ nonblank: true,
770
+ error: "Expected a probability from 0 to 1."
771
+ });
565
772
  function commandHelp(command, writeErr) {
566
773
  command.outputHelp({ error: true });
567
774
  const commandPath = [];
@@ -573,16 +780,26 @@ function commandHelp(command, writeErr) {
573
780
  `
574
781
  );
575
782
  }
783
+
784
+ // src/run-cli.ts
785
+ var plainOutput = {
786
+ stdoutIsTTY: false,
787
+ stderrIsTTY: false,
788
+ color: false
789
+ };
576
790
  async function runCli(args, version, runtime = {}) {
577
791
  const stdout = [];
578
792
  const stderr = [];
579
- const writeOut = runtime.stdout ?? ((value) => stdout.push(value));
580
- const writeErr = runtime.stderr ?? ((value) => stderr.push(value));
793
+ const command = runtime.command ?? "sedum";
794
+ const rawOut = runtime.stdout ?? ((value) => stdout.push(value));
795
+ const rawErr = runtime.stderr ?? ((value) => stderr.push(value));
796
+ const writeOut = (value) => rawOut(withCommand(value, command));
797
+ const writeErr = (value) => rawErr(withCommand(value, command));
581
798
  const capabilities = runtime.capabilities ?? plainOutput;
582
- const executeRun = runtime.executeRun ?? (async (options) => (await import("./run-command-VAVFPCWG.js")).executeRunCommand(options));
799
+ const executeRun = runtime.executeRun ?? (async (options) => (await import("./run-command-ZEIANJWZ.js")).executeRunCommand(options));
583
800
  const cwd = runtime.cwd ?? process.cwd();
584
801
  let exitCode = 3;
585
- const program = new Command().name("sedum").description(
802
+ const program = new Command2().name("sedum").description(
586
803
  "Run plain-English browser tests with deterministic automation."
587
804
  ).version(version, "-v, --version", "print the installed Sedum version").helpOption("-h, --help", "show command help").showSuggestionAfterError().showHelpAfterError("Run `sedum --help` to see available commands.").exitOverride().configureOutput({
588
805
  writeOut,
@@ -597,7 +814,7 @@ async function runCli(args, version, runtime = {}) {
597
814
  "after",
598
815
  "\nCreates a config, a SauceDemo example, .env.example, and ignore rules.\nExisting files are never replaced.\n"
599
816
  ).action(async () => {
600
- const { executeInitCommand } = await import("./init-command-54R2FQ2U.js");
817
+ const { executeInitCommand } = await import("./init-command-62IUO5LA.js");
601
818
  const interactive = capabilities.stdoutIsTTY && (process.stdin.isTTY === true || runtime.confirmInit !== void 0);
602
819
  const confirm = runtime.confirmInit ?? (interactive ? async (question) => {
603
820
  const { createInterface } = await import("readline/promises");
@@ -626,6 +843,23 @@ async function runCli(args, version, runtime = {}) {
626
843
  program.command("run").description("run configured tests, files, or directories").argument(
627
844
  "[paths...]",
628
845
  "test files or directories relative to the project root"
846
+ ).option(
847
+ "--affected",
848
+ "experimental: send Git diff and test sources to the text provider; run relevant tests",
849
+ false
850
+ ).option("--base <ref>", "base ref for --affected (default main or master)").option(
851
+ "--affected-ignore <glob>",
852
+ "exclude matching repository-relative diff paths (repeatable)",
853
+ collectAffectedGlob,
854
+ []
855
+ ).option(
856
+ "--threshold <probability>",
857
+ "minimum relevance probability for --affected (default 0.3)",
858
+ relevanceThreshold
859
+ ).option(
860
+ "--selection-only",
861
+ "with --affected, print selection JSON without running tests (calls the text provider)",
862
+ false
629
863
  ).option(
630
864
  "--include <glob>",
631
865
  "include matching project-relative paths (repeatable)",
@@ -646,7 +880,12 @@ async function runCli(args, version, runtime = {}) {
646
880
  "match id or description substring (repeatable)",
647
881
  collectValue,
648
882
  []
649
- ).option("--env <name>", "select a named environment").option("--browser <kind>", "chrome or chromium").option(
883
+ ).option(
884
+ "--id <id>",
885
+ "select a test by its exact id (repeatable)",
886
+ collectValue,
887
+ []
888
+ ).option("--env <name>", "select a named environment").option("--browser <kind>", "chrome or chromium").option("--vision", "enable vision fallback for ambiguous clicks").option("--no-vision", "disable vision fallback").option("--vision-model <model>", "override the OpenRouter vision model").option(
650
889
  "--url-override <url>",
651
890
  "replace entry URL origin for preview deployments"
652
891
  ).option("--output-dir <path>", "run output directory").option("--reporter-dir <path>", "reporter artifact directory").option("--headed", "show the browser", false).option(
@@ -694,7 +933,7 @@ async function runCli(args, version, runtime = {}) {
694
933
  false
695
934
  ).addHelpText(
696
935
  "after",
697
- "\nPrerequisites:\n Install Chromium with `sedum browsers install chromium` and set TYPESAFE_API_KEY.\n\nExamples:\n sedum run tests/login.test.yaml\n sedum run tests/login.test.yaml --strict --costs\n"
936
+ "\nPrerequisites:\n Install Chromium with `sedum browsers install chromium` and set TYPESAFE_API_KEY (and TYPESAFE_BASE_URL for a compatible provider).\n\nExamples:\n sedum run tests/login.test.ts\n sedum run tests/login.test.ts --id 'tests/login.test.ts#signs in'\n sedum run tests/login.test.yaml --strict --costs\n"
698
937
  ).action(
699
938
  async (paths, options) => {
700
939
  if (options.shardIndex === void 0 !== (options.shardCount === void 0) || options.shardIndex !== void 0 && options.shardIndex > options.shardCount) {
@@ -708,6 +947,79 @@ async function runCli(args, version, runtime = {}) {
708
947
  exitCode = 3;
709
948
  return;
710
949
  }
950
+ if (options.affected && (options.shardCount ?? 1) > 1) {
951
+ writeErr(
952
+ renderDiagnostic({
953
+ code: "affected_sharding_unsupported",
954
+ message: "--affected cannot be combined with multiple shards: independent relevance selections can leave tests unexecuted.",
955
+ fix: "Remove the shard options, or run without --affected. --parallel is supported."
956
+ })
957
+ );
958
+ exitCode = 3;
959
+ return;
960
+ }
961
+ if (!options.affected && (options.base !== void 0 || options.affectedIgnore.length > 0 || options.threshold !== void 0 || options.selectionOnly)) {
962
+ writeErr(
963
+ "--base, --threshold, --affected-ignore, and --selection-only require --affected.\n"
964
+ );
965
+ exitCode = 3;
966
+ return;
967
+ }
968
+ if (options.affected) {
969
+ const { selectAffectedTests, AffectedSelectionError } = await import("./affected-selection-WV5WY5NQ.js");
970
+ const { ProviderError: ProviderError2 } = await import("@sedum-dev/core");
971
+ writeErr(
972
+ "Experimental selection sends the committed Git diff and complete test/module sources to the configured provider. Tracked local edits are refused. Full CI is still recommended.\n"
973
+ );
974
+ try {
975
+ const selection = await selectAffectedTests({
976
+ cwd,
977
+ paths,
978
+ filters: {
979
+ include: options.include,
980
+ exclude: options.exclude,
981
+ labels: options.labels,
982
+ names: options.name,
983
+ ids: options.id
984
+ },
985
+ threshold: options.threshold ?? 0.3,
986
+ ignore: options.affectedIgnore,
987
+ ...options.base !== void 0 ? { base: options.base } : {},
988
+ ...options.env ? { environment: options.env } : {},
989
+ ...runtime.signal ? { signal: runtime.signal } : {},
990
+ ...runtime.createRelevanceProvider ? { createProvider: runtime.createRelevanceProvider } : {}
991
+ });
992
+ paths = selection.tests.filter((test) => test.selected).map((test) => test.file);
993
+ if (options.selectionOnly) {
994
+ writeOut(`${JSON.stringify(selection, null, 2)}
995
+ `);
996
+ exitCode = 0;
997
+ return;
998
+ }
999
+ writeErr(
1000
+ `Affected selection: ${paths.length}/${selection.tests.length} tests, threshold ${selection.threshold}, base ${selection.base}.
1001
+ `
1002
+ );
1003
+ for (const test of selection.tests)
1004
+ writeErr(
1005
+ `${test.selected ? "RUN " : "SKIP"} ${test.probability.toFixed(4)} ${JSON.stringify(test.file)} (${test.reason})
1006
+ `
1007
+ );
1008
+ if (!paths.length) {
1009
+ writeErr("No relevant tests selected; no tests were executed.\n");
1010
+ exitCode = 0;
1011
+ return;
1012
+ }
1013
+ } catch (error) {
1014
+ writeErr(
1015
+ `${error instanceof AffectedSelectionError || error instanceof ProviderError2 ? error.message : "Affected selection could not complete."}
1016
+ No tests were run. Fix the selection error or run without --affected.
1017
+ `
1018
+ );
1019
+ exitCode = 3;
1020
+ return;
1021
+ }
1022
+ }
711
1023
  const lifecycle = new ReporterLifecycle();
712
1024
  const terminalNames = options.reporter.length ? options.reporter.filter(
713
1025
  (name) => name !== "json" && name !== "markdown" && name !== "junit"
@@ -744,15 +1056,20 @@ async function runCli(args, version, runtime = {}) {
744
1056
  }
745
1057
  };
746
1058
  const execution = await executeRun({
1059
+ command,
1060
+ ...runtime.onStrayRejection ? { onStrayRejection: runtime.onStrayRejection } : {},
747
1061
  paths,
748
1062
  filters: {
749
1063
  include: options.include,
750
1064
  exclude: options.exclude,
751
1065
  labels: options.labels,
752
- names: options.name
1066
+ names: options.name,
1067
+ ids: options.id
753
1068
  },
754
1069
  ...options.env ? { environment: options.env } : {},
755
1070
  ...options.browser ? { browser: options.browser } : {},
1071
+ ...options.vision !== void 0 ? { vision: options.vision } : {},
1072
+ ...options.visionModel !== void 0 ? { visionModel: options.visionModel } : {},
756
1073
  ...options.urlOverride ? { urlOverride: options.urlOverride } : {},
757
1074
  ...options.outputDir ? { outputDir: options.outputDir } : {},
758
1075
  ...options.reporterDir ? { reporterDir: options.reporterDir } : {},
@@ -834,12 +1151,18 @@ async function runCli(args, version, runtime = {}) {
834
1151
  );
835
1152
  exitCode = 0;
836
1153
  });
837
- program.command("doctor").description("check whether this environment can run Sedum").option("--json", "print versioned JSON checks on stdout", false).addHelpText(
1154
+ program.command("doctor").description("check whether this environment can run Sedum").option("--json", "print versioned JSON checks on stdout", false).option(
1155
+ "--vision",
1156
+ "also check the vision fallback's OPEN_ROUTER_API_KEY (automatic when vision.enabled is true)",
1157
+ false
1158
+ ).addHelpText(
838
1159
  "after",
839
1160
  "\nThe authenticated API check makes one small, potentially billable request.\n\nExit codes:\n 0 all checks passed\n 3 one or more prerequisites failed\n"
840
1161
  ).action(async (options) => {
841
- const { executeDoctorCommand, renderDoctorText } = await import("./doctor-command-2PMOA32Y.js");
842
- const result = await executeDoctorCommand(cwd, runtime.doctorProbes);
1162
+ const { executeDoctorCommand, renderDoctorText } = await import("./doctor-command-F4Y5KW36.js");
1163
+ const result = await executeDoctorCommand(cwd, runtime.doctorProbes, {
1164
+ vision: options.vision
1165
+ });
843
1166
  writeOut(
844
1167
  options.json ? `${JSON.stringify(result)}
845
1168
  ` : renderDoctorText(result)
@@ -853,7 +1176,7 @@ async function runCli(args, version, runtime = {}) {
853
1176
  "test files, module files, or directories relative to the project root (default: configured tests)"
854
1177
  ).option(
855
1178
  "--online",
856
- "classify sentences the offline cache cannot, using TYPESAFE_API_KEY, and update .sedum/classifications.json",
1179
+ "classify sentences the offline cache cannot, using the configured provider API key, and update .sedum/classifications.json",
857
1180
  false
858
1181
  ).addHelpText(
859
1182
  "after",
@@ -863,7 +1186,7 @@ async function runCli(args, version, runtime = {}) {
863
1186
  paths,
864
1187
  online: options.online,
865
1188
  cwd,
866
- createProvider: runtime.createClassificationProvider ?? createTypeSafeClassifier,
1189
+ createProvider: runtime.createClassificationProvider ?? createSelectedClassifier,
867
1190
  ...runtime.signal ? { signal: runtime.signal } : {}
868
1191
  });
869
1192
  const problems = execution.discovery?.problems ?? [];
@@ -947,8 +1270,11 @@ Fix: use \`sedum browsers install chromium\`.
947
1270
  "Fix: correct the command shown above and rerun it, or use `sedum --help`.\n"
948
1271
  );
949
1272
  } else {
1273
+ const detail = error instanceof Error ? `${error.name}: ${error.message.split("\n")[0].slice(0, 200)}` : "unknown error";
950
1274
  writeErr(
951
- "The command could not be parsed safely.\nFix: run `sedum --help` and correct the command.\n"
1275
+ `Sedum stopped on an unexpected internal error (${detail}).
1276
+ Fix: rerun the command; if it happens again, report it with the run's result.json.
1277
+ `
952
1278
  );
953
1279
  exitCode = 3;
954
1280
  }
@@ -957,6 +1283,7 @@ Fix: use \`sedum browsers install chromium\`.
957
1283
  }
958
1284
 
959
1285
  export {
1286
+ sedumCommand,
960
1287
  runExitCode,
961
1288
  renderRunSummary,
962
1289
  runCli