@robhowley/pi-structured-return 1.2.1 → 1.2.2

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,14 @@ 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 |
22
24
  | `junit-xml` (gradle) | 263 | 81 | **69%** | gradle console output with build lifecycle noise |
25
+ | `junit-xml` (jest) | 309 | 99 | **68%** | source annotations with deep jest-circus stack traces per failure |
23
26
  | `minitest-text` | 168 | 59 | **65%** | default output with backtrace |
24
27
  | `ruff-json` | 107 | 52 | **51%** | source context + help text per error |
25
28
  | `eslint-json` | 64 | 59 | **8%** | already compact formatter |
@@ -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
  }
@@ -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.2.2",
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": {
@@ -46,12 +46,30 @@ Prefer better output at the source.
46
46
  - `structured_return({ command: "ruby [any minitest args]", parseAs: "minitest-text" })` — no format flags needed; works with plain ruby invocation
47
47
 
48
48
  ### junit-xml
49
+
49
50
  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
51
 
51
52
  - `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
53
  - `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
54
  - `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
55
+
56
+ #### .NET / xUnit
57
+
58
+ `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.
59
+
60
+ - `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`
61
+
62
+ #### Maven
63
+
64
+ `mvn test` writes one XML per test class via surefire — no extra configuration needed.
65
+
66
+ - `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`
67
+
68
+ #### Jest
69
+
70
+ Jest requires the `jest-junit` reporter (`npm install --save-dev jest-junit`). Pass it via `--reporters` on the CLI — no permanent config change needed.
71
+
72
+ - `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
73
 
56
74
  #### Swift / XCTest (Swift Package Manager)
57
75