opencode-model-router 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +306 -0
  2. package/README.md +3 -2
  3. package/package.json +8 -1
  4. package/src/compat/background.ts +5 -0
  5. package/src/compat/session-lookup.ts +21 -0
  6. package/src/compat/v2-hooks.ts +256 -88
  7. package/src/compat/v2-observations.ts +1 -0
  8. package/src/compat/v2-vocabulary.ts +14 -0
  9. package/src/executor/create.ts +3 -0
  10. package/src/executor/git.ts +110 -26
  11. package/src/executor/integrate/checks.ts +29 -11
  12. package/src/executor/integrate/queue.ts +95 -13
  13. package/src/executor/ledger.ts +16 -12
  14. package/src/executor/lfs-restore.ts +492 -0
  15. package/src/executor/paths.ts +7 -2
  16. package/src/executor/recovery.ts +2 -1
  17. package/src/executor/runtime.ts +1010 -226
  18. package/src/executor/slots/pool.ts +120 -19
  19. package/src/executor/slots/provision.ts +111 -23
  20. package/src/executor/slots/root.ts +81 -0
  21. package/src/executor/types.ts +28 -2
  22. package/src/executor/unattended.ts +6 -1
  23. package/src/executor/verify-trees.ts +507 -0
  24. package/src/guard/enforce.ts +2 -1
  25. package/src/guard/fingerprint.ts +9 -0
  26. package/src/guard/guards.ts +7 -1
  27. package/src/index.ts +107 -27
  28. package/src/router/answer-dedup.ts +198 -0
  29. package/src/router/common-dir.ts +241 -0
  30. package/src/router/config.ts +71 -12
  31. package/src/router/diff-handles.ts +322 -0
  32. package/src/router/diff-summary.ts +318 -0
  33. package/src/router/git-metadata-guard.ts +144 -7
  34. package/src/router/git-tools.ts +930 -73
  35. package/src/router/role-agents.ts +100 -36
  36. package/src/router/run-summary.ts +253 -0
  37. package/src/router/run-tools.ts +145 -23
  38. package/src/router/sessions.ts +14 -1
  39. package/src/routing/classify/rules.ts +93 -14
  40. package/src/routing/wire/hint.ts +9 -2
  41. package/src/v2.ts +3 -1
  42. package/src/verify/exec.ts +454 -2
  43. package/src/verify/plan-task.ts +86 -26
  44. package/src/verify/runner.ts +14 -6
  45. package/src/verify/tree.ts +5 -1
  46. package/src/verify/types.ts +44 -0
  47. package/src/verify/wiring.ts +87 -10
@@ -18,10 +18,11 @@
18
18
  import { lstatSync, realpathSync, statSync } from "node:fs";
19
19
  import { join, posix, resolve as resolvePath, win32 } from "node:path";
20
20
  import { EXECUTOR_HOME_DIRNAME, resolveExecutorHome } from "../executor/paths";
21
+ import { defaultSlotsRoot } from "../executor/slots/root";
22
+ import { onDrvfs, reachesFolded, resolveCommonDirOnDisk, type CommonDirDeps } from "./common-dir";
21
23
  import { resolveActiveTiers, resolveRolesRouting, resolveRouting, slotsDirProblem, type RouterConfig, type TierConfig } from "./config";
22
24
  import {
23
- GIT_TOOL_NAMES, gitEnvironment, gitExecutable, gitPointers, hardeningArgs, inheritedSafeDirectoryArgs, nearestRepository, spawnBounded,
24
- workRootGuards,
25
+ GIT_TOOL_NAMES, gitEnvironment, gitExecutable, hardeningArgs, inheritedSafeDirectoryArgs, spawnBounded, workRootGuards,
25
26
  } from "./git-tools";
26
27
  import { positiveBudget, REFUSAL_CAP, ROUTE_BUDGET_RAISE_MAX, TIER_GUARD_BUDGET } from "./guard-profile";
27
28
  import { PLUGIN_AGENT, pluginAgentMarker, pluginAgentPolicy, type PluginAgentMarker } from "./plugin-agents";
@@ -244,22 +245,39 @@ export function approvedRootPattern(path: string, realpath: Realpath = nativeRea
244
245
  }
245
246
 
246
247
  /**
247
- * QA-62C-1, QA-62C-13: the git common directory of the repository holding `directory`, read from disk without running
248
- * git (used off Windows, where the executor never runs but a Windows host sharing the repository may). The nearest
249
- * checkout ({@link nearestRepository}) is read by the hardened {@link gitPointers}: `.git` and `commondir` at most 4 KiB,
250
- * regular files only, opened non-blocking, a linked `.git` and a network or device pointer refused. `common` is the
251
- * git directory's `commondir` target when present, else the git directory (`<checkout>/.git` or what `gitdir:` names).
252
- * `{}` when no repository is found or its `.git` names no git directory; `problem` when the pointers are refused or unreadable.
248
+ * What {@link executorHomeOnDisk} found: no repository; the `external_directory` deny pattern of every executor home and the
249
+ * homes (as found and canonical) on a Windows drive under WSL, where letter case is not significant; or why a home of a
250
+ * repository found cannot be denied.
253
251
  */
254
- function gitCommonDirOnDisk(directory: string): { common?: string; problem?: string } {
255
- const checkout = nearestRepository(resolvePath(directory));
256
- if (checkout === undefined) return {};
257
- try {
258
- const pointers = gitPointers(checkout);
259
- return pointers === undefined ? {} : { common: pointers.common };
260
- } catch (error) {
261
- return { problem: errorText(error) };
252
+ type HomeOnDisk =
253
+ | { readonly kind: "none" }
254
+ | { readonly kind: "deny"; readonly deny: string[]; readonly folded: readonly string[] }
255
+ | { readonly kind: "problem"; readonly problem: string };
256
+
257
+ /**
258
+ * QA-62C-1, QA-62C-13, QA-62C-15 (#192): the executor homes in the git common directories of the repository holding
259
+ * `directory`, found on disk without running git ({@link resolveCommonDirOnDisk}: git's discovery order, a bare repository
260
+ * and the repository enclosing it included, hardened pointer reads, a Windows drive pointer mapped under WSL). Each home
261
+ * that does not exist yet gets its canonical parent and the literal name. `problem` when a repository is found but a home
262
+ * cannot be denied (a common directory cannot be read, or a home has no canonical form).
263
+ */
264
+ function executorHomeOnDisk(directory: string, realpath: Realpath, deps: CommonDirDeps): HomeOnDisk {
265
+ const found = resolveCommonDirOnDisk(resolvePath(directory), deps);
266
+ if (found.kind === "none") return found;
267
+ if (found.kind === "unresolved") return { kind: "problem", problem: `the git common directory could not be read (${found.reason})` };
268
+ const deny: string[] = [];
269
+ const folded: string[] = [];
270
+ for (const common of found.commons) {
271
+ const home = join(common, EXECUTOR_HOME_DIRNAME);
272
+ const canonical = executorDirectoryRoot(home, realpath, false);
273
+ if (canonical.root === undefined) {
274
+ return { kind: "problem", problem: `the executor home ${home} ${canonical.problem ?? "has no canonical long form"}` };
275
+ }
276
+ deny.push(join(canonical.root, "*"));
277
+ const root = found.drvfsRoot;
278
+ if (root !== undefined) folded.push(...[home, canonical.root].filter((path) => onDrvfs(path, root)));
262
279
  }
280
+ return { kind: "deny", deny: [...new Set(deny)], folded: [...new Set(folded)] };
263
281
  }
264
282
 
265
283
  /** Executor directories may not exist yet; only ENOENT permits using a canonical parent and the literal basename. */
@@ -291,11 +309,11 @@ function executorDirectoryRoot(path: string, realpath: Realpath, requireSame = t
291
309
 
292
310
  /** D6: reject overlap with non-slot worktrees, but existing executor worktrees must not block future slots. */
293
311
  function executorSlotsRootPattern(path: string, worktrees: readonly string[], realpath: Realpath): { pattern?: string; problem?: string } {
294
- const problem = slotsDirProblem(path);
312
+ const problem = slotsDirProblem(path, process.platform);
295
313
  if (problem !== undefined) return { problem };
296
314
  const canonical = executorDirectoryRoot(path, realpath);
297
315
  if (canonical.root === undefined) return { problem: canonical.problem };
298
- const after = slotsDirProblem(canonical.root);
316
+ const after = slotsDirProblem(canonical.root, process.platform);
299
317
  if (after !== undefined) return { problem: `canonical form ${canonical.root} ${after}` };
300
318
  for (const [index, worktree] of worktrees.entries()) {
301
319
  let root: string;
@@ -508,11 +526,15 @@ export interface RoleRegistrationOptions {
508
526
  /**
509
527
  * G-16: false when the plan executor cannot run on this platform (the caller asks `executorPlatformSupported`): the
510
528
  * executor is treated as disabled, so no executor-home lookup runs and no slots root is granted. The executor home in
511
- * the git common directory (found on disk by {@link gitCommonDirOnDisk}, no git) is still denied whenever that directory
529
+ * the git common directory (found on disk by {@link executorHomeOnDisk}, no git) is still denied whenever that directory
512
530
  * resolves, even before the home exists (QA-62C-1, QA-62C-14: a Windows host may run the executor on a repository
513
- * shared with WSL). Absent: true.
531
+ * shared with WSL). Off win32, a repository whose home cannot be denied fails closed (QA-62C-15). Absent: true.
514
532
  */
515
533
  executorPlatform?: boolean;
534
+ /** #192 seam (tests): the platform of the QA-62C-15 decisions and the on-disk lookup; default `process.platform`. */
535
+ platform?: NodeJS.Platform;
536
+ /** #192 seams (tests): the on-disk common-directory lookup's OS access ({@link resolveCommonDirOnDisk}). */
537
+ commonDir?: Omit<CommonDirDeps, "platform">;
516
538
  /** Clock in epoch ms for the approval expiry; default `Date.now`. */
517
539
  now?: () => number;
518
540
  }
@@ -581,6 +603,12 @@ export async function registerRoleAgents(
581
603
  const executorEnabled = opts.executorPlatform !== false
582
604
  && executorRouting.leases.mode === "enforce" && cfg.enforcement?.verify?.require !== "never";
583
605
  const executorProblems: Array<readonly [key: string, message: string]> = [];
606
+ const platform = opts.platform ?? process.platform;
607
+ const commonDirDeps: CommonDirDeps = { ...opts.commonDir, platform };
608
+ // QA-62C-15 (#192): off win32, why a repository's executor home cannot be denied; set, every allow is withheld below.
609
+ let withheld: string | undefined;
610
+ // #192: homes found on disk on a Windows drive under WSL; the allows that reach them in another letter case are withheld.
611
+ let folded: readonly string[] = [];
584
612
  // QA-62F-1, QA-62F-9: outside every work root, listed worktrees or configured roots can still cover the executor
585
613
  // home in the git common directory, even when listing failed. Resolve the home (one read-only, guarded rev-parse)
586
614
  // and deny it there; the slots-root grant below stays inside the work roots only.
@@ -609,12 +637,26 @@ export async function registerRoleAgents(
609
637
  && (directoryError.code === "ENOENT" || directoryError.code === "ENOTDIR");
610
638
  }
611
639
  }
612
- if (!notRepository) {
640
+ // QA-62C-15 (#192): off win32 git fails on repositories it cannot read (Linux git under WSL and a Git for Windows
641
+ // worktree whose `.git` names `gitdir: D:/…` reports none; an invalid gitfile or dubious ownership fails). On any
642
+ // failure look on disk: homes found there are denied (no slots grant: git cannot run the executor here), and a
643
+ // repository whose home cannot be denied fails closed; with no repository on disk git's answer stands (D7 silence,
644
+ // else one warning). win32 keeps git's answer.
645
+ const found: HomeOnDisk = platform === "win32" ? { kind: "none" } : executorHomeOnDisk(homeDirectory, realpath, commonDirDeps);
646
+ if (found.kind === "deny") {
647
+ externalDirectoryDenied = found.deny;
648
+ folded = found.folded;
649
+ if (!notRepository) {
650
+ executorProblems.push(["roles:executor-home", `${PREFIX}the executor home could not be resolved (${problem}); it is denied as found on disk and role agents get no slots external_directory rule`]);
651
+ }
652
+ } else if (found.kind === "problem") {
653
+ withheld = found.problem;
654
+ } else if (!notRepository) {
613
655
  executorProblems.push(["roles:executor-home", `${PREFIX}the executor home could not be resolved (${problem}); the executor home is not denied and role agents get no slots external_directory rule`]);
614
656
  }
615
657
  }
616
658
  // An unresolved home cannot be protected by a final deny: do not grant the slots root either (D6).
617
- if (!outside && home !== undefined && hasLocalActions && (slotsDir !== null || process.platform === "win32")) {
659
+ if (!outside && home !== undefined && hasLocalActions) {
618
660
  // Match create.ts's location toplevel, not Git's first (main) worktree on another drive.
619
661
  let toplevel: string | undefined;
620
662
  try {
@@ -626,12 +668,20 @@ export async function registerRoleAgents(
626
668
  } catch { /* Unresolved entries cannot select a drive; the slots overlap check still fails closed. */ }
627
669
  }
628
670
  } catch { /* A missing canonical location cannot select a default drive. */ }
629
- const drive = /^([A-Za-z]):[\\/]/.exec(toplevel ?? "");
630
- const root = slotsDir ?? (drive === null ? undefined : `${drive[1]}:\\.omr-slots`);
671
+ // #192: the same default root as the pool and create.ts (win32: the toplevel's drive; POSIX: the real home).
672
+ let root: string | undefined = slotsDir ?? undefined;
673
+ let rootProblem = "the repository toplevel is not on a drive-letter path";
674
+ if (slotsDir === null) {
675
+ try {
676
+ root = defaultSlotsRoot({ platform: process.platform, ...(toplevel === undefined ? {} : { toplevel }) });
677
+ } catch (error) {
678
+ if (process.platform !== "win32") rootProblem = errorText(error);
679
+ }
680
+ }
631
681
  const slots = worktreeListingProblem !== undefined
632
682
  ? { problem: `the worktree listing failed (${worktreeListingProblem})` }
633
683
  : root === undefined
634
- ? { problem: "the repository toplevel is not on a drive-letter path" }
684
+ ? { problem: rootProblem }
635
685
  : executorSlotsRootPattern(root, worktrees, realpath);
636
686
  if (slots.pattern === undefined) {
637
687
  executorProblems.push(["roles:executor-slots", `${PREFIX}executor slots root ${root ?? "(default)"} ${slots.problem ?? "is not usable"}; not granted`]);
@@ -645,17 +695,31 @@ export async function registerRoleAgents(
645
695
  // Deny the executor home in the common directory, found on disk without running git, whether or not it exists yet
646
696
  // (QA-62C-14: a deny on a missing path is harmless, and the Windows host may create it later); never grant the slots
647
697
  // root here. A home that does not exist yet gets its canonical parent and the literal name, like the win32 branch.
648
- const found = gitCommonDirOnDisk(worktrees[0] ?? opts.directory);
649
- if (found.problem !== undefined) {
650
- executorProblems.push(["roles:executor-home", `${PREFIX}the git common directory could not be read (${found.problem}); the executor home is not denied`]);
651
- } else if (found.common !== undefined) {
652
- const home = join(found.common, EXECUTOR_HOME_DIRNAME);
653
- const canonical = executorDirectoryRoot(home, opts.realpath ?? nativeRealpath, false);
654
- if (canonical.root !== undefined) {
655
- externalDirectoryDenied = [join(canonical.root, "*")];
656
- } else {
657
- executorProblems.push(["roles:executor-home", `${PREFIX}the executor home ${home} ${canonical.problem ?? "has no canonical long form"}; the executor home is not denied`]);
658
- }
698
+ // QA-62C-15 (#192): found in git's discovery order (a bare repository too, a drive pointer mapped under WSL); off
699
+ // win32 a repository whose home cannot be denied fails closed.
700
+ const found = executorHomeOnDisk(worktrees[0] ?? opts.directory, opts.realpath ?? nativeRealpath, commonDirDeps);
701
+ if (found.kind === "deny") {
702
+ externalDirectoryDenied = found.deny;
703
+ folded = found.folded;
704
+ } else if (found.kind === "problem") {
705
+ if (platform === "win32") executorProblems.push(["roles:executor-home", `${PREFIX}${found.problem}; the executor home is not denied`]);
706
+ else withheld = found.problem;
707
+ }
708
+ }
709
+ // QA-62C-15 (#192): fail closed. Any allow (worktree, work root, repository parent or approval) could cover the home
710
+ // that cannot be denied: role agents get no external_directory rule at all, one warning, and no slots grant (none was
711
+ // added: the home was not resolved).
712
+ if (withheld !== undefined) {
713
+ externalDirectory = [];
714
+ executorProblems.push(["roles:executor-home", `${PREFIX}${withheld}; the executor home is not denied, so role agents get no external_directory rule (fail closed)`]);
715
+ } else if (folded.length > 0) {
716
+ // #192: on a Windows drive under WSL names match in any letter case, but the host's deny matches case-sensitively off
717
+ // win32: `/mnt/d/x/.GIT/omr-executor/…` passes an allow on `/mnt/d/x/*` and misses the deny. Withhold every allow
718
+ // that reaches a home once case is ignored, with one warning.
719
+ const reaching = externalDirectory.filter((pattern) => folded.some((home) => reachesFolded(pattern, home)));
720
+ if (reaching.length > 0) {
721
+ externalDirectory = externalDirectory.filter((pattern) => !reaching.includes(pattern));
722
+ executorProblems.push(["roles:executor-home", `${PREFIX}the executor home ${folded.join(", ")} is on a Windows drive, where letter case is not significant, but the deny matches case-sensitively; role agents do not get the external_directory rules that reach it (${reaching.join(", ")})`]);
659
723
  }
660
724
  }
661
725
  built = new Map();
@@ -0,0 +1,253 @@
1
+ /**
2
+ * #108 slice 2: `router_run({ summary: "failures" })` (OpenCode v2 roles mode, where `router_run` exists). Opt-in, for a vitest
3
+ * npm script only: the router appends `--reporter=json --outputFile=<OS temp>/omr-run-<uuid>.json` to the script's arguments,
4
+ * reads that report after the run, deletes it, and answers with the counts and the failing tests grouped by file (the first
5
+ * error block of each) within {@link RUN_SUMMARY_MAX_BYTES}. Without `summary` nothing changes, and the plan executor's checks
6
+ * (which share `planRun`) never set it.
7
+ */
8
+ import { randomUUID } from "node:crypto";
9
+ import { isAbsolute, join, relative, sep } from "node:path";
10
+ import { reportPathAllowed } from "../verify/runner";
11
+ import { stripUrlUserinfo } from "./git-tools";
12
+
13
+ /** Bound of a summarized `router_run` answer (status line included), in UTF-8 bytes. */
14
+ export const RUN_SUMMARY_MAX_BYTES = 4096;
15
+ /** The report files of `summary: "failures"`: `<OS temp>/omr-run-<uuid>.json`; nothing else is read or deleted. */
16
+ export const RUN_REPORT_NAME_RE = /^omr-run-[0-9a-f-]{36}\.json$/;
17
+ /** A larger report is not read (its size is checked first; the summary then falls back to the output's last lines). */
18
+ export const RUN_REPORT_MAX_BYTES = 8 * 1024 * 1024;
19
+ /** A caller argument, a fixed argument or a script-body token that sets vitest's reporter or output file. */
20
+ export const REPORTER_OPTION_RE = /^--(?:reporters?|outputFile|output-file)(?:[.=]|$)/;
21
+ /** Lines of a failure's first error block, and characters per line. */
22
+ const ERROR_BLOCK_LINES = 4;
23
+ const LINE_MAX_CHARS = 200;
24
+ /** Characters of a failing test's name line. */
25
+ const NAME_MAX_CHARS = 300;
26
+ /** Room kept for the omitted-count line. */
27
+ const OMITTED_RESERVE_BYTES = 260;
28
+
29
+ /** A fresh report path in `tmp`, the OS temp directory the caller read once (`os.tmpdir()`) and checks it against. */
30
+ export function newRunReportPath(tmp: string): string {
31
+ return join(tmp, `omr-run-${randomUUID()}.json`);
32
+ }
33
+
34
+ /**
35
+ * The verify runner's report-path guard with this tool's report names: only a file the router named, directly in `tmp` (absolute),
36
+ * may be read or deleted. A relative `tmp` (a relative TEMP/TMPDIR) admits nothing.
37
+ */
38
+ export function runReportPathAllowed(path: string, tmp: string): boolean {
39
+ return reportPathAllowed(path, tmp, process.platform, RUN_REPORT_NAME_RE);
40
+ }
41
+
42
+ /**
43
+ * Why a package.json script body cannot be summarized, or undefined when it can. It must be one `vitest` command (its first word
44
+ * `vitest`) whose appended arguments reach vitest as options: nothing the script shell would chain, pipe, redirect or substitute
45
+ * (`;`, `&`, `|`, `<`, `>`, backquote, `$(`, a line break), no `#` (a comment would swallow them), no trailing backslash, no `--`
46
+ * argument (vitest would read them as file filters), no quote, backslash, `$`, `%` or `^` inside an option name (the shell could
47
+ * make another option of it), and no `--reporter`/`--outputFile` of its own.
48
+ */
49
+ export function vitestScriptRefusal(body: string): string | undefined {
50
+ const text = body.trim();
51
+ if (!/^vitest(?:\s|$)/.test(text)) return "does not start with vitest";
52
+ if (/[;&|<>`\r\n]|\$\(/.test(text)) return "is not a single vitest command (it chains, pipes, redirects or substitutes)";
53
+ if (text.includes("#")) return "has a # (the script shell may read the rest as a comment)";
54
+ if (text.endsWith("\\")) return "ends with a backslash";
55
+ const tokens = text.split(/\s+/);
56
+ if (tokens.includes("--")) return "has a -- argument (vitest would read the appended options as file filters)";
57
+ for (const token of tokens) {
58
+ const bare = token.replace(/^["']+/, "");
59
+ if (REPORTER_OPTION_RE.test(bare)) return "already sets --reporter or --outputFile";
60
+ if (bare.startsWith("-") && /["'\\$%^]/.test(bare.split("=")[0]!)) return "has a quote or escape inside an option name";
61
+ }
62
+ return undefined;
63
+ }
64
+
65
+ /** ANSI CSI escape sequences (colours, cursor moves). */
66
+ const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
67
+ /** Control characters (line breaks and tabs included) and the Unicode line and paragraph separators. */
68
+ const CONTROL_RE = /[\p{Cc}\u2028\u2029]+/gu;
69
+
70
+ /**
71
+ * Report text shown on one line (a test name, an ancestor title, a file path): ANSI escapes removed, control characters and
72
+ * line breaks flattened to one space, credentials redacted (as the raw output is). A name cannot start a line of its own.
73
+ */
74
+ export function oneLine(text: string): string {
75
+ return stripUrlUserinfo(text.replace(ANSI_RE, "").replace(CONTROL_RE, " ")).trim();
76
+ }
77
+
78
+ /** One failing test (or a file-level error) and the first block of its error message. */
79
+ export interface VitestFailure { readonly name: string; readonly error?: string }
80
+ /** The failures of one test file, in report order. */
81
+ export interface VitestFileFailures { readonly file: string; readonly failures: readonly VitestFailure[] }
82
+ /** What a summary needs from a vitest (jest-compatible) JSON report. Counts the report does not carry are undefined. */
83
+ export interface VitestReportSummary {
84
+ readonly total?: number;
85
+ readonly passed?: number;
86
+ readonly failed?: number;
87
+ readonly skipped?: number;
88
+ readonly files?: number;
89
+ readonly failedFiles?: number;
90
+ readonly groups: readonly VitestFileFailures[];
91
+ }
92
+
93
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
94
+ const count = (value: unknown): number | undefined => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
95
+
96
+ /** A test file's name as shown: relative to the work root with `/` separators when inside it, else as reported. */
97
+ function shownFile(cwd: string, file: string): string {
98
+ const below = relative(cwd, file);
99
+ return below !== "" && !below.startsWith("..") && !isAbsolute(below) ? below.split(sep).join("/") : file;
100
+ }
101
+
102
+ /** At most `max` characters of one line, marked when cut. */
103
+ function clip(line: string, max: number): string {
104
+ return line.length <= max ? line : `${line.slice(0, max - 1)}…`;
105
+ }
106
+
107
+ /**
108
+ * The first block of an error message: ANSI codes removed, credentials redacted, leading blank lines skipped, then lines up
109
+ * to the first blank line or stack frame (`at …`, `❯ …`), at most {@link ERROR_BLOCK_LINES} lines of {@link LINE_MAX_CHARS},
110
+ * other control characters in a line flattened to a space (the renderer indents every line it shows).
111
+ */
112
+ export function firstErrorBlock(message: string): string | undefined {
113
+ const lines = stripUrlUserinfo(message.replace(ANSI_RE, "")).split(/\r\n|[\n\r\u2028\u2029]/).map(line => line.replace(CONTROL_RE, " "));
114
+ const start = lines.findIndex(line => line.trim() !== "");
115
+ if (start === -1) return undefined;
116
+ const block: string[] = [];
117
+ for (const line of lines.slice(start)) {
118
+ if (line.trim() === "" || /^\s*(?:at\s|❯\s)/.test(line) || block.length === ERROR_BLOCK_LINES) break;
119
+ block.push(clip(line.trimEnd(), LINE_MAX_CHARS));
120
+ }
121
+ return block.length === 0 ? undefined : block.join("\n");
122
+ }
123
+
124
+ /** Parse a vitest `--reporter=json` report; undefined when it is not one (not JSON, no `testResults` array). */
125
+ export function parseVitestReport(text: string, cwd: string): VitestReportSummary | undefined {
126
+ let report: unknown;
127
+ try { report = JSON.parse(text); } catch { return undefined; }
128
+ if (!isRecord(report) || !Array.isArray(report.testResults)) return undefined;
129
+ const groups: VitestFileFailures[] = [];
130
+ for (const suite of report.testResults.filter(isRecord)) {
131
+ if (typeof suite.name !== "string") continue;
132
+ const results = Array.isArray(suite.assertionResults) ? suite.assertionResults.filter(isRecord) : [];
133
+ const failures: VitestFailure[] = [];
134
+ const message = typeof suite.message === "string" ? suite.message : "";
135
+ const fileError = message.trim() === "" ? undefined : firstErrorBlock(message);
136
+ for (const result of results.filter(entry => entry.status === "failed")) {
137
+ const titles = Array.isArray(result.ancestorTitles) ? result.ancestorTitles.map(String) : [];
138
+ const name = [...titles, String(result.title ?? result.fullName ?? "(unnamed test)")].map(oneLine).join(" > ");
139
+ const messages = Array.isArray(result.failureMessages) ? result.failureMessages : [];
140
+ const error = typeof messages[0] === "string" ? firstErrorBlock(messages[0]) : undefined;
141
+ failures.push({ name, ...(error === undefined ? {} : { error }) });
142
+ }
143
+ if (fileError !== undefined || (suite.status === "failed" && failures.length === 0)) {
144
+ failures.unshift({ name: "(file error)", ...(fileError === undefined ? {} : { error: fileError }) });
145
+ }
146
+ if (failures.length > 0) groups.push({ file: oneLine(shownFile(cwd, suite.name)), failures });
147
+ }
148
+ const pending = count(report.numPendingTests);
149
+ const todo = count(report.numTodoTests);
150
+ const total = count(report.numTotalTests);
151
+ const passed = count(report.numPassedTests);
152
+ const failed = count(report.numFailedTests);
153
+ const skipped = pending === undefined && todo === undefined ? undefined : (pending ?? 0) + (todo ?? 0);
154
+ const files = count(report.numTotalTestSuites);
155
+ const failedFiles = count(report.numFailedTestSuites);
156
+ return {
157
+ ...(total === undefined ? {} : { total }), ...(passed === undefined ? {} : { passed }), ...(failed === undefined ? {} : { failed }),
158
+ ...(skipped === undefined ? {} : { skipped }), ...(files === undefined ? {} : { files }), ...(failedFiles === undefined ? {} : { failedFiles }),
159
+ groups,
160
+ };
161
+ }
162
+
163
+ const bytes = (text: string) => Buffer.byteLength(text);
164
+ const known = (value: number | undefined) => value === undefined ? "?" : String(value);
165
+
166
+ /** The last lines of `output` within `max` bytes (whole lines only; the first, possibly cut, line is dropped). */
167
+ function outputTail(output: string, max: number): string {
168
+ if (max <= 0 || output.trim() === "") return "";
169
+ if (bytes(output) <= max) return output.endsWith("\n") ? output : `${output}\n`;
170
+ const raw = Buffer.from(output);
171
+ const tail = raw.subarray(raw.length - max).toString("utf8");
172
+ const newline = tail.indexOf("\n");
173
+ const whole = newline === -1 ? "" : tail.slice(newline + 1);
174
+ return whole === "" || whole.endsWith("\n") ? whole : `${whole}\n`;
175
+ }
176
+
177
+ /** Cut `text` to `max` bytes at a line end (a last safety bound; the renderers below already stay within it). */
178
+ function fitBytes(text: string, max: number): string {
179
+ if (bytes(text) <= max) return text;
180
+ const kept = Buffer.from(text).subarray(0, max).toString("utf8").replace(/\uFFFD+$/, "");
181
+ const newline = kept.lastIndexOf("\n");
182
+ return newline > 0 ? kept.slice(0, newline + 1) : kept;
183
+ }
184
+
185
+ /**
186
+ * The answer of a summarized run whose report could be read: `status` (the usual status line), the counts, then the failures
187
+ * grouped by file. The cut rule, at most `max` bytes in all:
188
+ * 1. Failure names first, in report order (a file's `FAIL <file>` line with its first shown failure); the first one that does
189
+ * not fit ends the list.
190
+ * 2. Then the first error block of each listed failure, in order, as long as it fits (one that does not is skipped).
191
+ * 3. A last line gives the exact number of failures (and files) not listed and of error blocks left out.
192
+ * A run that exited non-zero although the report lists no failure gets the output's last lines instead.
193
+ */
194
+ export function renderFailureSummary(status: string, report: VitestReportSummary, exitCode: number | null, output: string,
195
+ max = RUN_SUMMARY_MAX_BYTES): string {
196
+ const head = `${status}\n[router_run] vitest: ${known(report.failed)} failed, ${known(report.passed)} passed, ${known(report.skipped)} skipped `
197
+ + `of ${known(report.total)} tests; ${known(report.failedFiles)} of ${known(report.files)} test files failed\n`;
198
+ if (report.groups.length === 0) {
199
+ if (exitCode === 0) return fitBytes(head, max);
200
+ const label = `[router_run] the run ended with exit code ${exitCode ?? "none"} but its report lists no failing test; the last lines of its output:\n`;
201
+ return fitBytes(`${head}${label}${outputTail(output, max - bytes(head) - bytes(label))}`, max);
202
+ }
203
+ type Item = { group: number; name: string; error: string | undefined };
204
+ const items: Item[] = report.groups.flatMap((group, index) => group.failures.map(failure => ({
205
+ group: index, name: ` × ${clip(failure.name, NAME_MAX_CHARS)}\n`, error: failure.error === undefined ? undefined : `${failure.error.split("\n").map(line => ` ${line}`).join("\n")}\n`,
206
+ })));
207
+ const fileLine = (group: number) => `FAIL ${clip(report.groups[group]!.file, NAME_MAX_CHARS)}\n`;
208
+ const room = max - bytes(head) - OMITTED_RESERVE_BYTES;
209
+ // 1. Names.
210
+ let used = 0;
211
+ let listed = 0;
212
+ for (const item of items) {
213
+ const first = listed === 0 || items[listed - 1]!.group !== item.group;
214
+ const cost = bytes(item.name) + (first ? bytes(fileLine(item.group)) : 0);
215
+ if (used + cost > room) break;
216
+ used += cost;
217
+ listed++;
218
+ }
219
+ // 2. Error blocks, in order, while they fit.
220
+ const withError = new Set<number>();
221
+ let missingErrors = 0;
222
+ for (let index = 0; index < listed; index++) {
223
+ const error = items[index]!.error;
224
+ if (error === undefined) continue;
225
+ if (used + bytes(error) <= room) {
226
+ used += bytes(error);
227
+ withError.add(index);
228
+ } else missingErrors++;
229
+ }
230
+ let body = "";
231
+ for (let index = 0; index < listed; index++) {
232
+ const item = items[index]!;
233
+ if (index === 0 || items[index - 1]!.group !== item.group) body += fileLine(item.group);
234
+ body += item.name;
235
+ if (withError.has(index)) body += item.error;
236
+ }
237
+ // 3. What was left out, exactly.
238
+ const rest = items.slice(listed);
239
+ const restFiles = new Set(rest.map(item => item.group)).size;
240
+ const parts = [
241
+ rest.length > 0 ? `${rest.length} more ${rest.length === 1 ? "failure" : "failures"} in ${restFiles} ${restFiles === 1 ? "file" : "files"}` : "",
242
+ missingErrors > 0 ? `the error ${missingErrors === 1 ? "block" : "blocks"} of ${missingErrors} listed ${missingErrors === 1 ? "failure" : "failures"}` : "",
243
+ ].filter(Boolean);
244
+ const omitted = parts.length === 0 ? ""
245
+ : `[router_run] not shown, to keep this summary within ${max} bytes: ${parts.join("; ")}. Run without summary for the full output.\n`;
246
+ return fitBytes(`${head}${body}${omitted}`, max);
247
+ }
248
+
249
+ /** The answer of a summarized run without a usable report: `status`, why, and the output's last lines, within `max` bytes. */
250
+ export function renderSummaryUnavailable(status: string, reason: string, output: string, max = RUN_SUMMARY_MAX_BYTES): string {
251
+ const head = `${status}\n[router_run] vitest summary unavailable: ${reason}; the last lines of the output:\n`;
252
+ return fitBytes(`${head}${outputTail(output, max - bytes(head))}`, max);
253
+ }