@robhowley/pi-structured-return 1.2.1 → 1.3.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/README.md CHANGED
@@ -15,11 +15,16 @@ Linters: 1 unused variable warning in a single file.
15
15
 
16
16
  | Parser | Raw (tokens) | Structured (tokens) | Reduction | Notes |
17
17
  |---|---|---|---|---|
18
+ | `junit-xml` (maven) | 1063 | 86 | **92%** | build lifecycle noise with surefire stack traces per failure |
18
19
  | `junit-xml` (go) | 400 | 58 | **86%** | verbose output with full stack trace per failure |
20
+ | `junit-xml` (dotnet) | 487 | 107 | **78%** | build header and VSTest output with per-failure stack traces |
19
21
  | `vitest-json` | 348 | 75 | **78%** | source diff with inline arrows and ANSI color codes per failure |
20
22
  | `junit-xml` (pytest) | 289 | 71 | **75%** | verbose output with source snippets and summary footer |
21
23
  | `rspec-json` | 212 | 55 | **74%** | default output with backtrace |
24
+ | `cargo-test` | 285 | 68 | **76%** | cargo progress + test binary output with panic traces per failure |
22
25
  | `junit-xml` (gradle) | 263 | 81 | **69%** | gradle console output with build lifecycle noise |
26
+ | `junit-xml` (jest) | 309 | 99 | **68%** | source annotations with deep jest-circus stack traces per failure |
27
+ | `cargo-build` | 225 | 77 | **66%** | rustc error annotations with code spans and help text per error |
23
28
  | `minitest-text` | 168 | 59 | **65%** | default output with backtrace |
24
29
  | `ruff-json` | 107 | 52 | **51%** | source context + help text per error |
25
30
  | `eslint-json` | 64 | 59 | **8%** | already compact formatter |
@@ -31,6 +36,8 @@ Tokens counted with `cl100k_base` (tiktoken). Linter output is more compact than
31
36
  - `vitest-json`
32
37
  - `rspec-json`
33
38
  - `minitest-text` (parses default minitest output — no flags or reporters needed)
39
+ - `cargo-build` (`cargo build --message-format=json` — errors with file, line, error code, and primary span label; warnings filtered out)
40
+ - `cargo-test` (`cargo test` — assertion left/right values, panic messages, and file:line per failure; detects compilation failures and directs to `cargo build --message-format=json`)
34
41
  - `ruff-json` (`ruff check` only — `ruff format` has no json support)
35
42
  - `eslint-json`
36
43
 
@@ -6,6 +6,8 @@ import vitestJson from "../parsers/vitest-json";
6
6
  import rspecJson from "../parsers/rspec-json";
7
7
  import minitestText from "../parsers/minitest-text";
8
8
  import junitXml from "../parsers/junit-xml";
9
+ import cargoBuild from "../parsers/cargo-build";
10
+ import cargoTest from "../parsers/cargo-test";
9
11
  import tailFallback from "../parsers/tail-fallback";
10
12
 
11
13
  const builtIns: Record<string, ParserModule> = {
@@ -15,6 +17,8 @@ const builtIns: Record<string, ParserModule> = {
15
17
  "rspec-json": rspecJson,
16
18
  "minitest-text": minitestText,
17
19
  "junit-xml": junitXml,
20
+ "cargo-build": cargoBuild,
21
+ "cargo-test": cargoTest,
18
22
  "tail-fallback": tailFallback,
19
23
  };
20
24
 
@@ -46,6 +50,17 @@ const AUTO_DETECT: Array<{ parserId: string; detect: (argv: string[]) => boolean
46
50
  detect: (argv) =>
47
51
  argv.some((a) => a.startsWith("--junitxml") || a.startsWith("--junit-xml") || a === "--format=junit"),
48
52
  },
53
+ {
54
+ parserId: "cargo-build",
55
+ detect: (argv) =>
56
+ argv.includes("cargo") &&
57
+ argv.includes("build") &&
58
+ argv.some((a) => a.startsWith("--message-format=json") || a === "json"),
59
+ },
60
+ {
61
+ parserId: "cargo-test",
62
+ detect: (argv) => argv.includes("cargo") && argv.includes("test"),
63
+ },
49
64
  ];
50
65
 
51
66
  export function listParsers(): { id: string; autoDetect: boolean }[] {
@@ -108,7 +108,9 @@ export function formatResult(result: ParsedResult): string {
108
108
  for (const f of result.failures ?? []) {
109
109
  const location = [f.file, f.line].filter(Boolean).join(":");
110
110
  const rule = f.rule ? ` [${f.rule}]` : "";
111
- lines.push(` ${location} ${f.message ?? ""}${rule}`);
111
+ const msgLines = (f.message ?? "").split("\n");
112
+ lines.push(` ${location} ${msgLines[0]}${rule}`);
113
+ for (const extra of msgLines.slice(1)) lines.push(` ${extra}`);
112
114
  }
113
115
  return lines.join("\n");
114
116
  }
@@ -0,0 +1,170 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { describe, it, expect } from "vitest";
5
+ import parser from "./cargo-build";
6
+ import type { RunContext } from "../types";
7
+
8
+ function makeCtx(stdoutContent: string, cwd = "/project"): RunContext {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cargo-build-test-"));
10
+ const stdoutPath = path.join(dir, "stdout");
11
+ const stderrPath = path.join(dir, "stderr");
12
+ const logPath = path.join(dir, "combined.log");
13
+ fs.writeFileSync(stdoutPath, stdoutContent);
14
+ fs.writeFileSync(stderrPath, "");
15
+ fs.writeFileSync(logPath, stdoutContent);
16
+ return {
17
+ command: "cargo build --message-format=json",
18
+ argv: ["cargo", "build", "--message-format=json"],
19
+ cwd,
20
+ artifactPaths: [],
21
+ stdoutPath,
22
+ stderrPath,
23
+ logPath,
24
+ };
25
+ }
26
+
27
+ /** Build a minimal compiler-message NDJSON line */
28
+ function compilerMessage(opts: {
29
+ level: string;
30
+ message: string;
31
+ code?: string;
32
+ file?: string;
33
+ line?: number;
34
+ label?: string;
35
+ }): string {
36
+ const span = opts.file
37
+ ? [
38
+ {
39
+ file_name: opts.file,
40
+ line_start: opts.line ?? 1,
41
+ is_primary: true,
42
+ label: opts.label ?? null,
43
+ },
44
+ ]
45
+ : [];
46
+ return JSON.stringify({
47
+ reason: "compiler-message",
48
+ message: {
49
+ message: opts.message,
50
+ level: opts.level,
51
+ code: opts.code ? { code: opts.code } : null,
52
+ spans: span,
53
+ },
54
+ });
55
+ }
56
+
57
+ const BUILD_FINISHED_OK = JSON.stringify({ reason: "build-finished", success: true });
58
+ const BUILD_FINISHED_ERR = JSON.stringify({ reason: "build-finished", success: false });
59
+
60
+ describe("cargo-build parser", () => {
61
+ it("two errors → status fail, correct count and details", async () => {
62
+ const stdout = [
63
+ compilerMessage({
64
+ level: "error",
65
+ message: "mismatched types",
66
+ code: "E0308",
67
+ file: "src/main.rs",
68
+ line: 6,
69
+ label: "expected `i32`, found `&str`",
70
+ }),
71
+ compilerMessage({
72
+ level: "error",
73
+ message: "cannot find value `missing_var` in this scope",
74
+ code: "E0425",
75
+ file: "src/main.rs",
76
+ line: 7,
77
+ label: "not found in this scope",
78
+ }),
79
+ BUILD_FINISHED_ERR,
80
+ ].join("\n");
81
+
82
+ const result = await parser.parse(makeCtx(stdout));
83
+ expect(result.status).toBe("fail");
84
+ expect(result.summary).toBe("2 errors");
85
+ expect(result.failures).toHaveLength(2);
86
+
87
+ const first = result.failures![0];
88
+ expect(first.file).toBe("src/main.rs");
89
+ expect(first.line).toBe(6);
90
+ expect(first.rule).toBe("E0308");
91
+ expect(first.message).toBe("mismatched types\nexpected `i32`, found `&str`");
92
+
93
+ const second = result.failures![1];
94
+ expect(second.file).toBe("src/main.rs");
95
+ expect(second.line).toBe(7);
96
+ expect(second.rule).toBe("E0425");
97
+ });
98
+
99
+ it("single error, no code → message only, no rule", async () => {
100
+ const stdout = [
101
+ compilerMessage({ level: "error", message: "something went wrong", file: "src/lib.rs", line: 3 }),
102
+ BUILD_FINISHED_ERR,
103
+ ].join("\n");
104
+
105
+ const result = await parser.parse(makeCtx(stdout));
106
+ expect(result.status).toBe("fail");
107
+ expect(result.summary).toBe("1 error");
108
+ expect(result.failures![0].rule).toBeUndefined();
109
+ expect(result.failures![0].message).toBe("something went wrong");
110
+ });
111
+
112
+ it("warnings are ignored, only errors count", async () => {
113
+ const stdout = [
114
+ compilerMessage({ level: "warning", message: "unused variable", file: "src/lib.rs", line: 1 }),
115
+ BUILD_FINISHED_OK,
116
+ ].join("\n");
117
+
118
+ const result = await parser.parse(makeCtx(stdout));
119
+ expect(result.status).toBe("pass");
120
+ expect(result.summary).toBe("build succeeded");
121
+ expect(result.failures).toHaveLength(0);
122
+ });
123
+
124
+ it("no errors → build succeeded", async () => {
125
+ const stdout = [BUILD_FINISHED_OK].join("\n");
126
+ const result = await parser.parse(makeCtx(stdout));
127
+ expect(result.status).toBe("pass");
128
+ expect(result.summary).toBe("build succeeded");
129
+ });
130
+
131
+ it("non-JSON lines mixed in (e.g. cargo human-readable stderr leaked) are skipped", async () => {
132
+ const stdout = [
133
+ " Compiling myapp v0.1.0",
134
+ compilerMessage({ level: "error", message: "broken", file: "src/lib.rs", line: 5 }),
135
+ "error: could not compile",
136
+ BUILD_FINISHED_ERR,
137
+ ].join("\n");
138
+
139
+ const result = await parser.parse(makeCtx(stdout));
140
+ expect(result.status).toBe("fail");
141
+ expect(result.failures).toHaveLength(1);
142
+ });
143
+
144
+ it("file path made relative to cwd", async () => {
145
+ const cwd = "/project";
146
+ const stdout = [
147
+ compilerMessage({ level: "error", message: "oops", file: "src/lib.rs", line: 1 }),
148
+ BUILD_FINISHED_ERR,
149
+ ].join("\n");
150
+
151
+ const result = await parser.parse(makeCtx(stdout, cwd));
152
+ expect(result.failures![0].file).toBe("src/lib.rs");
153
+ expect(result.failures![0].file).not.toContain("/project");
154
+ });
155
+
156
+ it("failure-note level messages are skipped", async () => {
157
+ const stdout = [
158
+ compilerMessage({
159
+ level: "failure-note",
160
+ message: "Some errors have detailed explanations: E0308.",
161
+ }),
162
+ compilerMessage({ level: "error", message: "mismatched types", code: "E0308", file: "src/main.rs", line: 2 }),
163
+ BUILD_FINISHED_ERR,
164
+ ].join("\n");
165
+
166
+ const result = await parser.parse(makeCtx(stdout));
167
+ expect(result.failures).toHaveLength(1);
168
+ expect(result.failures![0].rule).toBe("E0308");
169
+ });
170
+ });
@@ -0,0 +1,74 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import type { ParserModule, ParsedFailure } from "../types";
4
+
5
+ interface CargoSpan {
6
+ file_name: string;
7
+ line_start: number;
8
+ is_primary: boolean;
9
+ label: string | null;
10
+ }
11
+
12
+ interface CargoCode {
13
+ code: string;
14
+ }
15
+
16
+ interface CargoMessage {
17
+ message: string;
18
+ level: string;
19
+ code: CargoCode | null;
20
+ spans: CargoSpan[];
21
+ }
22
+
23
+ interface CargoCompilerMessage {
24
+ reason: "compiler-message";
25
+ message: CargoMessage;
26
+ }
27
+
28
+ const parser: ParserModule = {
29
+ id: "cargo-build",
30
+ async parse(ctx) {
31
+ // --message-format=json writes NDJSON to stdout; one JSON object per line
32
+ const stdout = fs.readFileSync(ctx.stdoutPath, "utf8");
33
+ const failures: ParsedFailure[] = [];
34
+
35
+ for (const line of stdout.split("\n")) {
36
+ if (!line.trim().startsWith("{")) continue;
37
+ let obj: Partial<CargoCompilerMessage>;
38
+ try {
39
+ obj = JSON.parse(line);
40
+ } catch {
41
+ continue;
42
+ }
43
+
44
+ if (obj.reason !== "compiler-message") continue;
45
+ const msg = obj.message;
46
+ if (!msg || msg.level !== "error") continue;
47
+
48
+ const primarySpan = msg.spans?.find((s) => s.is_primary);
49
+ const file = primarySpan ? path.relative(ctx.cwd, path.resolve(ctx.cwd, primarySpan.file_name)) : undefined;
50
+ const lineNum = primarySpan?.line_start;
51
+ const label = primarySpan?.label ?? undefined;
52
+ const code = msg.code?.code;
53
+
54
+ failures.push({
55
+ id: [file, lineNum, code].filter(Boolean).join(":"),
56
+ file,
57
+ line: lineNum,
58
+ // Surface the primary span label (e.g. "expected `i32`, found `&str`") as a second line
59
+ message: label ? `${msg.message}\n${label}` : msg.message,
60
+ rule: code,
61
+ });
62
+ }
63
+
64
+ return {
65
+ tool: "cargo",
66
+ status: failures.length > 0 ? "fail" : "pass",
67
+ summary: failures.length > 0 ? `${failures.length} error${failures.length === 1 ? "" : "s"}` : "build succeeded",
68
+ failures,
69
+ logPath: ctx.logPath,
70
+ };
71
+ },
72
+ };
73
+
74
+ export default parser;
@@ -0,0 +1,191 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { describe, it, expect } from "vitest";
5
+ import parser from "./cargo-test";
6
+ import type { RunContext } from "../types";
7
+
8
+ function makeCtx(logContent: string, cwd = "/project"): RunContext {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cargo-test-test-"));
10
+ const stdoutPath = path.join(dir, "stdout");
11
+ const stderrPath = path.join(dir, "stderr");
12
+ const logPath = path.join(dir, "combined.log");
13
+ fs.writeFileSync(stdoutPath, logContent);
14
+ fs.writeFileSync(stderrPath, "");
15
+ fs.writeFileSync(logPath, logContent);
16
+ return {
17
+ command: "cargo test",
18
+ argv: ["cargo", "test"],
19
+ cwd,
20
+ artifactPaths: [],
21
+ stdoutPath,
22
+ stderrPath,
23
+ logPath,
24
+ };
25
+ }
26
+
27
+ // Realistic cargo test output with Rust 1.73+ panic format
28
+ const REAL_OUTPUT_NEW_FORMAT = ` Compiling math v0.1.0 (/project)
29
+ Finished \`test\` profile [unoptimized + debuginfo] target(s) in 1.23s
30
+ Running unittests src/lib.rs (target/debug/deps/math-abc123)
31
+
32
+ running 3 tests
33
+ test tests::adds_two_numbers_correctly ... ok
34
+ test tests::multiplies_two_numbers_correctly ... FAILED
35
+ test tests::does_not_panic ... FAILED
36
+
37
+ failures:
38
+
39
+ ---- tests::multiplies_two_numbers_correctly stdout ----
40
+
41
+ thread 'tests::multiplies_two_numbers_correctly' (12345) panicked at src/lib.rs:20:9:
42
+ assertion \`left == right\` failed
43
+ left: 12
44
+ right: 99
45
+
46
+ ---- tests::does_not_panic stdout ----
47
+
48
+ thread 'tests::does_not_panic' (12346) panicked at src/lib.rs:26:18:
49
+ index out of bounds: the len is 0 but the index is 0
50
+ note: run with \`RUST_BACKTRACE=1\` environment variable to display a backtrace
51
+
52
+
53
+ failures:
54
+ tests::does_not_panic
55
+ tests::multiplies_two_numbers_correctly
56
+
57
+ test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
58
+
59
+ error: test failed, to rerun pass \`--lib\`
60
+ `;
61
+
62
+ // Pre-1.73 panic format
63
+ const OLD_FORMAT_PANIC = `running 2 tests
64
+ test tests::foo ... FAILED
65
+ test tests::bar ... ok
66
+
67
+ failures:
68
+
69
+ ---- tests::foo stdout ----
70
+ thread 'tests::foo' panicked at 'assertion failed: \`(left == right)\`
71
+ left: \`5\`,
72
+ right: \`10\`', src/lib.rs:8:5
73
+
74
+ failures:
75
+ tests::foo
76
+
77
+ test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
78
+ `;
79
+
80
+ const ALL_PASSING = `running 2 tests
81
+ test tests::a ... ok
82
+ test tests::b ... ok
83
+
84
+ test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
85
+ `;
86
+
87
+ const COMPILE_ERROR = ` Compiling math v0.1.0 (/project)
88
+ error[E0308]: mismatched types
89
+ --> src/lib.rs:5:20
90
+ |
91
+ 5 | let x: i32 = "oops";
92
+ | ^^^^^^ expected \`i32\`, found \`&str\`
93
+
94
+ error: could not compile \`math\` due to 1 previous error
95
+ `;
96
+
97
+ describe("cargo-test parser", () => {
98
+ describe("Rust 1.73+ panic format", () => {
99
+ it("2 failed, 1 passed → correct summary and failure details", async () => {
100
+ const result = await parser.parse(makeCtx(REAL_OUTPUT_NEW_FORMAT));
101
+ expect(result.status).toBe("fail");
102
+ expect(result.summary).toBe("2 failed, 1 passed");
103
+ expect(result.failures).toHaveLength(2);
104
+ });
105
+
106
+ it("assertion failure has file, line, and compact left/right message", async () => {
107
+ const result = await parser.parse(makeCtx(REAL_OUTPUT_NEW_FORMAT));
108
+ const f = result.failures!.find((f) => f.id.includes("20"));
109
+ expect(f).toBeDefined();
110
+ expect(f!.file).toBe("src/lib.rs");
111
+ expect(f!.line).toBe(20);
112
+ expect(f!.message).toMatch(/assertion .* failed/);
113
+ expect(f!.message).toMatch(/left: 12/);
114
+ expect(f!.message).toMatch(/right: 99/);
115
+ });
116
+
117
+ it("runtime panic has file, line, and error message", async () => {
118
+ const result = await parser.parse(makeCtx(REAL_OUTPUT_NEW_FORMAT));
119
+ const f = result.failures!.find((f) => f.id.includes("26"));
120
+ expect(f).toBeDefined();
121
+ expect(f!.file).toBe("src/lib.rs");
122
+ expect(f!.line).toBe(26);
123
+ expect(f!.message).toMatch(/index out of bounds/);
124
+ });
125
+
126
+ it("file paths are relative", async () => {
127
+ const result = await parser.parse(makeCtx(REAL_OUTPUT_NEW_FORMAT, "/project"));
128
+ for (const f of result.failures!) {
129
+ expect(f.file).not.toMatch(/^\/project/);
130
+ }
131
+ });
132
+ });
133
+
134
+ describe("pre-1.73 panic format", () => {
135
+ it("parses old-style panicked at 'message', file:line format", async () => {
136
+ const result = await parser.parse(makeCtx(OLD_FORMAT_PANIC));
137
+ expect(result.status).toBe("fail");
138
+ expect(result.summary).toBe("1 failed, 1 passed");
139
+ expect(result.failures).toHaveLength(1);
140
+ const f = result.failures![0];
141
+ expect(f.file).toBe("src/lib.rs");
142
+ expect(f.line).toBe(8);
143
+ expect(f.message).toMatch(/assertion failed/);
144
+ });
145
+ });
146
+
147
+ describe("all passing", () => {
148
+ it("all tests pass → status pass, empty failures", async () => {
149
+ const result = await parser.parse(makeCtx(ALL_PASSING));
150
+ expect(result.status).toBe("pass");
151
+ expect(result.summary).toBe("2 passed");
152
+ expect(result.failures).toHaveLength(0);
153
+ });
154
+ });
155
+
156
+ describe("compilation failure", () => {
157
+ it("no test result line → status error with guidance message", async () => {
158
+ const result = await parser.parse(makeCtx(COMPILE_ERROR));
159
+ expect(result.status).toBe("error");
160
+ expect(result.summary).toMatch(/compilation failed/);
161
+ expect(result.summary).toMatch(/cargo build --message-format=json/);
162
+ expect(result.failures).toHaveLength(0);
163
+ });
164
+ });
165
+
166
+ describe("single failing test", () => {
167
+ it("single test failure parsed correctly", async () => {
168
+ const log = `running 1 test
169
+ test tests::only_one ... FAILED
170
+
171
+ failures:
172
+
173
+ ---- tests::only_one stdout ----
174
+
175
+ thread 'tests::only_one' panicked at src/lib.rs:5:3:
176
+ explicit panic
177
+
178
+ failures:
179
+ tests::only_one
180
+
181
+ test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
182
+ `;
183
+ const result = await parser.parse(makeCtx(log));
184
+ expect(result.status).toBe("fail");
185
+ expect(result.summary).toBe("1 failed, 0 passed");
186
+ expect(result.failures).toHaveLength(1);
187
+ expect(result.failures![0].line).toBe(5);
188
+ expect(result.failures![0].message).toBe("explicit panic");
189
+ });
190
+ });
191
+ });
@@ -0,0 +1,135 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import type { ParserModule, ParsedFailure } from "../types";
4
+
5
+ // Rust 1.73+: thread 'name' (optional-id) panicked at file:line:col:
6
+ // message on following line(s)
7
+ const PANIC_NEW = /^thread '.+?' (?:\(\d+\) )?panicked at (.+?):(\d+):\d+:?$/;
8
+
9
+ // Pre-1.73: thread 'name' panicked at 'message', file:line:col
10
+ // Message may span multiple lines — use dotall flag
11
+ const PANIC_OLD = /thread '.+?' panicked at '(.*)', (.+?):(\d+):\d+/s;
12
+
13
+ // test result: FAILED. 1 passed; 2 failed; ...
14
+ const TEST_RESULT_RE = /^test result: \w+\. (\d+) passed; (\d+) failed/;
15
+
16
+ // ---- test::name stdout ----
17
+ const BLOCK_HEADER_RE = /^---- (.+) stdout ----$/;
18
+
19
+ const parser: ParserModule = {
20
+ id: "cargo-test",
21
+ async parse(ctx) {
22
+ // Use combined log — test binary output goes to stdout, cargo progress to stderr;
23
+ // reading both ensures we catch everything regardless of buffering order.
24
+ const log = fs.readFileSync(ctx.logPath, "utf8");
25
+ const lines = log.split("\n").map((l) => l.trim());
26
+
27
+ // If compilation failed there will be no "test result:" line
28
+ const hasTestResult = lines.some((l) => TEST_RESULT_RE.test(l));
29
+ if (!hasTestResult) {
30
+ return {
31
+ tool: "cargo",
32
+ status: "error",
33
+ summary: "compilation failed — run `cargo build --message-format=json` for structured errors",
34
+ failures: [],
35
+ logPath: ctx.logPath,
36
+ };
37
+ }
38
+
39
+ let passed = 0;
40
+ let failed = 0;
41
+ for (const line of lines) {
42
+ const m = TEST_RESULT_RE.exec(line);
43
+ if (m) {
44
+ passed = Number(m[1]);
45
+ failed = Number(m[2]);
46
+ }
47
+ }
48
+
49
+ // Split into per-test failure blocks delimited by "---- test::name stdout ----" headers
50
+ const blocks: Array<{ name: string; lines: string[] }> = [];
51
+ let current: { name: string; lines: string[] } | null = null;
52
+
53
+ for (const line of lines) {
54
+ const headerMatch = BLOCK_HEADER_RE.exec(line);
55
+ if (headerMatch) {
56
+ if (current) blocks.push(current);
57
+ current = { name: headerMatch[1], lines: [] };
58
+ } else if (current) {
59
+ current.lines.push(line);
60
+ }
61
+ }
62
+ if (current) blocks.push(current);
63
+
64
+ const failures: ParsedFailure[] = blocks.map(({ name, lines: blockLines }) =>
65
+ parseFailureBlock(name, blockLines, ctx.cwd)
66
+ );
67
+
68
+ return {
69
+ tool: "cargo",
70
+ status: failed > 0 ? "fail" : "pass",
71
+ summary: failed > 0 ? `${failed} failed, ${passed} passed` : `${passed} passed`,
72
+ failures,
73
+ logPath: ctx.logPath,
74
+ };
75
+ },
76
+ };
77
+
78
+ function parseFailureBlock(testName: string, lines: string[], cwd: string): ParsedFailure {
79
+ let file: string | undefined;
80
+ let lineNum: number | undefined;
81
+ let message: string | undefined;
82
+
83
+ // Try new format (1.73+) line by line first
84
+ for (let i = 0; i < lines.length; i++) {
85
+ const line = lines[i];
86
+ const newMatch = PANIC_NEW.exec(line);
87
+ if (newMatch) {
88
+ file = path.relative(cwd, path.resolve(cwd, newMatch[1]));
89
+ lineNum = Number(newMatch[2]);
90
+ // Collect message lines that follow until blank line or note:/error:
91
+ const msgLines: string[] = [];
92
+ for (let j = i + 1; j < lines.length; j++) {
93
+ const next = lines[j];
94
+ if (next === "" || next.startsWith("note:") || next.startsWith("error:")) break;
95
+ msgLines.push(next);
96
+ }
97
+ message = formatMessage(msgLines);
98
+ break;
99
+ }
100
+ }
101
+
102
+ // Fall back to pre-1.73 format; join block so dotall regex handles multi-line messages
103
+ if (!file) {
104
+ const blockText = lines.join("\n");
105
+ const oldMatch = PANIC_OLD.exec(blockText);
106
+ if (oldMatch) {
107
+ // Collapse internal newlines in message to a single space
108
+ message = oldMatch[1].replace(/\s+/g, " ").trim();
109
+ file = path.relative(cwd, path.resolve(cwd, oldMatch[2]));
110
+ lineNum = Number(oldMatch[3]);
111
+ }
112
+ }
113
+
114
+ const id = [file, lineNum, testName].filter(Boolean).join(":");
115
+ return {
116
+ id: id || testName,
117
+ file,
118
+ line: lineNum,
119
+ message: message ?? testName,
120
+ };
121
+ }
122
+
123
+ /** Compact assertion left/right onto one line; otherwise join with "; " */
124
+ function formatMessage(msgLines: string[]): string {
125
+ if (msgLines.length === 0) return "";
126
+ const main = msgLines[0];
127
+ const leftLine = msgLines.find((l) => l.trimStart().startsWith("left:"));
128
+ const rightLine = msgLines.find((l) => l.trimStart().startsWith("right:"));
129
+ if (leftLine && rightLine) {
130
+ return `${main}\n${leftLine.trim()}, ${rightLine.trim()}`;
131
+ }
132
+ return msgLines.filter(Boolean).join("; ");
133
+ }
134
+
135
+ export default parser;
@@ -185,6 +185,66 @@ math-benchmark.TestDoesNotPanic(0x123)
185
185
  });
186
186
  });
187
187
 
188
+ describe("maven / java stack trace output", () => {
189
+ it("extracts file and line from first frame matching classname", async () => {
190
+ const xml = `<testsuite name="MathTest" tests="1" failures="0" errors="1">
191
+ <testcase name="multipliesTwoNumbersCorrectly" classname="MathTest" time="0.001">
192
+ <error message="expected: &lt;99&gt; but was: &lt;12&gt;" type="org.opentest4j.AssertionFailedError"><![CDATA[org.opentest4j.AssertionFailedError: expected: <99> but was: <12>
193
+ at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:151)
194
+ at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:150)
195
+ at MathTest.multipliesTwoNumbersCorrectly(MathTest.java:13)
196
+ at java.base/java.lang.reflect.Method.invoke(Method.java:565)
197
+ ]]></error>
198
+ </testcase>
199
+ </testsuite>`;
200
+ const result = await parser.parse(makeCtx(xml));
201
+ expect(result.failures![0].file).toBe("MathTest.java");
202
+ expect(result.failures![0].line).toBe(13);
203
+ });
204
+
205
+ it("falls back to first non-framework frame when classname has no match", async () => {
206
+ const xml = `<testsuite name="suite" tests="1" failures="0" errors="1">
207
+ <testcase name="doesNotDivideByZero" classname="MathTest" time="0.001">
208
+ <error message="/ by zero" type="java.lang.ArithmeticException"><![CDATA[java.lang.ArithmeticException: / by zero
209
+ at MathTest.doesNotDivideByZero(MathTest.java:18)
210
+ at java.base/java.lang.reflect.Method.invoke(Method.java:565)
211
+ ]]></error>
212
+ </testcase>
213
+ </testsuite>`;
214
+ const result = await parser.parse(makeCtx(xml));
215
+ expect(result.failures![0].file).toBe("MathTest.java");
216
+ expect(result.failures![0].line).toBe(18);
217
+ });
218
+ });
219
+
220
+ describe("dotnet / xunit output", () => {
221
+ it("extracts file and line from .NET stack trace body", async () => {
222
+ const xml = `<testsuites>
223
+ <testsuite name="dotnet.dll" tests="1" failures="1" errors="0">
224
+ <testcase classname="Benchmark.MathTest" name="DoesNotThrowOnNullAccess" time="0.001">
225
+ <failure type="failure" message="System.NullReferenceException : Object reference not set to an instance of an object.">at Benchmark.MathTest.DoesNotThrowOnNullAccess() in /project/MathTest.cs:line 21
226
+ at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)</failure>
227
+ </testcase>
228
+ </testsuite>
229
+ </testsuites>`;
230
+ const result = await parser.parse(makeCtx(xml));
231
+ expect(result.failures![0].file).toBe("MathTest.cs");
232
+ expect(result.failures![0].line).toBe(21);
233
+ });
234
+
235
+ it("decodes &#xA; entities in message attribute", async () => {
236
+ const xml = `<testsuites>
237
+ <testsuite name="dotnet.dll" tests="1" failures="1" errors="0">
238
+ <testcase classname="Benchmark.MathTest" name="MultipliesTwoNumbersCorrectly" time="0.001">
239
+ <failure type="failure" message="Assert.Equal() Failure: Values differ&#xA;Expected: 99&#xA;Actual: 12">at Benchmark.MathTest.MultipliesTwoNumbersCorrectly() in /project/MathTest.cs:line 14</failure>
240
+ </testcase>
241
+ </testsuite>
242
+ </testsuites>`;
243
+ const result = await parser.parse(makeCtx(xml));
244
+ expect(result.failures![0].message).toBe("Assert.Equal() Failure: Values differ\nExpected: 99\nActual: 12");
245
+ });
246
+ });
247
+
188
248
  describe("pytest --junitxml output", () => {
189
249
  it("extracts file and line from failure body when no file attr present", async () => {
190
250
  const xml = `<?xml version="1.0" encoding="utf-8"?>
@@ -207,6 +267,41 @@ tests/test_math.py:5: AssertionError</failure>
207
267
  });
208
268
  });
209
269
 
270
+ describe("jest-junit output", () => {
271
+ it("extracts file, line, and message from plain-text failure elements", async () => {
272
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
273
+ <testsuites name="jest tests" tests="3" failures="2" errors="0">
274
+ <testsuite name="basic math" errors="0" failures="2" skipped="0" tests="3">
275
+ <testcase classname="basic math adds two numbers correctly" name="basic math adds two numbers correctly" time="0"/>
276
+ <testcase classname="basic math multiplies two numbers correctly" name="basic math multiplies two numbers correctly" time="0.001">
277
+ <failure>Error: expect(received).toBe(expected) // Object.is equality
278
+
279
+ Expected: 99
280
+ Received: 12
281
+ at Object.toBe (/project/math.test.js:7:19)
282
+ at Promise.then.completed (/project/node_modules/jest-circus/build/utils.js:298:28)</failure>
283
+ </testcase>
284
+ <testcase classname="basic math does not divide by zero" name="basic math does not divide by zero" time="0">
285
+ <failure>TypeError: Cannot read properties of null (reading 'value')
286
+ at Object.value (/project/math.test.js:11:25)
287
+ at Promise.then.completed (/project/node_modules/jest-circus/build/utils.js:298:28)</failure>
288
+ </testcase>
289
+ </testsuite>
290
+ </testsuites>`;
291
+ const result = await parser.parse(makeCtx(xml, "/project"));
292
+ expect(result.status).toBe("fail");
293
+ expect(result.summary).toBe("2 failed, 1 passed");
294
+ expect(result.failures![0].file).toBe("math.test.js");
295
+ expect(result.failures![0].line).toBe(7);
296
+ expect(result.failures![0].message).toBe(
297
+ "Error: expect(received).toBe(expected) // Object.is equality\nExpected: 99\nReceived: 12"
298
+ );
299
+ expect(result.failures![1].file).toBe("math.test.js");
300
+ expect(result.failures![1].line).toBe(11);
301
+ expect(result.failures![1].message).toBe("TypeError: Cannot read properties of null (reading 'value')");
302
+ });
303
+ });
304
+
210
305
  describe("multi-suite totals", () => {
211
306
  it("failures and errors summed across suites", async () => {
212
307
  const xml = `<testsuites>
@@ -39,18 +39,76 @@ const xmlParser = new XMLParser({
39
39
  isArray: (name) => ["testsuite", "testcase"].includes(name),
40
40
  });
41
41
 
42
+ /** Decode numeric XML character references (e.g. &#xA; → newline) in attribute values. */
43
+ function decodeXmlEntities(s: string): string {
44
+ return s
45
+ .replace(/&#[xX]([0-9a-fA-F]+);/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
46
+ .replace(/&#(\d+);/g, (_, dec) => String.fromCharCode(Number(dec)));
47
+ }
48
+
49
+ /** Extract Expected/Received/Actual diff lines from a failure body, e.g. Jest assertion output. */
50
+ function extractAssertionDiff(text: string): string | undefined {
51
+ const diffLines: string[] = [];
52
+ for (const line of text.split("\n")) {
53
+ const trimmed = line.trim();
54
+ if (/^(Expected|Received|Actual)\s*:/.test(trimmed)) diffLines.push(trimmed);
55
+ }
56
+ return diffLines.length > 0 ? diffLines.join("\n") : undefined;
57
+ }
58
+
42
59
  /** Extract file, line, and message from failure body text.
43
- * Handles pytest-style (last line: "file.py:line: ExceptionType")
44
- * and Go-style (any line: " file.go:line: message"). */
45
- function parseBodyLocation(text: string): { file: string; line: number; message?: string } | undefined {
60
+ * Handles:
61
+ * - pytest-style: "file.py:line: message"
62
+ * - Go-style: " file.go:line: message"
63
+ * - .NET-style: "in /path/File.cs:line N"
64
+ * - Java/JVM-style: "at [module/]pkg.Class.method(File.java:N)"
65
+ * preferring the frame whose class matches `classname`. */
66
+ function parseBodyLocation(
67
+ text: string,
68
+ classname?: string
69
+ ): { file: string; line: number; message?: string } | undefined {
46
70
  const lines = text
47
71
  .split("\n")
48
72
  .map((l) => l.trim())
49
73
  .filter(Boolean);
74
+
75
+ // pytest / Go: "file.ext:line: message"
50
76
  for (const line of lines) {
51
77
  const m = line.match(/^([^:\s]+\.\w+):(\d+):\s*(.*)/);
52
78
  if (m) return { file: m[1], line: Number(m[2]), message: m[3] || undefined };
53
79
  }
80
+
81
+ // .NET: "in /path/File.cs:line N"
82
+ for (const line of lines) {
83
+ const m = line.match(/\bin ([^\s]+\.(?:cs|fs|vb)):line (\d+)/);
84
+ if (m) return { file: path.basename(m[1]), line: Number(m[2]) };
85
+ }
86
+
87
+ // Jest/Node-style: " at Something (file.js:line:col)" — skip node_modules frames
88
+ for (const line of lines) {
89
+ const m = line.match(/^at\s+\S+\s+\(([^)]+\.(?:[jt]sx?|mjs|cjs)):(\d+):\d+\)/);
90
+ if (m && !m[1].includes("node_modules")) {
91
+ return { file: path.basename(m[1]), line: Number(m[2]) };
92
+ }
93
+ }
94
+
95
+ // Java/JVM: "at [module/]pkg.Class.method(File.java:N)"
96
+ const javaRe = /^at (?:[\w.$]+\/)?([\w.$]+)\.\w+\(([\w]+\.(?:java|kt|scala|groovy)):(\d+)\)$/;
97
+ const frameworkPrefixes = ["java.", "javax.", "sun.", "com.sun.", "org.junit.", "org.opentest4j.", "junit."];
98
+ const simpleClass = classname?.split(".").pop();
99
+ let firstUserFrame: { file: string; line: number } | undefined;
100
+
101
+ for (const line of lines) {
102
+ const m = line.match(javaRe);
103
+ if (!m) continue;
104
+ const [, cls, file, lineNum] = m;
105
+ if (simpleClass && cls === simpleClass) return { file, line: Number(lineNum) };
106
+ if (!firstUserFrame && !frameworkPrefixes.some((p) => cls.startsWith(p))) {
107
+ firstUserFrame = { file, line: Number(lineNum) };
108
+ }
109
+ }
110
+
111
+ if (firstUserFrame) return firstUserFrame;
54
112
  return undefined;
55
113
  }
56
114
 
@@ -104,10 +162,11 @@ const parser: ParserModule = {
104
162
  totalFailed += Number(suite.failures ?? 0) + Number(suite.errors ?? 0);
105
163
 
106
164
  for (const tc of suite.testcase ?? []) {
107
- const problem = tc.failure ?? tc.error;
108
- if (!problem) continue;
165
+ const rawProblem = tc.failure ?? tc.error;
166
+ if (!rawProblem) continue;
167
+ const problem: JUnitFailureOrError = typeof rawProblem === "string" ? { "#text": rawProblem } : rawProblem;
109
168
 
110
- const bodyLocation = problem["#text"] ? parseBodyLocation(problem["#text"]) : undefined;
169
+ const bodyLocation = problem["#text"] ? parseBodyLocation(problem["#text"], tc.classname) : undefined;
111
170
  const panicInfo =
112
171
  !bodyLocation && suite["system-out"] && tc.name ? parsePanicInfo(suite["system-out"], tc.name) : undefined;
113
172
  const file =
@@ -121,13 +180,29 @@ const parser: ParserModule = {
121
180
  id: id || String(failures.length),
122
181
  file,
123
182
  line: Number.isNaN(line) ? undefined : line,
124
- message:
125
- problem.message && problem.message.toLowerCase() !== "failed"
126
- ? problem.message
127
- : (bodyLocation?.message ??
128
- panicInfo?.message ??
129
- problem.message ??
130
- problem["#text"]?.trim().split("\n")[0]),
183
+ message: (() => {
184
+ const raw =
185
+ problem.message && problem.message.toLowerCase() !== "failed"
186
+ ? problem.message
187
+ : (bodyLocation?.message ??
188
+ panicInfo?.message ??
189
+ problem.message ??
190
+ problem["#text"]?.trim().split("\n")[0]);
191
+ if (!raw) return undefined;
192
+ const decoded = decodeXmlEntities(raw);
193
+ // Append assertion diff lines (Expected/Received/Actual) from the body when not already present.
194
+ // Covers Jest-style failures where the diff follows the error type line in #text.
195
+ if (
196
+ problem["#text"] &&
197
+ !decoded.includes("Expected") &&
198
+ !decoded.includes("Received") &&
199
+ !decoded.includes("Actual")
200
+ ) {
201
+ const diff = extractAssertionDiff(problem["#text"]);
202
+ if (diff) return `${decoded}\n${diff}`;
203
+ }
204
+ return decoded;
205
+ })(),
131
206
  rule: problem.type,
132
207
  });
133
208
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robhowley/pi-structured-return",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "Structured command execution for Pi agents: compact results for the model, full logs for humans.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -45,13 +45,38 @@ Prefer better output at the source.
45
45
  ### minitest
46
46
  - `structured_return({ command: "ruby [any minitest args]", parseAs: "minitest-text" })` — no format flags needed; works with plain ruby invocation
47
47
 
48
+ ### cargo build
49
+ - `structured_return({ command: "cargo build --message-format=json", parseAs: "cargo-build" })` — `--message-format=json` is built into cargo; errors include file, line, error code (E0308 etc.), and primary span label (expected X, found Y); warnings are filtered out
50
+
51
+ ### cargo test
52
+ - `structured_return({ command: "cargo test", parseAs: "cargo-test" })` — no extra flags needed; assertion failures surface left/right values and file:line; panics surface the message and file:line; if compilation fails, the summary says so and tells the model to run `cargo build --message-format=json` for structured errors
53
+ - `structured_return({ command: "cargo test [filter]", parseAs: "cargo-test" })` — filter by test name substring, module path, or `--test integration_test_name`
54
+
48
55
  ### junit-xml
56
+
49
57
  JUnit XML is the de facto standard output format across the JVM ecosystem and many others — Maven, Gradle, pytest (`--junitxml`), Go (`go-junit-report`), .NET (`--logger trx` with conversion), Jest (`jest-junit`), and more. If a tool can emit JUnit XML, `junit-xml` covers it without a custom parser.
50
58
 
51
59
  - `structured_return({ command: "[tool] [args] --junitxml=.tmp/report.xml", parseAs: "junit-xml", artifactPaths: [".tmp/report.xml"] })` — pytest, nose2, and any other tool that writes to a file via `--junitxml`
52
60
  - `structured_return({ command: "go test [any go test args] 2>&1 | go-junit-report > .tmp/report.xml", parseAs: "junit-xml", artifactPaths: [".tmp/report.xml"] })` — Go requires `go-junit-report` (`go install github.com/jstemmer/go-junit-report/v2@latest`); pipe `go test -v` output through it
53
61
  - `structured_return({ command: "gradle test", parseAs: "junit-xml", artifactPaths: ["build/test-results/test/TEST-*.xml"] })` — Gradle writes one XML per test class; pass all matching paths
54
- - `structured_return({ command: "mvn test", parseAs: "junit-xml", artifactPaths: ["target/surefire-reports/TEST-*.xml"] })` — Maven surefire same pattern
62
+
63
+ #### .NET / xUnit
64
+
65
+ `dotnet test` requires the `JunitXml.TestLogger` package (`dotnet add package JunitXml.TestLogger`). Pass the logger inline — no config file changes needed. Add a namespace to your test class or the logger will fall back to `UnknownNamespace.UnknownType` for classnames.
66
+
67
+ - `structured_return({ command: "dotnet test --logger \"junit;LogFilePath=.tmp/report.xml\"", parseAs: "junit-xml", artifactPaths: [".tmp/report.xml"] })` — any dotnet test args (project path, `--filter`, etc.) go before `--logger`
68
+
69
+ #### Maven
70
+
71
+ `mvn test` writes one XML per test class via surefire — no extra configuration needed.
72
+
73
+ - `structured_return({ command: "mvn test", parseAs: "junit-xml", artifactPaths: ["target/surefire-reports/TEST-*.xml"] })` — surefire writes one XML per class; glob covers all of them; any maven args (e.g. `-pl module`, `-Dtest=ClassName`) go before `test`
74
+
75
+ #### Jest
76
+
77
+ Jest requires the `jest-junit` reporter (`npm install --save-dev jest-junit`). Pass it via `--reporters` on the CLI — no permanent config change needed.
78
+
79
+ - `structured_return({ command: "jest [any jest args] --reporters=jest-junit", parseAs: "junit-xml", artifactPaths: [".tmp/junit.xml"] })` — set `JEST_JUNIT_OUTPUT_FILE=.tmp/junit.xml` or configure `outputFile` in `jest-junit` config; file paths, `--testPathPattern`, etc. go in `[any jest args]`
55
80
 
56
81
  #### Swift / XCTest (Swift Package Manager)
57
82