blastproof 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -207,7 +207,7 @@ function formatInitGuidance(result) {
207
207
  }
208
208
 
209
209
  // src/commands/plan.ts
210
- import path10 from "path";
210
+ import path11 from "path";
211
211
 
212
212
  // src/auth.ts
213
213
  import { readFile, writeFile as writeFile2, mkdir as mkdir3 } from "fs/promises";
@@ -363,12 +363,13 @@ var RunBudget = class {
363
363
  };
364
364
  }
365
365
  };
366
- function estimateMaxModelCalls(tests, maxIterationsPerStep, maxRetriesPerStep) {
366
+ function estimateMaxModelCalls(tests, maxIterationsPerStep, maxRetriesPerStep, judgeCalls = 1) {
367
367
  const totalSteps = tests.reduce(
368
368
  (sum, test) => sum + (test.setup?.length ?? 0) + test.steps.length,
369
369
  0
370
370
  );
371
- return totalSteps * (maxIterationsPerStep + maxRetriesPerStep + Math.min(maxIterationsPerStep, maxRetriesPerStep));
371
+ const bundled = (2 * judgeCalls - 1) * Math.min(maxIterationsPerStep, maxRetriesPerStep);
372
+ return totalSteps * (maxIterationsPerStep + maxRetriesPerStep + bundled);
372
373
  }
373
374
 
374
375
  // src/runner/env.ts
@@ -1249,6 +1250,25 @@ async function executeTest(page, test, options) {
1249
1250
  };
1250
1251
  }
1251
1252
 
1253
+ // src/runner/device.ts
1254
+ import { devices } from "playwright";
1255
+ function isDevice(name) {
1256
+ return Object.hasOwn(devices, name);
1257
+ }
1258
+ function unknownDeviceMessage(name) {
1259
+ const words = name.toLowerCase().split(/\s+/).filter(Boolean);
1260
+ const same = Object.keys(devices).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
1261
+ if (same) return `"${name}" is not a device Playwright knows; did you mean "${same}"? Names are case-sensitive`;
1262
+ const close = Object.keys(devices).filter((candidate) => !candidate.endsWith(" landscape")).filter((candidate) => words.length > 0 && words.every((word) => candidate.toLowerCase().includes(word))).slice(-3);
1263
+ const hint = close.length ? `did you mean ${close.map((c) => `"${c}"`).join(", ")}?` : "see the device names in Playwright's registry: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json";
1264
+ return `"${name}" is not a device Playwright knows; ${hint}`;
1265
+ }
1266
+ function deviceOptions(name) {
1267
+ if (!name) return {};
1268
+ const { defaultBrowserType: _browser, ...options } = devices[name];
1269
+ return options;
1270
+ }
1271
+
1252
1272
  // src/auth.ts
1253
1273
  var AUTH_STATE_RELATIVE_PATH = path3.join(".blastproof", ".auth-state.json");
1254
1274
  var AuthError = class extends Error {
@@ -1327,7 +1347,7 @@ async function fromSteps(options) {
1327
1347
  const { auth, baseUrl, browser, brain, maxRetries, snapshot, timeoutMs, maxSnapshotLines, onEvent, mask } = options;
1328
1348
  const steps = auth.steps;
1329
1349
  const takeSnapshot = snapshot ?? ((page) => defaultSnapshot(page, maxSnapshotLines));
1330
- const context = await browser.newContext();
1350
+ const context = await browser.newContext(deviceOptions(options.device));
1331
1351
  try {
1332
1352
  const page = await context.newPage();
1333
1353
  const result = await runJourney(
@@ -1406,9 +1426,10 @@ async function authenticate(options) {
1406
1426
  if (auth.cache) await writeCached(cwd, session);
1407
1427
  return session;
1408
1428
  }
1409
- function contextOptions(session) {
1410
- if (!session) return {};
1429
+ function contextOptions(session, device) {
1430
+ if (!session) return deviceOptions(device);
1411
1431
  return {
1432
+ ...deviceOptions(device),
1412
1433
  ...session.storageState ? { storageState: session.storageState } : {},
1413
1434
  ...session.extraHTTPHeaders ? { extraHTTPHeaders: session.extraHTTPHeaders } : {}
1414
1435
  };
@@ -1449,6 +1470,9 @@ var llmSchema = z.object({
1449
1470
  });
1450
1471
  }
1451
1472
  });
1473
+ var deviceSchema = z.string().superRefine((name, ctx) => {
1474
+ if (!isDevice(name)) ctx.addIssue({ code: "custom", message: unknownDeviceMessage(name) });
1475
+ });
1452
1476
  var browserSchema = z.object({
1453
1477
  headless: z.boolean().default(true),
1454
1478
  /**
@@ -1463,7 +1487,13 @@ var browserSchema = z.object({
1463
1487
  * undefined lets `runner/snapshot.ts`'s own default (200) apply, so a config
1464
1488
  * that never mentions this behaves exactly as before it existed.
1465
1489
  */
1466
- max_snapshot_lines: z.number().int().positive().optional()
1490
+ max_snapshot_lines: z.number().int().positive().optional(),
1491
+ /**
1492
+ * The device every test runs as unless its file names its own (spec
1493
+ * device-emulation). Optional: undefined is Playwright's desktop default, so a
1494
+ * config that never mentions it behaves exactly as before it existed.
1495
+ */
1496
+ device: deviceSchema.optional()
1467
1497
  });
1468
1498
  var budgetSchema = z.object({
1469
1499
  max_llm_calls: z.coerce.number().int().positive().optional(),
@@ -1471,6 +1501,11 @@ var budgetSchema = z.object({
1471
1501
  /** Seconds, not milliseconds, to match how a human would set a deadline. */
1472
1502
  max_duration_s: z.coerce.number().positive().optional()
1473
1503
  });
1504
+ var firstJudgeSchema = z.object({
1505
+ model: z.string().min(1),
1506
+ api_key_env: z.string().min(1).default("OPENROUTER_API_KEY"),
1507
+ threshold: z.coerce.number().gt(0, "must be a probability above 0").lt(1, "must be a probability below 1").default(0.7)
1508
+ });
1474
1509
  var cookieSchema = z.object({
1475
1510
  name: z.string().min(1),
1476
1511
  value: z.string(),
@@ -1550,7 +1585,8 @@ var configSchema = z.object({
1550
1585
  * those tests, not of the runner. Opted into by the person who knows.
1551
1586
  */
1552
1587
  concurrency: z.number().int().min(1, "concurrency must be at least 1").default(1),
1553
- budget: budgetSchema.optional()
1588
+ budget: budgetSchema.optional(),
1589
+ first_judge: firstJudgeSchema.optional()
1554
1590
  });
1555
1591
  var ENV_OVERRIDES = {
1556
1592
  BLASTPROOF_BASE_URL: ["base_url"],
@@ -1561,7 +1597,10 @@ var ENV_OVERRIDES = {
1561
1597
  BLASTPROOF_LLM_TIMEOUT_S: ["llm", "timeout_s"],
1562
1598
  BLASTPROOF_MAX_LLM_CALLS: ["budget", "max_llm_calls"],
1563
1599
  BLASTPROOF_MAX_TOKENS: ["budget", "max_tokens"],
1564
- BLASTPROOF_MAX_DURATION_S: ["budget", "max_duration_s"]
1600
+ BLASTPROOF_MAX_DURATION_S: ["budget", "max_duration_s"],
1601
+ BLASTPROOF_FIRST_JUDGE_MODEL: ["first_judge", "model"],
1602
+ BLASTPROOF_FIRST_JUDGE_THRESHOLD: ["first_judge", "threshold"],
1603
+ BLASTPROOF_BROWSER_DEVICE: ["browser", "device"]
1565
1604
  };
1566
1605
  function applyEnvOverrides(data, env = process.env) {
1567
1606
  const merged = data && typeof data === "object" ? { ...data } : {};
@@ -1607,13 +1646,13 @@ function unwrapToObjectSchema(schema) {
1607
1646
  }
1608
1647
  return current instanceof z.ZodObject ? current : void 0;
1609
1648
  }
1610
- function findUnknownConfigKeys(data, schema = configSchema, path11 = []) {
1649
+ function findUnknownConfigKeys(data, schema = configSchema, path12 = []) {
1611
1650
  const object = unwrapToObjectSchema(schema);
1612
1651
  if (!object || data === null || typeof data !== "object" || Array.isArray(data)) return [];
1613
1652
  const shape = object.shape;
1614
1653
  const warnings = [];
1615
1654
  for (const key of Object.keys(data)) {
1616
- const fieldPath = [...path11, key];
1655
+ const fieldPath = [...path12, key];
1617
1656
  const fieldSchema = shape[key];
1618
1657
  if (!fieldSchema) {
1619
1658
  warnings.push(fieldPath.join("."));
@@ -1763,7 +1802,7 @@ warning: ${findings.length} file(s) changed in the working tree are not in the d
1763
1802
  }
1764
1803
 
1765
1804
  // src/llm/brain.ts
1766
- import { APICallError, generateObject, NoObjectGeneratedError, RetryError } from "ai";
1805
+ import { APICallError as APICallError2, generateObject, NoObjectGeneratedError, RetryError } from "ai";
1767
1806
 
1768
1807
  // src/llm/prompts.ts
1769
1808
  function agentSystemPrompt() {
@@ -1848,6 +1887,16 @@ function assertUserPrompt(step, expectation, snapshot, stepHistory) {
1848
1887
  );
1849
1888
  return parts.join("\n");
1850
1889
  }
1890
+ function firstJudgeQuestion() {
1891
+ const system = assertSystemPrompt();
1892
+ return {
1893
+ instructions: system.slice(0, system.indexOf("Answer with pass=true/false")).trim(),
1894
+ criteria: {
1895
+ true: "The snapshot shows the state the step asks for. Every value the step names appears where the step places it, committed (not only typed into an open, unsubmitted field). An outcome that is an absence is shown by the thing being absent.",
1896
+ false: "Some part of the outcome the step asks for is not shown, or cannot be assessed from this snapshot: a value is missing or different, appears only somewhere else on the page, or only inside an unsubmitted control, or the claim is true of something other than what the step asks."
1897
+ }
1898
+ };
1899
+ }
1851
1900
  function plannerSystemPrompt() {
1852
1901
  return `You are a QA engineer writing one end-to-end test for a web page, in plain English.
1853
1902
 
@@ -1879,6 +1928,223 @@ function plannerUserPrompt(input) {
1879
1928
  return parts.join("\n");
1880
1929
  }
1881
1930
 
1931
+ // src/llm/decision.ts
1932
+ import { appendFileSync, mkdirSync } from "fs";
1933
+ import path5 from "path";
1934
+ import { APICallError } from "ai";
1935
+
1936
+ // src/llm/provider.ts
1937
+ import { createAnthropic } from "@ai-sdk/anthropic";
1938
+ import { createOpenAI } from "@ai-sdk/openai";
1939
+ var DEFAULT_MODELS = {
1940
+ anthropic: "claude-haiku-4-5",
1941
+ openai: "gpt-6-luna",
1942
+ ollama: "gpt-oss:20b"
1943
+ };
1944
+ var DEFAULT_API_KEY_ENVS = {
1945
+ anthropic: "ANTHROPIC_API_KEY",
1946
+ openai: "OPENAI_API_KEY"
1947
+ };
1948
+ var DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434/v1";
1949
+ var DEFAULT_TIMEOUT_SECONDS = {
1950
+ anthropic: 300,
1951
+ openai: 300,
1952
+ ollama: 900
1953
+ };
1954
+ function timeoutSeconds(llm) {
1955
+ return llm.timeout_s ?? DEFAULT_TIMEOUT_SECONDS[llm.provider];
1956
+ }
1957
+ function withExtraBody(extra, base = fetch) {
1958
+ return (input, init) => {
1959
+ if (typeof init?.body !== "string") return base(input, init);
1960
+ let body;
1961
+ try {
1962
+ body = JSON.parse(init.body);
1963
+ } catch {
1964
+ return base(input, init);
1965
+ }
1966
+ if (body === null || typeof body !== "object" || Array.isArray(body)) return base(input, init);
1967
+ return base(input, { ...init, body: JSON.stringify({ ...extra, ...body }) });
1968
+ };
1969
+ }
1970
+ var MissingApiKeyError = class extends Error {
1971
+ constructor(variable, provider) {
1972
+ super(
1973
+ `Missing API key: environment variable ${variable} is not set (required for provider "${provider}"). Export it before running, e.g. \`export ${variable}=...\`, or change llm.provider / llm.api_key_env in .blastproof/config.yaml.`
1974
+ );
1975
+ this.name = "MissingApiKeyError";
1976
+ }
1977
+ };
1978
+ function createModel(llm, env = process.env) {
1979
+ const modelId = llm.model ?? DEFAULT_MODELS[llm.provider];
1980
+ switch (llm.provider) {
1981
+ case "anthropic":
1982
+ case "openai": {
1983
+ const keyEnv = llm.api_key_env ?? DEFAULT_API_KEY_ENVS[llm.provider];
1984
+ const apiKey = env[keyEnv];
1985
+ if (!apiKey) {
1986
+ throw new MissingApiKeyError(keyEnv, llm.provider);
1987
+ }
1988
+ const baseURL = llm.base_url ? { baseURL: llm.base_url } : {};
1989
+ const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
1990
+ const model = llm.provider === "anthropic" ? (
1991
+ // A configured endpoint applies to whichever provider is selected —
1992
+ // dropping it here routed corporate-proxy configs to the public API
1993
+ // with no error (design D2).
1994
+ createAnthropic({ apiKey, ...baseURL })(modelId)
1995
+ ) : (
1996
+ // `.chat` = Chat Completions: works with official OpenAI and any
1997
+ // OpenAI-compatible endpoint (OpenRouter, LiteLLM, vLLM) via base_url.
1998
+ createOpenAI({ apiKey, ...baseURL, ...extra }).chat(modelId)
1999
+ );
2000
+ return { model, provider: llm.provider, modelId };
2001
+ }
2002
+ case "ollama": {
2003
+ const baseURL = llm.base_url ?? DEFAULT_OLLAMA_BASE_URL;
2004
+ const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
2005
+ const model = createOpenAI({ baseURL, apiKey: "ollama", ...extra }).chat(modelId);
2006
+ return { model, provider: "ollama", modelId };
2007
+ }
2008
+ }
2009
+ }
2010
+
2011
+ // src/llm/decision.ts
2012
+ var DECISIONS_ENDPOINT = "https://openrouter.ai/api/alpha/decisions";
2013
+ var MAX_DECISION_CHARS = 6e4;
2014
+ var RETRY_DELAYS_MS = [2e3, 4e3];
2015
+ var sleep = (ms, signal) => new Promise((resolve2, reject) => {
2016
+ if (signal?.aborted) return reject(signal.reason);
2017
+ const timer = setTimeout(resolve2, ms);
2018
+ signal?.addEventListener(
2019
+ "abort",
2020
+ () => {
2021
+ clearTimeout(timer);
2022
+ reject(signal.reason);
2023
+ },
2024
+ { once: true }
2025
+ );
2026
+ });
2027
+ function retryable(status) {
2028
+ return status === 408 || status === 409 || status === 429 || status >= 500;
2029
+ }
2030
+ function readAnswer(text) {
2031
+ let body;
2032
+ try {
2033
+ body = JSON.parse(text);
2034
+ } catch {
2035
+ return { p: void 0 };
2036
+ }
2037
+ const root = body ?? {};
2038
+ const raw = root.answers?.pass?.noul;
2039
+ const p = typeof raw === "number" && raw >= 0 && raw <= 1 ? raw : void 0;
2040
+ const input = root.usage?.input_tokens;
2041
+ const output = root.usage?.output_tokens;
2042
+ const totalTokens = typeof input === "number" ? input + (typeof output === "number" ? output : 0) : void 0;
2043
+ return { p, usage: { totalTokens } };
2044
+ }
2045
+ function createDecisionClient(options) {
2046
+ const doFetch = options.fetch ?? fetch;
2047
+ const wait = options.sleep ?? sleep;
2048
+ const url = options.endpoint ?? DECISIONS_ENDPOINT;
2049
+ return async (question, state, signal) => {
2050
+ const requestBodyValues = {
2051
+ model: options.model,
2052
+ state,
2053
+ questions: { pass: { type: "noul", ...question } }
2054
+ };
2055
+ for (let attempt = 0; ; attempt++) {
2056
+ let response;
2057
+ try {
2058
+ response = await doFetch(url, {
2059
+ method: "POST",
2060
+ headers: { Authorization: `Bearer ${options.apiKey}`, "Content-Type": "application/json" },
2061
+ body: JSON.stringify(requestBodyValues),
2062
+ signal
2063
+ });
2064
+ } catch (error) {
2065
+ if (signal?.aborted) throw error;
2066
+ if (attempt < RETRY_DELAYS_MS.length) {
2067
+ await wait(RETRY_DELAYS_MS[attempt], signal);
2068
+ continue;
2069
+ }
2070
+ throw new APICallError({
2071
+ message: `first judge ${options.model}: ${error instanceof Error ? error.message : String(error)}`,
2072
+ url,
2073
+ requestBodyValues,
2074
+ cause: error
2075
+ });
2076
+ }
2077
+ const text = await response.text();
2078
+ if (response.ok) return readAnswer(text);
2079
+ if (retryable(response.status) && attempt < RETRY_DELAYS_MS.length) {
2080
+ await wait(RETRY_DELAYS_MS[attempt], signal);
2081
+ continue;
2082
+ }
2083
+ throw new APICallError({
2084
+ message: `first judge ${options.model}`,
2085
+ url,
2086
+ requestBodyValues,
2087
+ statusCode: response.status,
2088
+ responseBody: text
2089
+ });
2090
+ }
2091
+ };
2092
+ }
2093
+ var MissingFirstJudgeKeyError = class extends MissingApiKeyError {
2094
+ constructor(variable, model) {
2095
+ super(variable, model);
2096
+ this.message = `Missing API key: environment variable ${variable} is not set (required for the first judge "${model}"). Export it before running, e.g. \`export ${variable}=...\`, or remove first_judge from .blastproof/config.yaml (and unset BLASTPROOF_FIRST_JUDGE_MODEL).`;
2097
+ }
2098
+ };
2099
+ var FirstJudgeLog = class {
2100
+ constructor(model, threshold, file) {
2101
+ this.model = model;
2102
+ this.threshold = threshold;
2103
+ this.file = file;
2104
+ }
2105
+ model;
2106
+ threshold;
2107
+ file;
2108
+ passed = 0;
2109
+ failedByLabelCheck = 0;
2110
+ toLlm = 0;
2111
+ dirReady = false;
2112
+ record(test, entry) {
2113
+ if (entry.outcome === "passed") this.passed++;
2114
+ else if (entry.outcome === "label-check") this.failedByLabelCheck++;
2115
+ else this.toLlm++;
2116
+ if (entry.outcome === "too-large" || !this.file) return;
2117
+ if (!this.dirReady) {
2118
+ mkdirSync(path5.dirname(this.file), { recursive: true });
2119
+ this.dirReady = true;
2120
+ }
2121
+ const line = {
2122
+ test,
2123
+ step: entry.step,
2124
+ claim: entry.claim,
2125
+ model: this.model,
2126
+ p: entry.p ?? null,
2127
+ threshold: this.threshold,
2128
+ outcome: entry.outcome,
2129
+ snapshot: entry.snapshot
2130
+ };
2131
+ appendFileSync(this.file, `${JSON.stringify(line)}
2132
+ `, "utf8");
2133
+ }
2134
+ summaryLine() {
2135
+ const labelCheck = this.failedByLabelCheck > 0 ? `, ${this.failedByLabelCheck} failed by the label check` : "";
2136
+ return `First judge (experimental, ${this.model} at ${this.threshold}): ${this.passed} passed${labelCheck}, ${this.toLlm} to the LLM judge`;
2137
+ }
2138
+ };
2139
+ function firstJudgeLogPath(sessionDir) {
2140
+ return path5.join(sessionDir, "first-judge.jsonl");
2141
+ }
2142
+ function createFirstJudgeClient(config, env = process.env, fetchImpl) {
2143
+ const apiKey = env[config.api_key_env];
2144
+ if (!apiKey) throw new MissingFirstJudgeKeyError(config.api_key_env, config.model);
2145
+ return createDecisionClient({ model: config.model, apiKey, fetch: fetchImpl });
2146
+ }
2147
+
1882
2148
  // src/llm/schemas.ts
1883
2149
  import { z as z2 } from "zod";
1884
2150
  function absentAsNull(schema) {
@@ -1964,7 +2230,7 @@ function withProviderDetail(error) {
1964
2230
  }
1965
2231
  function asProviderRefusal(error) {
1966
2232
  const cause = RetryError.isInstance(error) ? error.lastError : error;
1967
- if (!APICallError.isInstance(cause)) return error;
2233
+ if (!APICallError2.isInstance(cause)) return error;
1968
2234
  if (cause.statusCode !== void 0 && cause.statusCode < 400) return error;
1969
2235
  withProviderDetail(cause);
1970
2236
  return new ProviderRefusedError(cause.statusCode, cause.message);
@@ -1986,12 +2252,12 @@ function spentAndExplained(error, budget) {
1986
2252
  `the answer reached the ${MAX_OUTPUT_TOKENS}-token output limit before its JSON was complete`
1987
2253
  );
1988
2254
  }
1989
- async function countedGenerate(generate, budget, options) {
2255
+ async function counted(budget, call) {
1990
2256
  budget.check();
1991
2257
  const abort = callAbort(budget);
1992
2258
  let result;
1993
2259
  try {
1994
- result = await generate({ ...options, maxOutputTokens: MAX_OUTPUT_TOKENS, abortSignal: abort?.signal });
2260
+ result = await call(abort?.signal);
1995
2261
  } catch (error) {
1996
2262
  if (abort?.signal.aborted) {
1997
2263
  if (abort.byDeadline) throw budget.deadlineReached();
@@ -2004,7 +2270,29 @@ async function countedGenerate(generate, budget, options) {
2004
2270
  budget.record(result.usage);
2005
2271
  return result;
2006
2272
  }
2007
- function createBrain(model, generate = generateObject, budget) {
2273
+ function countedGenerate(generate, budget, options) {
2274
+ return counted(budget, (abortSignal) => generate({ ...options, maxOutputTokens: MAX_OUTPUT_TOKENS, abortSignal }));
2275
+ }
2276
+ async function firstJudgment(firstJudge, budget, judged, label) {
2277
+ const question = firstJudgeQuestion();
2278
+ const entry = { step: judged.step, claim: judged.claim, snapshot: judged.snapshot };
2279
+ if (judged.prompt.length + question.instructions.length > MAX_DECISION_CHARS) {
2280
+ firstJudge.record({ ...entry, p: void 0, outcome: "too-large" });
2281
+ return void 0;
2282
+ }
2283
+ const { p } = await counted(budget, (signal) => firstJudge.decide(question, judged.prompt, signal));
2284
+ if (p === void 0 || p < firstJudge.threshold) {
2285
+ firstJudge.record({ ...entry, p, outcome: "to-llm" });
2286
+ return void 0;
2287
+ }
2288
+ const judgment = label({
2289
+ pass: true,
2290
+ reason: `passed by the first judge, ${firstJudge.model}, at p(yes) ${p.toFixed(2)} (threshold ${firstJudge.threshold}); a decision model gives no reason`
2291
+ });
2292
+ firstJudge.record({ ...entry, p, outcome: judgment.pass ? "passed" : "label-check" });
2293
+ return judgment;
2294
+ }
2295
+ function createBrain(model, generate = generateObject, budget, firstJudge) {
2008
2296
  return {
2009
2297
  async nextAction(input) {
2010
2298
  const result = await countedGenerate(generate, budget, {
@@ -2026,16 +2314,19 @@ function createBrain(model, generate = generateObject, budget) {
2026
2314
  action: placeholdersAsLabels(entry.action),
2027
2315
  result: placeholdersAsLabels(entry.result)
2028
2316
  }));
2317
+ const judgedStep = placeholdersAsLabels(step);
2318
+ const claim = placeholdersAsLabels(expectation);
2319
+ const prompt = assertUserPrompt(judgedStep, claim, snapshot, asJudged);
2320
+ const label = (judgment) => secretMismatch(judgedStep, snapshot, asJudged, usedEarlier ?? [], judgment);
2321
+ if (firstJudge) {
2322
+ const decided = await firstJudgment(firstJudge, budget, { step: judgedStep, claim, snapshot, prompt }, label);
2323
+ if (decided) return decided;
2324
+ }
2029
2325
  const result = await countedGenerate(generate, budget, {
2030
2326
  model,
2031
2327
  schema: assertJudgmentSchema,
2032
2328
  system: assertSystemPrompt(),
2033
- prompt: assertUserPrompt(
2034
- placeholdersAsLabels(step),
2035
- placeholdersAsLabels(expectation),
2036
- snapshot,
2037
- asJudged
2038
- ),
2329
+ prompt,
2039
2330
  temperature: 0
2040
2331
  });
2041
2332
  const parsed = assertJudgmentSchema.safeParse(result.object);
@@ -2044,7 +2335,7 @@ function createBrain(model, generate = generateObject, budget) {
2044
2335
  `Model returned an invalid assert judgment: ${parsed.error.issues[0]?.message ?? "unknown"}`
2045
2336
  );
2046
2337
  }
2047
- return secretMismatch(placeholdersAsLabels(step), snapshot, asJudged, usedEarlier ?? [], parsed.data);
2338
+ return label(parsed.data);
2048
2339
  }
2049
2340
  };
2050
2341
  }
@@ -2087,92 +2378,17 @@ function createPlanner(model, generate = generateObject, budget) {
2087
2378
  };
2088
2379
  }
2089
2380
 
2090
- // src/llm/provider.ts
2091
- import { createAnthropic } from "@ai-sdk/anthropic";
2092
- import { createOpenAI } from "@ai-sdk/openai";
2093
- var DEFAULT_MODELS = {
2094
- anthropic: "claude-haiku-4-5",
2095
- openai: "gpt-6-luna",
2096
- ollama: "gpt-oss:20b"
2097
- };
2098
- var DEFAULT_API_KEY_ENVS = {
2099
- anthropic: "ANTHROPIC_API_KEY",
2100
- openai: "OPENAI_API_KEY"
2101
- };
2102
- var DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434/v1";
2103
- var DEFAULT_TIMEOUT_SECONDS = {
2104
- anthropic: 300,
2105
- openai: 300,
2106
- ollama: 900
2107
- };
2108
- function timeoutSeconds(llm) {
2109
- return llm.timeout_s ?? DEFAULT_TIMEOUT_SECONDS[llm.provider];
2110
- }
2111
- function withExtraBody(extra, base = fetch) {
2112
- return (input, init) => {
2113
- if (typeof init?.body !== "string") return base(input, init);
2114
- let body;
2115
- try {
2116
- body = JSON.parse(init.body);
2117
- } catch {
2118
- return base(input, init);
2119
- }
2120
- if (body === null || typeof body !== "object" || Array.isArray(body)) return base(input, init);
2121
- return base(input, { ...init, body: JSON.stringify({ ...extra, ...body }) });
2122
- };
2123
- }
2124
- var MissingApiKeyError = class extends Error {
2125
- constructor(variable, provider) {
2126
- super(
2127
- `Missing API key: environment variable ${variable} is not set (required for provider "${provider}"). Export it before running, e.g. \`export ${variable}=...\`, or change llm.provider / llm.api_key_env in .blastproof/config.yaml.`
2128
- );
2129
- this.name = "MissingApiKeyError";
2130
- }
2131
- };
2132
- function createModel(llm, env = process.env) {
2133
- const modelId = llm.model ?? DEFAULT_MODELS[llm.provider];
2134
- switch (llm.provider) {
2135
- case "anthropic":
2136
- case "openai": {
2137
- const keyEnv = llm.api_key_env ?? DEFAULT_API_KEY_ENVS[llm.provider];
2138
- const apiKey = env[keyEnv];
2139
- if (!apiKey) {
2140
- throw new MissingApiKeyError(keyEnv, llm.provider);
2141
- }
2142
- const baseURL = llm.base_url ? { baseURL: llm.base_url } : {};
2143
- const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
2144
- const model = llm.provider === "anthropic" ? (
2145
- // A configured endpoint applies to whichever provider is selected —
2146
- // dropping it here routed corporate-proxy configs to the public API
2147
- // with no error (design D2).
2148
- createAnthropic({ apiKey, ...baseURL })(modelId)
2149
- ) : (
2150
- // `.chat` = Chat Completions: works with official OpenAI and any
2151
- // OpenAI-compatible endpoint (OpenRouter, LiteLLM, vLLM) via base_url.
2152
- createOpenAI({ apiKey, ...baseURL, ...extra }).chat(modelId)
2153
- );
2154
- return { model, provider: llm.provider, modelId };
2155
- }
2156
- case "ollama": {
2157
- const baseURL = llm.base_url ?? DEFAULT_OLLAMA_BASE_URL;
2158
- const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
2159
- const model = createOpenAI({ baseURL, apiKey: "ollama", ...extra }).chat(modelId);
2160
- return { model, provider: "ollama", modelId };
2161
- }
2162
- }
2163
- }
2164
-
2165
2381
  // src/planner.ts
2166
2382
  import { mkdir as mkdir4, writeFile as writeFile3 } from "fs/promises";
2167
- import path6 from "path";
2383
+ import path7 from "path";
2168
2384
  import { stringify } from "yaml";
2169
2385
 
2170
2386
  // src/runner/testfile.ts
2171
2387
  import { readFile as readFile3, readdir } from "fs/promises";
2172
- import path5 from "path";
2388
+ import path6 from "path";
2173
2389
  import { parse as parseYaml2 } from "yaml";
2174
2390
  import { z as z3 } from "zod";
2175
- var TESTS_RELATIVE_DIR = path5.join(".blastproof", "tests");
2391
+ var TESTS_RELATIVE_DIR = path6.join(".blastproof", "tests");
2176
2392
  var prioritySchema = z3.enum(["P0", "P1", "P2"]);
2177
2393
  var testFileSchema = z3.object({
2178
2394
  summary: z3.string().min(1),
@@ -2181,7 +2397,8 @@ var testFileSchema = z3.object({
2181
2397
  tags: z3.array(z3.string()).default([]),
2182
2398
  setup: z3.array(z3.string().min(1)).optional(),
2183
2399
  routes: z3.array(z3.string()).default([]),
2184
- auth: z3.boolean().default(true)
2400
+ auth: z3.boolean().default(true),
2401
+ device: deviceSchema.optional()
2185
2402
  });
2186
2403
  var TestFileError = class extends Error {
2187
2404
  constructor(message) {
@@ -2219,7 +2436,7 @@ async function discoverTestFiles(root) {
2219
2436
  async function walk(dir) {
2220
2437
  const entries = await readdir(dir, { withFileTypes: true });
2221
2438
  for (const entry of entries) {
2222
- const full = path5.join(dir, entry.name);
2439
+ const full = path6.join(dir, entry.name);
2223
2440
  if (entry.isDirectory()) {
2224
2441
  await walk(full);
2225
2442
  } else if (/\.ya?ml$/i.test(entry.name)) {
@@ -2306,8 +2523,8 @@ async function generateForRoute(page, options) {
2306
2523
  };
2307
2524
  }
2308
2525
  async function writeDraft(cwd, draft, meta) {
2309
- const dir = path6.join(cwd, TESTS_RELATIVE_DIR);
2310
- const file = path6.join(dir, `${routeToSlug(meta.route)}.yaml`);
2526
+ const dir = path7.join(cwd, TESTS_RELATIVE_DIR);
2527
+ const file = path7.join(dir, `${routeToSlug(meta.route)}.yaml`);
2311
2528
  try {
2312
2529
  await mkdir4(dir, { recursive: true });
2313
2530
  await writeFile3(file, renderTestYaml(draft, meta), { flag: "wx" });
@@ -2315,11 +2532,11 @@ async function writeDraft(cwd, draft, meta) {
2315
2532
  const err = error;
2316
2533
  if (err.code === "EEXIST" && err.syscall !== "mkdir") {
2317
2534
  throw new PlannerError(
2318
- `Refusing to overwrite ${path6.relative(cwd, file)} (route ${meta.route}). Delete or rename it to regenerate.`
2535
+ `Refusing to overwrite ${path7.relative(cwd, file)} (route ${meta.route}). Delete or rename it to regenerate.`
2319
2536
  );
2320
2537
  }
2321
2538
  throw new PlannerError(
2322
- `Cannot write draft to ${file}: ${fsReason(error)}. Check that ${path6.dirname(file)} is a directory you can write to, not a file.`
2539
+ `Cannot write draft to ${file}: ${fsReason(error)}. Check that ${path7.dirname(file)} is a directory you can write to, not a file.`
2323
2540
  );
2324
2541
  }
2325
2542
  return file;
@@ -2482,11 +2699,11 @@ function formatSpendLine(spend) {
2482
2699
  }
2483
2700
 
2484
2701
  // src/commands/run.ts
2485
- import path9 from "path";
2702
+ import path10 from "path";
2486
2703
 
2487
2704
  // src/report/html.ts
2488
2705
  import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
2489
- import path7 from "path";
2706
+ import path8 from "path";
2490
2707
  var ESCAPES = {
2491
2708
  "&": "&amp;",
2492
2709
  "<": "&lt;",
@@ -2562,7 +2779,7 @@ function renderSteps(steps) {
2562
2779
  </ol>`;
2563
2780
  }
2564
2781
  function withheldScreenshot(file, reportDir) {
2565
- const href = path7.relative(reportDir, file).split(path7.sep).join("/");
2782
+ const href = path8.relative(reportDir, file).split(path8.sep).join("/");
2566
2783
  return ` <p class="note">Screenshot withheld: this run handled secrets ({{env.*}}), and a screenshot cannot be masked. <a href="${escapeHtml(href)}">${escapeHtml(href)}</a></p>`;
2567
2784
  }
2568
2785
  async function renderTest(result, screenshots, cwd) {
@@ -2570,10 +2787,11 @@ async function renderTest(result, screenshots, cwd) {
2570
2787
  const notRun = result.status === "not-run";
2571
2788
  const tagClass = failed ? "fail" : notRun ? "skip" : "pass";
2572
2789
  const label = failed ? "FAIL" : notRun ? "NOT RUN" : "PASS";
2573
- const file = cwd ? path7.relative(cwd, result.file) : result.file;
2790
+ const file = cwd ? path8.relative(cwd, result.file) : result.file;
2791
+ const device = result.device ? ` \xB7 ${escapeHtml(result.device)}` : "";
2574
2792
  const parts = [
2575
2793
  ` <details${failed || notRun ? " open" : ""}>`,
2576
- ` <summary><span class="tag ${tagClass}">${label}</span> ${escapeHtml(result.summary)} <span class="note">${escapeHtml(result.priority)} \xB7 ${escapeHtml(file)}</span></summary>`
2794
+ ` <summary><span class="tag ${tagClass}">${label}</span> ${escapeHtml(result.summary)} <span class="note">${escapeHtml(result.priority)}${device} \xB7 ${escapeHtml(file)}</span></summary>`
2577
2795
  ];
2578
2796
  if (failed) {
2579
2797
  if (result.failedStep) {
@@ -2610,14 +2828,14 @@ async function renderHtml(results, skipped, meta) {
2610
2828
 
2611
2829
  `;
2612
2830
  const rows = results.map((r) => {
2613
- const file = meta.cwd ? path7.relative(meta.cwd, r.file) : r.file;
2831
+ const file = meta.cwd ? path8.relative(meta.cwd, r.file) : r.file;
2614
2832
  const tagClass = r.status === "failed" ? "fail" : r.status === "not-run" ? "skip" : "pass";
2615
2833
  const label = r.status === "failed" ? "FAIL" : r.status === "not-run" ? "NOT RUN" : "PASS";
2616
2834
  const time = r.status === "not-run" ? "\u2014" : seconds(r.durationMs);
2617
2835
  return ` <tr><td><span class="tag ${tagClass}">${label}</span></td><td>${escapeHtml(r.priority)}</td><td>${escapeHtml(r.summary)}</td><td>${escapeHtml(file)}</td><td class="num">${time}</td></tr>`;
2618
2836
  }).join("\n");
2619
2837
  const skippedRows = skipped.map((s) => {
2620
- const file = meta.cwd ? path7.relative(meta.cwd, s.path) : s.path;
2838
+ const file = meta.cwd ? path8.relative(meta.cwd, s.path) : s.path;
2621
2839
  return ` <tr><td><span class="tag skip">SKIP</span></td><td>\u2014</td><td>${escapeHtml(s.summary)}</td><td>${escapeHtml(file)}</td><td class="num">\u2014</td></tr>`;
2622
2840
  }).join("\n");
2623
2841
  return `<!doctype html>
@@ -2656,7 +2874,7 @@ ${detail}
2656
2874
  }
2657
2875
  async function writeHtml(file, html) {
2658
2876
  try {
2659
- await mkdir5(path7.dirname(file), { recursive: true });
2877
+ await mkdir5(path8.dirname(file), { recursive: true });
2660
2878
  await writeFile4(file, html, "utf8");
2661
2879
  return file;
2662
2880
  } catch (error) {
@@ -2668,7 +2886,7 @@ async function writeHtml(file, html) {
2668
2886
 
2669
2887
  // src/report/junit.ts
2670
2888
  import { mkdir as mkdir6, writeFile as writeFile5 } from "fs/promises";
2671
- import path8 from "path";
2889
+ import path9 from "path";
2672
2890
  var ESCAPES2 = {
2673
2891
  "&": "&amp;",
2674
2892
  "<": "&lt;",
@@ -2683,7 +2901,7 @@ function seconds2(ms) {
2683
2901
  return (ms / 1e3).toFixed(3);
2684
2902
  }
2685
2903
  function renderJUnit(results, skipped, meta) {
2686
- const relative = (file) => meta.cwd ? path8.relative(meta.cwd, file) : file;
2904
+ const relative = (file) => meta.cwd ? path9.relative(meta.cwd, file) : file;
2687
2905
  const failures = results.filter((result) => result.status === "failed").length;
2688
2906
  const notRun = results.filter((result) => result.status === "not-run");
2689
2907
  const lines = [
@@ -2738,7 +2956,7 @@ ${reason}` : reason;
2738
2956
  }
2739
2957
  async function writeJUnit(file, xml) {
2740
2958
  try {
2741
- await mkdir6(path8.dirname(file), { recursive: true });
2959
+ await mkdir6(path9.dirname(file), { recursive: true });
2742
2960
  await writeFile5(file, xml, "utf8");
2743
2961
  return file;
2744
2962
  } catch (error) {
@@ -2926,8 +3144,12 @@ ${notRun.length} test(s) not run (run stopped: ${notRun[0].reason}):`);
2926
3144
  for (const r of notRun) console.log(` - ${r.summary} (${r.file})`);
2927
3145
  }
2928
3146
  }
2929
- async function runOne(browser, test, config, sessionDir, session, runMask, budget, write) {
2930
- const brain = createBrain(createModel(config.llm).model, void 0, budget);
3147
+ function deviceTag(test, config) {
3148
+ const device = test.device ?? config.browser.device;
3149
+ return device ? ` [${device}]` : "";
3150
+ }
3151
+ async function runOne(browser, test, config, sessionDir, session, runMask, budget, write, firstJudge) {
3152
+ const brain = createBrain(createModel(config.llm).model, void 0, budget, firstJudge);
2931
3153
  let resolved;
2932
3154
  const mask = runMask;
2933
3155
  try {
@@ -2947,11 +3169,12 @@ async function runOne(browser, test, config, sessionDir, session, runMask, budge
2947
3169
  }
2948
3170
  throw error;
2949
3171
  }
2950
- const context = await browser.newContext(test.auth ? contextOptions(session) : {});
3172
+ const device = test.device ?? config.browser.device;
3173
+ const context = await browser.newContext(contextOptions(test.auth ? session : void 0, device));
2951
3174
  try {
2952
3175
  const page = await context.newPage();
2953
3176
  page.setDefaultTimeout(config.browser.timeout_ms);
2954
- return await executeTest(page, resolved, {
3177
+ const result = await executeTest(page, resolved, {
2955
3178
  brain,
2956
3179
  sessionDir,
2957
3180
  baseUrl: config.base_url,
@@ -2963,6 +3186,7 @@ async function runOne(browser, test, config, sessionDir, session, runMask, budge
2963
3186
  mask: (text) => mask.mask(text),
2964
3187
  onEvent: (event) => printEvent(event, write)
2965
3188
  });
3189
+ return device ? { ...result, device } : result;
2966
3190
  } finally {
2967
3191
  await context.close();
2968
3192
  }
@@ -2983,7 +3207,7 @@ function printImpactReport(impact, selection, cwd) {
2983
3207
  if (selection.unroutedSkipped.length > 0) {
2984
3208
  console.log("Unrouted tests (skipped):");
2985
3209
  for (const test of selection.unroutedSkipped) {
2986
- console.log(` ${test.summary} (${path9.relative(cwd, test.path)})`);
3210
+ console.log(` ${test.summary} (${path10.relative(cwd, test.path)})`);
2987
3211
  }
2988
3212
  }
2989
3213
  if (selection.uncoveredRoutes.length > 0) {
@@ -2999,16 +3223,17 @@ function reportNearMissedSecrets(variables) {
2999
3223
  );
3000
3224
  }
3001
3225
  }
3002
- async function finalize(results, skipped, options, sessionDir, secretsHeld, nearMissedSecrets, durationMs, impact, incomplete, spend) {
3226
+ async function finalize(results, skipped, options, sessionDir, secretsHeld, nearMissedSecrets, durationMs, impact, incomplete, spend, firstJudgeLog) {
3003
3227
  if (results.length > 0) printSummary(results);
3004
3228
  reportNearMissedSecrets(nearMissedSecrets);
3005
3229
  if (spend) console.log(formatSpendLine(spend));
3230
+ if (firstJudgeLog) console.log(firstJudgeLog.summaryLine());
3006
3231
  const score = scoreOf(results, incomplete !== void 0);
3007
3232
  console.log(
3008
3233
  incomplete ? formatIncompleteLine(score, incomplete.message) : formatScoreLine(computeScore(results), results, options.minScore)
3009
3234
  );
3010
3235
  if (options.junit) {
3011
- const target = typeof options.junit === "string" ? path9.resolve(options.cwd, options.junit) : path9.join(sessionDir, "junit.xml");
3236
+ const target = typeof options.junit === "string" ? path10.resolve(options.cwd, options.junit) : path10.join(sessionDir, "junit.xml");
3012
3237
  const xml = renderJUnit(results, skipped, {
3013
3238
  score,
3014
3239
  durationMs,
@@ -3017,10 +3242,10 @@ async function finalize(results, skipped, options, sessionDir, secretsHeld, near
3017
3242
  spend
3018
3243
  });
3019
3244
  await writeJUnit(target, xml);
3020
- console.log(`JUnit report: ${path9.relative(options.cwd, target)}`);
3245
+ console.log(`JUnit report: ${path10.relative(options.cwd, target)}`);
3021
3246
  }
3022
3247
  if (options.html) {
3023
- const target = typeof options.html === "string" ? path9.resolve(options.cwd, options.html) : path9.join(sessionDir, "report.html");
3248
+ const target = typeof options.html === "string" ? path10.resolve(options.cwd, options.html) : path10.join(sessionDir, "report.html");
3024
3249
  const html = await renderHtml(results, skipped, {
3025
3250
  score,
3026
3251
  durationMs,
@@ -3033,10 +3258,10 @@ async function finalize(results, skipped, options, sessionDir, secretsHeld, near
3033
3258
  // withhold-a-screenshot-that-saw-a-secret, D1): the run's mask, not the
3034
3259
  // failed test's own placeholders, because a login credential is echoed by
3035
3260
  // the pages of every test that comes after it.
3036
- screenshots: secretsHeld ? { withheldRelativeTo: path9.dirname(target) } : "embed"
3261
+ screenshots: secretsHeld ? { withheldRelativeTo: path10.dirname(target) } : "embed"
3037
3262
  });
3038
3263
  await writeHtml(target, html);
3039
- console.log(`HTML report: ${path9.relative(options.cwd, target)}`);
3264
+ console.log(`HTML report: ${path10.relative(options.cwd, target)}`);
3040
3265
  }
3041
3266
  if (incomplete) return EXIT_FAILED;
3042
3267
  if (reportUnclassified(options, impact)) return EXIT_FAILED;
@@ -3067,7 +3292,7 @@ function printRouteDrift(drift, cwd) {
3067
3292
  "Route drift (test routes declared by no routes: mapping \u2014 contribute nothing to --impacted selection):"
3068
3293
  );
3069
3294
  for (const { test, routes } of drift.drifted) {
3070
- console.error(` ${test.summary} (${path9.relative(cwd, test.path)}): ${routes.join(", ")}`);
3295
+ console.error(` ${test.summary} (${path10.relative(cwd, test.path)}): ${routes.join(", ")}`);
3071
3296
  }
3072
3297
  console.error("Fix the route typo, or add the route to a routes: mapping in .blastproof/config.yaml.");
3073
3298
  }
@@ -3076,7 +3301,7 @@ function printAuthoring(result, cwd) {
3076
3301
  console.error("\nAuthoring (a step enters a value but names none):");
3077
3302
  for (const { test, origin, index, step } of result.findings) {
3078
3303
  const where = origin === "setup" ? `setup step ${index}` : `step ${index}`;
3079
- console.error(` ${test.summary} (${path9.relative(cwd, test.path)}) ${where}:`);
3304
+ console.error(` ${test.summary} (${path10.relative(cwd, test.path)}) ${where}:`);
3080
3305
  console.error(` ${step}`);
3081
3306
  console.error(` \u2192 ${suggestValueClause(step)}`);
3082
3307
  }
@@ -3089,7 +3314,7 @@ function printDryRun(selected, config, cwd) {
3089
3314
  console.log(`
3090
3315
  Dry run: ${selected.length} test(s) selected, base_url=${config.base_url}`);
3091
3316
  for (const test of selected) {
3092
- console.log(` ${test.summary} [${test.priority}] (${path9.relative(cwd, test.path)})`);
3317
+ console.log(` ${test.summary} [${test.priority}]${deviceTag(test, config)} (${path10.relative(cwd, test.path)})`);
3093
3318
  }
3094
3319
  const needsLogin = selected.some((test) => test.auth);
3095
3320
  const authSteps = needsLogin ? config.auth?.steps ?? [] : [];
@@ -3097,7 +3322,10 @@ Dry run: ${selected.length} test(s) selected, base_url=${config.base_url}`);
3097
3322
  const ceiling = estimateMaxModelCalls(
3098
3323
  withAuth,
3099
3324
  DEFAULT_MAX_ITERATIONS_PER_STEP,
3100
- config.max_retries_per_step
3325
+ config.max_retries_per_step,
3326
+ // A judgment the first judge does not pass makes two calls (design
3327
+ // a-decision-model-judges-first, D8).
3328
+ config.first_judge ? 2 : 1
3101
3329
  );
3102
3330
  const authNote = authSteps.length > 0 ? ", including the login journey" : "";
3103
3331
  console.log(
@@ -3139,7 +3367,7 @@ async function runCommand(options) {
3139
3367
  impact = mapImpact(changedFiles, config.routes ?? {}, config.ignore ?? []);
3140
3368
  printUncommitted(await getUncommittedFiles(options.cwd), changedFiles, config, base);
3141
3369
  }
3142
- const testsDir = path9.join(options.cwd, TESTS_RELATIVE_DIR);
3370
+ const testsDir = path10.join(options.cwd, TESTS_RELATIVE_DIR);
3143
3371
  let files;
3144
3372
  try {
3145
3373
  files = await discoverTestFiles(testsDir);
@@ -3155,8 +3383,8 @@ async function runCommand(options) {
3155
3383
  } catch (error) {
3156
3384
  if (error instanceof TestFileError) {
3157
3385
  results.push({
3158
- file: path9.relative(options.cwd, file),
3159
- summary: path9.basename(file),
3386
+ file: path10.relative(options.cwd, file),
3387
+ summary: path10.basename(file),
3160
3388
  priority: "P1",
3161
3389
  tags: [],
3162
3390
  status: "failed",
@@ -3198,7 +3426,7 @@ ${results.length} test file(s) could not be parsed:`);
3198
3426
  }
3199
3427
  return reportUnclassified(options, impact) ? EXIT_FAILED : EXIT_OK;
3200
3428
  }
3201
- const sessionDir = path9.join(options.cwd, ".blastproof", "reports", sessionId());
3429
+ const sessionDir = path10.join(options.cwd, ".blastproof", "reports", sessionId());
3202
3430
  const startedAt = Date.now();
3203
3431
  if (selected.length === 0) {
3204
3432
  console.log(
@@ -3206,8 +3434,10 @@ ${results.length} test file(s) could not be parsed:`);
3206
3434
  );
3207
3435
  return finalize(results, selection.unroutedSkipped, options, sessionDir, false, [], Date.now() - startedAt, impact);
3208
3436
  }
3437
+ let decide;
3209
3438
  try {
3210
3439
  createModel(config.llm);
3440
+ if (config.first_judge) decide = createFirstJudgeClient(config.first_judge);
3211
3441
  } catch (error) {
3212
3442
  if (error instanceof MissingApiKeyError) {
3213
3443
  console.error(`error: ${error.message}`);
@@ -3219,6 +3449,18 @@ ${results.length} test file(s) could not be parsed:`);
3219
3449
  console.log(
3220
3450
  `blastproof run: ${selected.length} test(s), provider=${provider} model=${modelId}, base_url=${config.base_url}`
3221
3451
  );
3452
+ const firstJudgeLog = config.first_judge && decide ? new FirstJudgeLog(config.first_judge.model, config.first_judge.threshold, firstJudgeLogPath(sessionDir)) : void 0;
3453
+ const firstJudgeFor = (test) => firstJudgeLog && decide ? {
3454
+ model: firstJudgeLog.model,
3455
+ threshold: firstJudgeLog.threshold,
3456
+ decide,
3457
+ record: (entry) => firstJudgeLog.record(test, entry)
3458
+ } : void 0;
3459
+ if (firstJudgeLog) {
3460
+ console.log(
3461
+ `First judge (experimental): ${firstJudgeLog.model}, passing at p(yes) >= ${firstJudgeLog.threshold}; its decisions are kept in ${path10.relative(options.cwd, firstJudgeLogPath(sessionDir))}`
3462
+ );
3463
+ }
3222
3464
  const runMask = buildRunMask(config, parsed);
3223
3465
  const budget = options.budget ?? new RunBudget(resolveBudgetOptions(config, options));
3224
3466
  const preflight = await runPreflight({ browser: true, model: true, baseUrl: true }, config);
@@ -3239,10 +3481,11 @@ ${results.length} test file(s) could not be parsed:`);
3239
3481
  baseUrl: config.base_url,
3240
3482
  allowedOrigins: config.allowed_origins,
3241
3483
  browser,
3242
- brain: createBrain(createModel(config.llm).model, void 0, budget),
3484
+ brain: createBrain(createModel(config.llm).model, void 0, budget, firstJudgeFor("(login)")),
3243
3485
  maxRetries: config.max_retries_per_step,
3244
3486
  timeoutMs: config.browser.timeout_ms,
3245
3487
  maxSnapshotLines: config.browser.max_snapshot_lines,
3488
+ device: config.browser.device,
3246
3489
  mask: runMask,
3247
3490
  onEvent: printEvent
3248
3491
  });
@@ -3267,13 +3510,23 @@ ${results.length} test file(s) could not be parsed:`);
3267
3510
  if (stoppedBy) return { index, stopped: stoppedBy };
3268
3511
  const lines = [];
3269
3512
  const header = `
3270
- > ${test.summary} [${test.priority}] (${path9.relative(options.cwd, test.path)})`;
3513
+ > ${test.summary} [${test.priority}]${deviceTag(test, config)} (${path10.relative(options.cwd, test.path)})`;
3271
3514
  const write = streaming ? console.log : (line) => lines.push(line);
3272
3515
  if (streaming) console.log(header);
3273
3516
  else lines.push(header);
3274
3517
  try {
3275
3518
  budget.check();
3276
- const result = await runOne(browser, test, config, sessionDir, session, runMask, budget, write);
3519
+ const result = await runOne(
3520
+ browser,
3521
+ test,
3522
+ config,
3523
+ sessionDir,
3524
+ session,
3525
+ runMask,
3526
+ budget,
3527
+ write,
3528
+ firstJudgeFor(path10.relative(options.cwd, test.path))
3529
+ );
3277
3530
  if (!streaming) for (const line of lines) console.log(line);
3278
3531
  return { index, result };
3279
3532
  } catch (error) {
@@ -3312,7 +3565,8 @@ ${results.length} test file(s) could not be parsed:`);
3312
3565
  // phases deliberately, so reporting at the point of use rather than the
3313
3566
  // point of ownership would print the running total twice for a single
3314
3567
  // allowance, the second line silently including the first.
3315
- options.budget === void 0 ? budget.spend() : void 0
3568
+ options.budget === void 0 ? budget.spend() : void 0,
3569
+ firstJudgeLog
3316
3570
  );
3317
3571
  }
3318
3572
 
@@ -3327,7 +3581,7 @@ function printAuthEvent(event) {
3327
3581
  }
3328
3582
  }
3329
3583
  async function loadSuite(cwd) {
3330
- const testsDir = path10.join(cwd, TESTS_RELATIVE_DIR);
3584
+ const testsDir = path11.join(cwd, TESTS_RELATIVE_DIR);
3331
3585
  let files;
3332
3586
  try {
3333
3587
  files = await discoverTestFiles(testsDir);
@@ -3457,6 +3711,7 @@ async function planCommand(options) {
3457
3711
  maxRetries: config.max_retries_per_step,
3458
3712
  timeoutMs: config.browser.timeout_ms,
3459
3713
  maxSnapshotLines: config.browser.max_snapshot_lines,
3714
+ device: config.browser.device,
3460
3715
  mask,
3461
3716
  onEvent: printAuthEvent
3462
3717
  });
@@ -3475,7 +3730,7 @@ async function planCommand(options) {
3475
3730
  console.log(`
3476
3731
  > ${route}`);
3477
3732
  let draft;
3478
- const context = await browser.newContext(contextOptions(session));
3733
+ const context = await browser.newContext(contextOptions(session, config.browser.device));
3479
3734
  try {
3480
3735
  const page = await context.newPage();
3481
3736
  page.setDefaultTimeout(config.browser.timeout_ms);
@@ -3509,8 +3764,8 @@ async function planCommand(options) {
3509
3764
  if (options.write) {
3510
3765
  try {
3511
3766
  const file = await writeDraft(options.cwd, draft, { route, base });
3512
- written.push(path10.relative(options.cwd, file));
3513
- console.log(` wrote ${path10.relative(options.cwd, file)}`);
3767
+ written.push(path11.relative(options.cwd, file));
3768
+ console.log(` wrote ${path11.relative(options.cwd, file)}`);
3514
3769
  } catch (error) {
3515
3770
  generated.pop();
3516
3771
  const reason = error instanceof Error ? error.message : String(error);
@@ -3637,7 +3892,7 @@ function parsePositiveNumber(flag) {
3637
3892
  };
3638
3893
  }
3639
3894
  var program = new Command();
3640
- program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.27.0");
3895
+ program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.28.0");
3641
3896
  program.command("init").description("Scaffold .blastproof/ (config, tests, sample tests) in the current directory").action(async () => {
3642
3897
  try {
3643
3898
  const result = await initProject(process.cwd());