Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Test Report Analyst v0.1.2 · claude-code

Archive SHA-256 5870590dae3ef5e34931c7bd1b75ca0c6139adcd98b8815225bc07d185106909 · 68.3 KB · built Dec 1, 2026

src/analyze.js

// Loads test result and coverage files from the workspace and analyses them. Read-only: this module
// never writes. Untrusted report content (test names, failure messages, file paths) is only counted,
// truncated and quoted; Markdown output escapes it or puts it in code blocks.
import { ToolError } from "./errors.js";
import { normalizeRel, readText, findFiles, pathKey } from "./fsguard.js";
import { isGlob } from "./glob.js";
import { detectFormat, parseJunit, parseTap, parseJestJson, parseLcov } from "./parsers.js";

export const HARD_LIMITS = { max_file_bytes: 50 * 1024 * 1024, max_total_read_bytes: 200 * 1024 * 1024, max_files: 1000, max_tests: 200_000, timeout_seconds: 120 };
export const DEFAULT_LIMITS = { max_file_bytes: 20 * 1024 * 1024, max_total_read_bytes: 100 * 1024 * 1024, max_files: 200, max_tests: 200_000, timeout_seconds: 60 };
const PATH_ERRORS = new Set(["path_outside_workspace", "hidden_path", "invalid_path", "unsafe_path", "invalid_workspace"]);

export function createContext(root, opts = {}) {
  const limits = { ...DEFAULT_LIMITS };
  if (opts.max_file_bytes) limits.max_file_bytes = Math.min(opts.max_file_bytes, HARD_LIMITS.max_file_bytes);
  const deadline = opts.deadlineMs ?? Date.now() + limits.timeout_seconds * 1000;
  const warnings = [];
  const ctx = {
    root,
    limits,
    sources: new Map(),
    readBytes: 0,
    warnings,
    warn(w) {
      if (!warnings.includes(w) && warnings.length < 200) warnings.push(w);
    },
    tick() {
      if (Date.now() > deadline) throw new ToolError("time_limit_exceeded", `Reading the reports took longer than ${limits.timeout_seconds} s.`);
    },
    addRead(n, field) {
      ctx.readBytes += n;
      if (ctx.readBytes > limits.max_total_read_bytes) throw new ToolError("limit_exceeded", `${field}: more than ${limits.max_total_read_bytes} bytes read in total.`);
    },
  };
  return ctx;
}

// ---------------------------------------------------------------------------------------------
// Loading
// ---------------------------------------------------------------------------------------------
function expandPaths(ctx, paths, field) {
  const out = [];
  const seen = new Set();
  for (const [i, p] of (paths ?? []).entries()) {
    const f = `${field}.paths[${i}]`;
    if (isGlob(p)) {
      const rel = normalizeRel(p, f, { glob: true });
      const found = findFiles(ctx, rel, f).filter((x) => x.kind === "file");
      if (!found.length) ctx.warn(`${f}: the pattern ${rel} matched no files.`);
      for (const x of found) {
        if (seen.has(pathKey(x.path))) continue;
        seen.add(pathKey(x.path));
        out.push(x.path);
      }
    } else {
      const rel = normalizeRel(p, f);
      if (!seen.has(pathKey(rel))) {
        seen.add(pathKey(rel));
        out.push(rel);
      }
    }
  }
  if (out.length > ctx.limits.max_files) throw new ToolError("limit_exceeded", `${field}: ${out.length} files; the limit is ${ctx.limits.max_files} per run.`);
  return out;
}

function parseOne(ctx, label, text, format, want, field) {
  const fmt = format && format !== "auto" ? format : detectFormat(label, text);
  if (!fmt) throw new ToolError("invalid_input", `${field}: cannot tell the format of ${label}; pass format (junit, tap, jest${want === "coverage" ? ", lcov" : ""}).`);
  if (want === "tests" && fmt === "lcov") throw new ToolError("invalid_input", `${field}: ${label} is lcov coverage, not test results (use coverage_report).`);
  if (want === "coverage" && fmt !== "lcov") throw new ToolError("invalid_input", `${field}: ${label} is ${fmt} test results, not lcov coverage (use summarize_results).`);
  const opts = { field: `${field} (${label})`, fileLabel: label, tick: () => ctx.tick() };
  if (fmt === "junit") return { format: fmt, ...parseJunit(text, opts) };
  if (fmt === "tap") return { format: fmt, ...parseTap(text, opts) };
  if (fmt === "jest") return { format: fmt, ...parseJestJson(text, opts) };
  return { format: fmt, ...parseLcov(text, opts) };
}

/**
 * Reads one run: { paths?: [path or glob], results_text?: string, format?, label? }.
 * A file that cannot be read or parsed is reported in files[] (and makes the run incomplete); unsafe
 * paths and global limits stop the call.
 */
export function loadRun(ctx, src, want, field) {
  if (!src || ((!src.paths || !src.paths.length) && typeof src.results_text !== "string")) throw new ToolError("invalid_input", `${field}: give paths (files or globs inside the workspace) or results_text.`);
  const files = [];
  const cases = [];
  const coverage = [];
  let incomplete = false;
  const handle = (label, getText) => {
    ctx.tick();
    try {
      const r = parseOne(ctx, label, getText(), src.format, want, field);
      r.warnings?.forEach((w) => ctx.warn(w));
      if (r.incomplete) incomplete = true;
      if (want === "tests") {
        cases.push(...r.cases);
        if (cases.length > ctx.limits.max_tests) throw new ToolError("limit_exceeded", `${field}: more than ${ctx.limits.max_tests} test results.`);
        files.push({ path: label, format: r.format, status: "parsed", tests: r.cases.length });
      } else {
        coverage.push(...r.files);
        files.push({ path: label, format: r.format, status: "parsed", files: r.files.length });
      }
    } catch (e) {
      if (!(e instanceof ToolError) || PATH_ERRORS.has(e.code) || e.code === "time_limit_exceeded" || (e.code === "limit_exceeded" && /in total|test results|per run/.test(e.message))) throw e;
      incomplete = true;
      files.push({ path: label, format: null, status: "error", error: `${e.code}: ${e.message}` });
      ctx.warn(`${label} was not used: ${e.message}`);
    }
  };
  for (const rel of expandPaths(ctx, src.paths, field)) handle(rel, () => readText(ctx, rel, field));
  if (typeof src.results_text === "string") handle(src.label ? `${src.label} (results_text)` : "results_text", () => src.results_text);
  // TAP has no file names inside it: with several TAP files in one run, the file name keeps their suites apart.
  const tapFiles = files.filter((f) => f.format === "tap").map((f) => f.path);
  if (tapFiles.length > 1) for (const cs of cases) if (tapFiles.includes(cs.file)) cs.suite = cs.suite === "(top level)" ? cs.file : `${cs.file} > ${cs.suite}`;
  if (want === "tests") normalisePaths(cases);
  return { label: src.label ?? null, files, cases, coverage, complete: !incomplete };
}

const ABS = /^(?:[A-Za-z]:[\\/]|\/|\\\\)/;
function commonDir(paths) {
  if (!paths.length) return "";
  const split = paths.map((p) => p.split("/").slice(0, -1));
  let k = 0;
  while (split.every((s) => k < s.length && s[k] === split[0][k])) k++;
  return split[0].slice(0, k).join("/");
}
/** Folder to strip from absolute paths: the common folder minus its last part, so "src/a.test.ts" keeps its "src". */
function stripPrefix(abs) {
  const dir = abs.length > 1 ? commonDir(abs) : abs.length === 1 ? abs[0].split("/").slice(0, -1).join("/") : "";
  return dir.includes("/") ? dir.slice(0, dir.lastIndexOf("/")) : "";
}

/** Makes absolute file paths in reports (machine-specific) relative to (almost) their common folder. */
function normalisePaths(cases) {
  const abs = [...new Set(cases.flatMap((c) => [c.file, c.suite]).filter((p) => p && ABS.test(p)).map((p) => p.replace(/\\/g, "/")))];
  const prefix = stripPrefix(abs);
  const fix = (p) => {
    if (!p || !ABS.test(p)) return p;
    const n = p.replace(/\\/g, "/");
    return prefix && n.startsWith(prefix + "/") ? n.slice(prefix.length + 1) : n;
  };
  for (const c of cases) {
    c.file = fix(c.file);
    c.suite = fix(c.suite);
  }
}

// ---------------------------------------------------------------------------------------------
// Summaries
// ---------------------------------------------------------------------------------------------
const FAIL = new Set(["failed", "error"]);
const norm = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
export const caseKey = (c) => `${norm(c.suite)} :: ${c.classname && norm(c.classname) !== norm(c.suite) ? `${norm(c.classname)} :: ` : ""}${norm(c.name)}`;
const suiteKey = (c) => `${norm(c.suite)} :: ${norm(c.name)}`;
const looseKey = (c) => `${norm((c.file || c.suite || "").split(/[\\/]/).pop())} :: ${norm(c.name)}`;

export function firstLines(msg, n = 5, width = 300) {
  if (!msg) return { text: null, lines: 0 };
  const all = msg.split("\n").map((l) => l.replace(/\s+$/, "")).filter((l, i, a) => l || (i > 0 && i < a.length - 1));
  const shown = all.slice(0, n).map((l) => (l.length > width ? l.slice(0, width - 1) + "…" : l));
  return { text: shown.join("\n"), lines: all.length };
}

function totalsOf(cases) {
  const t = { tests: cases.length, passed: 0, failed: 0, errors: 0, skipped: 0, todo: 0, duration_ms: 0, with_duration: 0 };
  for (const c of cases) {
    if (c.status === "passed") t.passed++;
    else if (c.status === "failed") t.failed++;
    else if (c.status === "error") t.errors++;
    else if (c.status === "skipped") t.skipped++;
    else if (c.status === "todo") t.todo++;
    if (c.duration_ms !== null) {
      t.duration_ms += c.duration_ms;
      t.with_duration++;
    }
  }
  t.duration_ms = Math.round(t.duration_ms * 1000) / 1000;
  return t;
}

/** Groups attempts of the same test; mixed pass/fail attempts (or reported reruns) mark it flaky within the run. */
export function byTest(cases) {
  const m = new Map();
  for (const c of cases) {
    const k = caseKey(c);
    let g = m.get(k);
    if (!g) m.set(k, (g = { key: k, suiteKey: suiteKey(c), loose: looseKey(c), suite: c.suite, name: c.name, file: c.file, attempts: [], retried: false }));
    g.attempts.push(c);
    if (c.retried) g.retried = true;
  }
  for (const g of m.values()) {
    const st = g.attempts.map((a) => a.status);
    const anyPass = st.includes("passed");
    const anyFail = st.some((s) => FAIL.has(s));
    g.status = anyPass && anyFail ? "passed" : anyFail ? (st.includes("failed") ? "failed" : "error") : anyPass ? "passed" : st[st.length - 1];
    g.flaky_in_run = (anyPass && anyFail) || (g.retried && anyPass);
    g.message = g.attempts.find((a) => FAIL.has(a.status))?.message ?? null;
    const d = g.attempts.map((a) => a.duration_ms).filter((x) => x !== null);
    g.duration_ms = d.length ? Math.max(...d) : null;
  }
  return m;
}

export function summarize(run, opts = {}) {
  const slowestN = opts.slowest ?? 10;
  const maxFailures = opts.max_failures ?? 50;
  const nLines = opts.message_lines ?? 5;
  const totals = totalsOf(run.cases);
  const suites = new Map();
  for (const c of run.cases) {
    let s = suites.get(c.suite);
    if (!s) suites.set(c.suite, (s = { suite: c.suite, file: c.file, cases: [] }));
    s.cases.push(c);
  }
  const suiteRows = [...suites.values()]
    .map((s) => {
      const t = totalsOf(s.cases);
      return { suite: s.suite, file: s.file, tests: t.tests, passed: t.passed, failed: t.failed, errors: t.errors, skipped: t.skipped, todo: t.todo, duration_ms: t.with_duration ? t.duration_ms : null };
    })
    .sort((a, b) => b.failed + b.errors - (a.failed + a.errors) || (a.suite < b.suite ? -1 : a.suite > b.suite ? 1 : 0));
  const slowest = run.cases
    .filter((c) => c.duration_ms !== null)
    .sort((a, b) => b.duration_ms - a.duration_ms)
    .slice(0, slowestN)
    .map((c) => ({ suite: c.suite, name: c.name, duration_ms: c.duration_ms, status: c.status }));
  const failing = run.cases.filter((c) => FAIL.has(c.status));
  const failures = failing.slice(0, maxFailures).map((c) => {
    const fl = firstLines(c.message, nLines);
    return { suite: c.suite, name: c.name, classname: c.classname, file: c.file, status: c.status, message: fl.text, message_lines: fl.lines, duration_ms: c.duration_ms };
  });
  const flaky = [...byTest(run.cases).values()].filter((g) => g.flaky_in_run).map((g) => ({ suite: g.suite, name: g.name, reason: g.retried ? "passed after a reported retry/rerun" : "the run contains passing and failing attempts" }));
  const status = !totals.tests ? "no_tests" : totals.failed + totals.errors ? "failed" : "passed";
  return { status, complete: run.complete, totals, suites: suiteRows.slice(0, 500), suites_total: suiteRows.length, slowest, failures, failures_total: failing.length, flaky_in_run: flaky, files: run.files };
}

// ---------------------------------------------------------------------------------------------
// Comparing two runs
// ---------------------------------------------------------------------------------------------
export function compare(base, head, opts = {}) {
  const changed = Array.isArray(opts.changed_files) ? opts.changed_files : null;
  const nLines = opts.message_lines ?? 5;
  const limit = opts.limit ?? 100;
  const b = byTest(base.cases);
  const h = byTest(head.cases);
  // Fallbacks when the exact key differs (other machine, other reporter): suite + name, then file name + name; each only when unique.
  const indexBy = (m, f) => {
    const ix = new Map();
    for (const g of m.values()) ix.set(g[f], ix.has(g[f]) ? null : g); // null = ambiguous
    return ix;
  };
  const fallbacks = [["suiteKey", indexBy(b, "suiteKey"), indexBy(h, "suiteKey")], ["loose", indexBy(b, "loose"), indexBy(h, "loose")]];
  const pairs = [];
  const matchedBase = new Set();
  const added = [];
  for (const g of h.values()) {
    let o = b.get(g.key);
    for (const [f, bix, hix] of fallbacks) {
      if (o) break;
      const cand = bix.get(g[f]);
      if (cand && hix.get(g[f]) === g && !h.has(cand.key) && !matchedBase.has(cand.key)) o = cand;
    }
    if (o) {
      matchedBase.add(o.key);
      pairs.push([o, g]);
    } else added.push(g);
  }
  const removed = [...b.values()].filter((g) => !matchedBase.has(g.key));
  const kind = (s) => (FAIL.has(s) ? "fail" : s === "passed" ? "pass" : "other");
  const row = (o, g, extra = {}) => ({ suite: g.suite, name: g.name, base_status: o.status, head_status: g.status, ...extra });
  const newFailures = [];
  const fixed = [];
  const stillFailing = [];
  const flaky = [];
  const slower = [];
  for (const [o, g] of pairs) {
    const ko = kind(o.status);
    const kg = kind(g.status);
    const statusFlip = (ko === "pass" && kg === "fail") || (ko === "fail" && kg === "pass");
    const noChanges = changed !== null && changed.length === 0;
    if (statusFlip && noChanges) flaky.push(row(o, g, { reason: "status changed between the runs and no file changes were recorded" }));
    else if (g.flaky_in_run || o.flaky_in_run) flaky.push(row(o, g, { reason: g.flaky_in_run ? "passed and failed within the head run (retry or rerun)" : "passed and failed within the base run (retry or rerun)" }));
    if (ko === "pass" && kg === "fail") newFailures.push(row(o, g, { message: firstLines(g.message, nLines).text, flaky_candidate: noChanges }));
    else if (ko === "fail" && kg === "pass") fixed.push(row(o, g, { flaky_candidate: noChanges }));
    else if (ko === "fail" && kg === "fail") stillFailing.push(row(o, g, { message: firstLines(g.message, nLines).text }));
    if (o.duration_ms !== null && g.duration_ms !== null && g.duration_ms >= 100 + o.duration_ms && g.duration_ms >= o.duration_ms * 1.5) {
      slower.push({ suite: g.suite, name: g.name, base_ms: o.duration_ms, head_ms: g.duration_ms, change_pct: o.duration_ms > 0 ? Math.round(((g.duration_ms - o.duration_ms) / o.duration_ms) * 1000) / 10 : null });
    }
  }
  for (const g of added) if (g.flaky_in_run) flaky.push({ suite: g.suite, name: g.name, base_status: null, head_status: g.status, reason: "new test that passed and failed within the head run" });
  slower.sort((x, y) => y.head_ms - y.base_ms - (x.head_ms - x.base_ms));
  const cut = (a) => a.slice(0, limit);
  return {
    base: { label: base.label, status: summarize(base).status, complete: base.complete, totals: totalsOf(base.cases) },
    head: { label: head.label, status: summarize(head).status, complete: head.complete, totals: totalsOf(head.cases) },
    matched: pairs.length,
    new_failures: cut(newFailures),
    fixed: cut(fixed),
    still_failing: cut(stillFailing),
    new_tests: cut(added.map((g) => ({ suite: g.suite, name: g.name, status: g.status }))),
    removed_tests: cut(removed.map((g) => ({ suite: g.suite, name: g.name, status: g.status }))),
    flaky_candidates: cut(flaky),
    slower: slower.slice(0, 10),
    counts: { new_failures: newFailures.length, fixed: fixed.length, still_failing: stillFailing.length, new_tests: added.length, removed_tests: removed.length, flaky_candidates: flaky.length },
    changed_files_known: changed !== null,
  };
}

// ---------------------------------------------------------------------------------------------
// Coverage
// ---------------------------------------------------------------------------------------------
function ranges(nums, max = 30) {
  const out = [];
  let i = 0;
  while (i < nums.length && out.length < max) {
    let j = i;
    while (j + 1 < nums.length && nums[j + 1] === nums[j] + 1) j++;
    out.push(i === j ? `${nums[i]}` : `${nums[i]}-${nums[j]}`);
    i = j + 1;
  }
  return out.join(", ") + (i < nums.length ? ", …" : "");
}
const pct = (hit, found) => (found ? Math.round((hit / found) * 10000) / 100 : null);

export function coverage(run, opts = {}) {
  const merged = new Map();
  for (const f of run.coverage) {
    const k = f.path.replace(/\\/g, "/");
    const m = merged.get(k);
    if (!m) merged.set(k, { ...f, path: k });
    else {
      for (const [l, c] of f.lines) m.lines.set(l, Math.max(m.lines.get(l) ?? 0, c));
      for (const [n, c] of f.fns) m.fns.set(n, Math.max(m.fns.get(n) ?? 0, c));
      for (const [n, c] of f.branches) m.branches.set(n, Math.max(m.branches.get(n) ?? 0, c));
    }
  }
  const abs = [...merged.keys()].filter((p) => ABS.test(p));
  const prefix = stripPrefix(abs);
  const rows = [...merged.values()].map((f) => {
    const lines = [...f.lines.entries()].sort((a, b) => a[0] - b[0]);
    const found = lines.length || (Number.isFinite(f.lf) ? f.lf : 0);
    const hit = lines.length ? lines.filter(([, c]) => c > 0).length : Number.isFinite(f.lh) ? f.lh : 0;
    const uncovered = lines.filter(([, c]) => c === 0).map(([l]) => l);
    const fnFound = f.fns.size;
    const fnHit = [...f.fns.values()].filter((c) => c > 0).length;
    const brFound = f.branches.size;
    const brHit = [...f.branches.values()].filter((c) => c > 0).length;
    const path = prefix && f.path.startsWith(prefix + "/") ? f.path.slice(prefix.length + 1) : f.path;
    const r = { path, lines_found: found, lines_hit: hit, line_pct: pct(hit, found), uncovered_lines: found - hit, uncovered_ranges: ranges(uncovered), functions_found: fnFound, functions_hit: fnHit, branches_found: brFound, branches_hit: brHit };
    if (opts.include_lines) r.uncovered_line_numbers = uncovered.slice(0, 5000);
    return r;
  });
  const sort = opts.sort ?? "uncovered";
  rows.sort((a, b) => (sort === "path" ? (a.path < b.path ? -1 : 1) : sort === "coverage" ? (a.line_pct ?? 101) - (b.line_pct ?? 101) || (a.path < b.path ? -1 : 1) : b.uncovered_lines - a.uncovered_lines || (a.path < b.path ? -1 : 1)));
  const t = rows.reduce((s, r) => ({ lf: s.lf + r.lines_found, lh: s.lh + r.lines_hit, ff: s.ff + r.functions_found, fh: s.fh + r.functions_hit, bf: s.bf + r.branches_found, bh: s.bh + r.branches_hit }), { lf: 0, lh: 0, ff: 0, fh: 0, bf: 0, bh: 0 });
  const totals = { files: rows.length, lines_found: t.lf, lines_hit: t.lh, line_pct: pct(t.lh, t.lf), uncovered_lines: t.lf - t.lh, functions_found: t.ff, functions_hit: t.fh, function_pct: pct(t.fh, t.ff), branches_found: t.bf, branches_hit: t.bh, branch_pct: pct(t.bh, t.bf) };
  const threshold = opts.threshold ?? null;
  const below = threshold === null ? [] : rows.filter((r) => r.line_pct !== null && r.line_pct < threshold).map((r) => r.path);
  return { totals, files: rows.slice(0, opts.limit ?? 50), files_total: rows.length, threshold, below_threshold: below, sources: run.files, complete: run.complete };
}

// ---------------------------------------------------------------------------------------------
// Markdown
// ---------------------------------------------------------------------------------------------
export const md = (s) =>
  String(s ?? "")
    .replace(/\r\n?|\n/g, " ")
    .replace(/[\\`*_[\]<>|~&]/g, "\\$&")
    .replace(/^(\s*)([#+\-=])(?=\s|$|[-=]+\s*$)/, "$1\\$2")
    .replace(/^(\s*\d{1,9})([.)])(?=\s|$)/, "$1\\$2");

/** Fenced code block whose fence is longer than any backtick run in the text (cannot be closed early). */
export function codeBlock(text) {
  const runs = String(text).match(/`+/g) ?? [];
  const fence = "`".repeat(Math.max(3, ...runs.map((r) => r.length + 1)));
  return `${fence}text\n${text}\n${fence}`;
}
const fmtMs = (v) => (v === null || v === undefined ? "n/a" : v >= 1000 ? `${(v / 1000).toFixed(2)} s` : `${Math.round(v)} ms`);

export function summaryMarkdown(s, title = "Test results") {
  const t = s.totals;
  const out = [`# ${md(title)}`, "", `**${s.status === "passed" ? "Passed" : s.status === "failed" ? "Failed" : "No tests found"}**: ${t.tests} tests, ${t.passed} passed, ${t.failed} failed, ${t.errors} errors, ${t.skipped} skipped${t.todo ? `, ${t.todo} todo` : ""}. Total test time ${fmtMs(t.with_duration ? t.duration_ms : null)}.${s.complete ? "" : " **Incomplete:** some files could not be read or the run stopped early (see Files)."}`, ""];
  if (s.suites.length) {
    out.push("## Suites", "", "| Suite | Tests | Passed | Failed | Errors | Skipped | Time |", "| --- | ---: | ---: | ---: | ---: | ---: | ---: |");
    for (const r of s.suites.slice(0, 50)) out.push(`| ${md(r.suite)} | ${r.tests} | ${r.passed} | ${r.failed} | ${r.errors} | ${r.skipped} | ${fmtMs(r.duration_ms)} |`);
    if (s.suites_total > 50) out.push("", `(${s.suites_total - 50} more suites not shown)`);
    out.push("");
  }
  if (s.failures.length) {
    out.push(`## Failures (${s.failures_total})`, "");
    for (const f of s.failures) {
      out.push(`### ${md(f.suite)}: ${md(f.name)}`, "", `${f.status === "error" ? "Error" : "Failed"}${f.duration_ms !== null ? ` after ${fmtMs(f.duration_ms)}` : ""}${f.message_lines > 0 ? `; first ${Math.min(f.message_lines, f.message.split("\n").length)} of ${f.message_lines} message lines:` : "; no message."}`, "");
      if (f.message) out.push(codeBlock(f.message), "");
    }
  }
  if (s.slowest.length) {
    out.push("## Slowest tests", "", "| Test | Suite | Time | Status |", "| --- | --- | ---: | --- |");
    for (const r of s.slowest) out.push(`| ${md(r.name)} | ${md(r.suite)} | ${fmtMs(r.duration_ms)} | ${r.status} |`);
    out.push("");
  }
  if (s.flaky_in_run.length) out.push("## Flaky within this run", "", ...s.flaky_in_run.map((f) => `- ${md(f.suite)}: ${md(f.name)} (${md(f.reason)})`), "");
  out.push("## Files", "", ...s.files.map((f) => `- ${md(f.path)}: ${f.status === "parsed" ? `${f.format}, ${f.tests ?? f.files} ${f.tests !== undefined ? "tests" : "files"}` : `not used (${md(f.error)})`}`));
  return out.join("\n") + "\n";
}

export function compareMarkdown(c) {
  const lbl = (r, d) => md(r.label || d);
  const tl = (r) => `${r.totals.tests} tests, ${r.totals.failed + r.totals.errors} failing, ${r.totals.skipped} skipped${r.complete ? "" : " (incomplete)"}`;
  const out = ["# Test run comparison", "", `- Base (${lbl(c.base, "base")}): ${tl(c.base)}`, `- Head (${lbl(c.head, "head")}): ${tl(c.head)}`, `- Matched tests: ${c.matched}; new failures ${c.counts.new_failures}, fixed ${c.counts.fixed}, still failing ${c.counts.still_failing}, new tests ${c.counts.new_tests}, removed ${c.counts.removed_tests}, flaky candidates ${c.counts.flaky_candidates}.`, ""];
  const list = (title, rows, fn) => {
    if (!rows.length) return;
    out.push(`## ${title}`, "", ...rows.map(fn), "");
  };
  list("New failures", c.new_failures, (r) => `- ${md(r.suite)}: ${md(r.name)} (${r.base_status} -> ${r.head_status})${r.flaky_candidate ? " (flaky candidate)" : ""}${r.message ? `: ${md(r.message.split("\n")[0])}` : ""}`);
  list("Fixed", c.fixed, (r) => `- ${md(r.suite)}: ${md(r.name)}${r.flaky_candidate ? " (flaky candidate)" : ""}`);
  list("Flaky candidates", c.flaky_candidates, (r) => `- ${md(r.suite)}: ${md(r.name)}: ${md(r.reason)}`);
  list("Still failing", c.still_failing, (r) => `- ${md(r.suite)}: ${md(r.name)}`);
  list("Slower", c.slower, (r) => `- ${md(r.suite)}: ${md(r.name)}: ${fmtMs(r.base_ms)} -> ${fmtMs(r.head_ms)}`);
  list("New tests", c.new_tests, (r) => `- ${md(r.suite)}: ${md(r.name)} (${r.status})`);
  list("Removed tests", c.removed_tests, (r) => `- ${md(r.suite)}: ${md(r.name)}`);
  if (!c.changed_files_known) out.push("Flaky candidates from status changes need changed_files (an empty list when no files changed between the runs).", "");
  return out.join("\n");
}

export function coverageMarkdown(c) {
  const t = c.totals;
  const p = (v) => (v === null ? "n/a" : `${v}%`);
  const out = ["# Coverage", "", `Lines ${p(t.line_pct)} (${t.lines_hit}/${t.lines_found}, ${t.uncovered_lines} uncovered), functions ${p(t.function_pct)}, branches ${p(t.branch_pct)} across ${t.files} files.${c.complete ? "" : " **Incomplete:** some files could not be read."}`, ""];
  if (c.threshold !== null) out.push(c.below_threshold.length ? `${c.below_threshold.length} file(s) below ${c.threshold}% line coverage.` : `Every file is at or above ${c.threshold}% line coverage.`, "");
  out.push("| File | Lines | Uncovered | Uncovered lines | Functions | Branches |", "| --- | ---: | ---: | --- | ---: | ---: |");
  for (const r of c.files) out.push(`| ${md(r.path)} | ${p(r.line_pct)} | ${r.uncovered_lines} | ${md(r.uncovered_ranges) || " "} | ${r.functions_hit}/${r.functions_found} | ${r.branches_hit}/${r.branches_found} |`);
  if (c.files_total > c.files.length) out.push("", `(${c.files_total - c.files.length} more files not shown)`);
  return out.join("\n") + "\n";
}

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).