@robhowley/pi-structured-return 1.3.0 → 1.5.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 (43) hide show
  1. package/README.md +79 -52
  2. package/extensions/structured-return/src/config/registry.test.ts +171 -0
  3. package/extensions/structured-return/src/config/registry.ts +99 -13
  4. package/extensions/structured-return/src/index.test.ts +54 -0
  5. package/extensions/structured-return/src/index.ts +20 -9
  6. package/extensions/structured-return/src/parsers/ava-text.test.ts +116 -0
  7. package/extensions/structured-return/src/parsers/ava-text.ts +161 -0
  8. package/extensions/structured-return/src/parsers/cargo-build.ts +2 -2
  9. package/extensions/structured-return/src/parsers/cargo-test.ts +2 -2
  10. package/extensions/structured-return/src/parsers/dbt-json.test.ts +172 -0
  11. package/extensions/structured-return/src/parsers/dbt-json.ts +131 -0
  12. package/extensions/structured-return/src/parsers/eslint-json.ts +2 -2
  13. package/extensions/structured-return/src/parsers/go-test-json.test.ts +119 -0
  14. package/extensions/structured-return/src/parsers/go-test-json.ts +137 -0
  15. package/extensions/structured-return/src/parsers/hadolint-json.test.ts +73 -0
  16. package/extensions/structured-return/src/parsers/hadolint-json.ts +55 -0
  17. package/extensions/structured-return/src/parsers/junit-xml.ts +2 -2
  18. package/extensions/structured-return/src/parsers/minitest-text.ts +2 -2
  19. package/extensions/structured-return/src/parsers/mocha-json.test.ts +108 -0
  20. package/extensions/structured-return/src/parsers/mocha-json.ts +77 -0
  21. package/extensions/structured-return/src/parsers/mypy-json.test.ts +101 -0
  22. package/extensions/structured-return/src/parsers/mypy-json.ts +80 -0
  23. package/extensions/structured-return/src/parsers/pylint-json.test.ts +120 -0
  24. package/extensions/structured-return/src/parsers/pylint-json.ts +64 -0
  25. package/extensions/structured-return/src/parsers/rspec-json.ts +2 -2
  26. package/extensions/structured-return/src/parsers/rubocop-json.test.ts +118 -0
  27. package/extensions/structured-return/src/parsers/rubocop-json.ts +65 -0
  28. package/extensions/structured-return/src/parsers/ruff-json.ts +2 -2
  29. package/extensions/structured-return/src/parsers/shellcheck-json.test.ts +110 -0
  30. package/extensions/structured-return/src/parsers/shellcheck-json.ts +61 -0
  31. package/extensions/structured-return/src/parsers/stylelint-json.test.ts +120 -0
  32. package/extensions/structured-return/src/parsers/stylelint-json.ts +68 -0
  33. package/extensions/structured-return/src/parsers/swiftc-text.test.ts +73 -0
  34. package/extensions/structured-return/src/parsers/swiftc-text.ts +47 -0
  35. package/extensions/structured-return/src/parsers/tail-fallback.ts +2 -2
  36. package/extensions/structured-return/src/parsers/tsc-text.test.ts +81 -0
  37. package/extensions/structured-return/src/parsers/tsc-text.ts +47 -0
  38. package/extensions/structured-return/src/parsers/unittest-text.test.ts +126 -0
  39. package/extensions/structured-return/src/parsers/unittest-text.ts +116 -0
  40. package/extensions/structured-return/src/parsers/utils.ts +43 -0
  41. package/extensions/structured-return/src/parsers/vitest-json.ts +2 -2
  42. package/package.json +1 -1
  43. package/skills/structured-return/SKILL.md +44 -0
package/README.md CHANGED
@@ -1,48 +1,10 @@
1
1
  # pi-structured-return
2
2
 
3
- Structured command execution for pi agents: compact results for the model, full logs for humans.
4
-
5
- Cross-platform Pi package that combines:
6
- - a `structured-return` skill for choosing compact / machine-readable command forms
7
- - a `structured-return` extension that captures output, stores artifacts, applies parsers, and falls back to tail + log path
8
-
9
- ## Token reduction
3
+ Structured command execution for Pi agents: compact results for the model, full logs for humans.
10
4
 
11
5
  Tool output is designed for humans: source diffs, line annotations, timing breakdowns, absolute paths repeated on every line. Useful on a terminal. Expensive in a model context, especially on failure when output is most verbose and the model needs to act fast.
12
6
 
13
- Test runners: 3 tests, 1 passing, 1 assertion failure, 1 unexpected error.
14
- Linters: 1 unused variable warning in a single file.
15
-
16
- | Parser | Raw (tokens) | Structured (tokens) | Reduction | Notes |
17
- |---|---|---|---|---|
18
- | `junit-xml` (maven) | 1063 | 86 | **92%** | build lifecycle noise with surefire stack traces per failure |
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 |
21
- | `vitest-json` | 348 | 75 | **78%** | source diff with inline arrows and ANSI color codes per failure |
22
- | `junit-xml` (pytest) | 289 | 71 | **75%** | verbose output with source snippets and summary footer |
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 |
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 |
28
- | `minitest-text` | 168 | 59 | **65%** | default output with backtrace |
29
- | `ruff-json` | 107 | 52 | **51%** | source context + help text per error |
30
- | `eslint-json` | 64 | 59 | **8%** | already compact formatter |
31
-
32
- Tokens counted with `cl100k_base` (tiktoken). Linter output is more compact than test runner output to begin with, so the baseline reduction is lower. The numbers above are measured against a single file with a single error — a conservative lower bound. Both ruff and eslint repeat absolute file paths per error in their raw output, so reduction grows as violations spread across more files.
33
-
34
- ## Built-in parsers
35
- - `junit-xml` (JUnit XML — covers pytest `--junitxml`, Gradle, Maven, Jest with `jest-junit`, Go with `go-junit-report`, and any other tool that emits the JUnit XML schema)
36
- - `vitest-json`
37
- - `rspec-json`
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`)
41
- - `ruff-json` (`ruff check` only — `ruff format` has no json support)
42
- - `eslint-json`
43
-
44
-
45
- ## Before / after
7
+ This Pi package adds a `structured_return` tool alongside `bash`. A bundled skill teaches the model when to reach for it — test suites, linters, build tools, data pipelines — anywhere verbose output burns tokens. It captures full logs, applies a parser, and returns a compact structured result. The full output stays on disk.
46
8
 
47
9
  **Raw pytest output (262 tokens):**
48
10
  ```
@@ -84,28 +46,96 @@ pytest test_math.py --junitxml=.tmp/report.xml → cwd: project
84
46
  test_math.py:8 ZeroDivisionError: division by zero
85
47
  ```
86
48
 
49
+ 262 → 56 tokens. The model knows which tests failed, where, and why. No platform line, no progress bar, no source snippets, no banner separators, no short summary repeating the same info. And that's a single run — in an agentic loop the cost compounds. Every tool result accumulates in context for the life of the task. Over 15 red-green iterations, the difference isn't 262 vs 56 — it's 3,930 vs 840 tokens for one command in one task.
50
+
51
+ ## Token reduction
52
+
53
+ Measured with `cl100k_base` (tiktoken). All benchmarks use tiny fixtures — reduction grows with real-world output.
54
+
55
+ ### Test runners
56
+
57
+ Benchmark: 3 tests — 1 passing, 1 assertion failure, 1 unexpected error.
58
+
59
+ | Parser | Raw | Structured | Reduction | Notes |
60
+ |---|---|---|---|---|
61
+ | `go-test-json` | 1819 | 48 | **97%** | NDJSON event stream with stack traces; file:line + expected/actual preserved |
62
+ | `junit-xml` (maven) | 1063 | 86 | **92%** | build lifecycle noise with surefire stack traces per failure |
63
+ | `ava-text` | 483 | 56 | **88%** | source snippets, diffs, full stack traces stripped; expected/actual preserved |
64
+ | `junit-xml` (go) | 400 | 58 | **86%** | verbose output with full stack trace per failure |
65
+ | `junit-xml` (dotnet) | 487 | 107 | **78%** | build header and VSTest output with per-failure stack traces |
66
+ | `vitest-json` | 348 | 75 | **78%** | source diff with inline arrows and ANSI color codes per failure |
67
+ | `unittest-text` | 231 | 52 | **78%** | full tracebacks with source annotations; expected/actual from AssertionError |
68
+ | `cargo-test` | 285 | 68 | **76%** | cargo progress + test binary output with panic traces per failure |
69
+ | `junit-xml` (pytest) | 289 | 71 | **75%** | verbose output with source snippets and summary footer |
70
+ | `rspec-json` | 212 | 55 | **74%** | default output with backtrace |
71
+ | `junit-xml` (gradle) | 263 | 81 | **69%** | gradle console output with build lifecycle noise |
72
+ | `mocha-json` | 180 | 55 | **69%** | stack traces + assertion diff formatting; expected/actual preserved |
73
+ | `junit-xml` (jest) | 309 | 99 | **68%** | source annotations with deep jest-circus stack traces per failure |
74
+ | `minitest-text` | 168 | 59 | **65%** | default output with backtrace |
75
+
76
+ ### Linters, type checkers, and build tools
77
+
78
+ Benchmark: 1 file, 1–2 violations. Reduction is a conservative lower bound — scales with file and error count since raw output repeats paths, source snippets, and annotations per violation.
79
+
80
+ | Parser | Raw | Structured | Reduction | Notes |
81
+ |---|---|---|---|---|
82
+ | `cargo-build` | 225 | 77 | **66%** | rustc error annotations with code spans and help text per error |
83
+ | `swiftc-text` | 161 | 58 | **64%** | source annotations with backtick markers deduplicated |
84
+ | `ruff-json` | 107 | 52 | **51%** | source context + help text per error |
85
+ | `shellcheck-json` | 224 | 117 | **48%** | strips source snippets, carets, suggestions, wiki URLs |
86
+ | `rubocop-json` | 149 | 90 | **40%** | strips source snippets, caret indicators, summary line |
87
+ | `tsc-text` | 107 | 72 | **33%** | vs `--pretty true` default; source snippets and underlines stripped |
88
+ | `stylelint-json` | 70 | 51 | **27%** | strips summary footer and fix hint |
89
+ | `pylint-json` | 141 | 120 | **15%** | strips header, score line, separator; scales with error count |
90
+ | `hadolint-json` | 178 | 156 | **12%** | strips ANSI color codes and level labels; measured vs colored output |
91
+ | `eslint-json` | 64 | 59 | **8%** | already compact formatter |
92
+ | `mypy-json` | 75 | 72 | **4%** | mypy text is already compact; notes folded into parent errors |
93
+ | `flake8` | 75 | — | **—** | already compact (`file:line:col: CODE message`); no parser — use `bash` directly |
94
+
95
+ ### Pipeline tools
96
+
97
+ dbt output is the noisiest tool in this repo relative to useful signal. Every run prints version info, adapter registration, project stats, concurrency settings, and per-node start/finish lines — all before any result.
98
+
99
+ The numbers below use 3–4 model toy examples; real projects run hundreds of models where the noise scales linearly and reduction compounds.
100
+
101
+ | Parser | Raw | Structured | Reduction | Notes |
102
+ |---|---|---|---|---|
103
+ | `dbt-json` (run, success) | 428 | 20 | **95%** | version, adapter, concurrency, per-model start/finish — all noise on success |
104
+ | `dbt-json` (run, failure) | 618 | 198 | **68%** | error messages, model paths, compiled code paths preserved |
105
+ | `dbt-json` (test) | 720 | 274 | **62%** | unit test diff tables preserved verbatim; preamble stripped |
106
+ | `dbt-json` (compile) | 775 | 683 | **12%** | compiled SQL is the signal and returned verbatim |
107
+
108
+ At 12 models, run failures hit 85% reduction. An 18-model DAG success: 1,645 → 20 tokens (99%).
109
+
110
+ ## Built-in parsers
111
+
112
+ **Test runners:** `junit-xml` (pytest, Gradle, Maven, Jest, Go, .NET — anything that emits JUnit XML), `vitest-json`, `rspec-json`, `minitest-text`, `cargo-test`, `go-test-json`, `mocha-json`, `ava-text`, `unittest-text`
113
+
114
+ **Linters & type checkers:** `ruff-json`, `eslint-json`, `mypy-json`, `tsc-text`, `pylint-json`, `shellcheck-json`, `rubocop-json`, `swiftc-text`, `hadolint-json`, `stylelint-json`
115
+
116
+ **Build tools:** `cargo-build`
117
+
118
+ **Pipeline tools:** `dbt-json` (run, test, compile)
119
+
120
+ Run `/sr-parsers` in a pi session to see all registered parsers with their match rules.
121
+
122
+
87
123
  ## Installation
88
124
 
125
+ Install the skill and extension:
126
+
89
127
  ```bash
90
128
  pi install npm:@robhowley/pi-structured-return
91
129
  ```
92
130
 
93
131
  ## How it works
94
132
 
95
- 1. The agent runs commands through `structured_return` instead of `bash`.
133
+ 1. The agent runs commands through `structured_return` when it would reduce noise and token usage.
96
134
  2. Full output is captured and stored as a log.
97
135
  3. A parser converts noisy CLI output into a compact structured result. If no parser matches, the last 200 lines and the log path are returned as a fallback.
98
136
  4. The agent receives the structured result in context — signal only, no noise.
99
137
  5. The full log is always available on disk for both the agent and humans to inspect.
100
138
 
101
- ## Agentic loops
102
-
103
- The token table above measures a single run. In an agentic loop the cost compounds — every tool result accumulates in context for the life of the task.
104
-
105
- This applies to any loop: fixing a failing test suite, implementing a feature end-to-end, working through a migration, performance tuning execution times. The agent runs a command, reads the result, makes a change, runs it again. Each iteration adds another tool result to the context window. With a noisy CLI that means paying for the same verbose boilerplate every time.
106
-
107
- A parser reduces each run to a one- or two-line signal. Over 15 iterations the difference isn't 80 tokens vs 15 tokens — it's 1,200 tokens vs 225 for a single command in a single task.
108
-
109
139
  ## Extending with project-local parsers
110
140
 
111
141
  Built-in parsers cover common tools. For everything else — internal CLIs, custom test runners, proprietary lint tools — add a `.pi/structured-return.json` to your project root.
@@ -170,9 +200,6 @@ export default {
170
200
 
171
201
  The parser receives a `RunContext` (command, argv, cwd, stdout/stderr paths, artifact paths, log path) and returns a `ParsedResult`. Match rules support `argvIncludes` (array of required tokens) or `regex` (tested against the full argv string).
172
202
 
173
- ## Slash commands
174
- - `/sr-parsers` — list all registered parsers (built-in and project-local) with their match rules and targets
175
-
176
203
  ## Structured result schema
177
204
 
178
205
  Every parser returns the same shape. The model always knows where to look.
@@ -0,0 +1,171 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { resolveParser } from "./registry";
3
+
4
+ /** Resolve a parser from argv with no explicit parseAs or project registrations. */
5
+ async function detect(argv: string[]) {
6
+ const parser = await resolveParser({ cwd: "/project", argv, registrations: [] });
7
+ return parser.id;
8
+ }
9
+
10
+ describe("resolveParser priority", () => {
11
+ it("explicit parseAs wins over auto-detect", async () => {
12
+ // argv would auto-detect as ruff-json, but parseAs overrides
13
+ const parser = await resolveParser({
14
+ cwd: "/project",
15
+ parseAs: "eslint-json",
16
+ argv: ["ruff", "check", "--output-format=json"],
17
+ registrations: [],
18
+ });
19
+ expect(parser.id).toBe("eslint-json");
20
+ });
21
+
22
+ it("project registration wins over auto-detect", async () => {
23
+ const parser = await resolveParser({
24
+ cwd: "/project",
25
+ argv: ["ruff", "check", "--output-format=json"],
26
+ registrations: [{ id: "custom", match: { argvIncludes: ["ruff"] }, parseAs: "eslint-json" }],
27
+ });
28
+ expect(parser.id).toBe("eslint-json");
29
+ });
30
+
31
+ it("falls back to tail-fallback when nothing matches", async () => {
32
+ const parser = await resolveParser({ cwd: "/project", argv: ["unknown-tool"], registrations: [] });
33
+ expect(parser.id).toBe("tail-fallback");
34
+ });
35
+ });
36
+
37
+ describe("AUTO_DETECT", () => {
38
+ describe("hasFlag correctness — no false positives from bare value tokens", () => {
39
+ it("eslint -f json matches", async () => {
40
+ expect(await detect(["eslint", "src/", "-f", "json"])).toBe("eslint-json");
41
+ });
42
+
43
+ it("eslint without -f json does not match", async () => {
44
+ expect(await detect(["eslint", "src/"])).toBe("tail-fallback");
45
+ });
46
+
47
+ it("ruff --output-format=json (joined) matches", async () => {
48
+ expect(await detect(["ruff", "check", "--output-format=json"])).toBe("ruff-json");
49
+ });
50
+
51
+ it("ruff --output-format json (split) matches", async () => {
52
+ expect(await detect(["ruff", "check", "--output-format", "json"])).toBe("ruff-json");
53
+ });
54
+
55
+ it("ruff without --output-format does not match", async () => {
56
+ expect(await detect(["ruff", "check"])).toBe("tail-fallback");
57
+ });
58
+
59
+ it("mocha --reporter=json matches", async () => {
60
+ expect(await detect(["mocha", "--reporter=json"])).toBe("mocha-json");
61
+ });
62
+
63
+ it("mocha --reporter json (split) matches", async () => {
64
+ expect(await detect(["mocha", "--reporter", "json"])).toBe("mocha-json");
65
+ });
66
+
67
+ it("mocha with json in path does NOT false-positive", async () => {
68
+ expect(await detect(["mocha", "test/json/"])).toBe("tail-fallback");
69
+ });
70
+
71
+ it("rubocop --format=json matches", async () => {
72
+ expect(await detect(["rubocop", "--format=json"])).toBe("rubocop-json");
73
+ });
74
+
75
+ it("rubocop --format progress does NOT false-positive", async () => {
76
+ expect(await detect(["rubocop", "--format", "progress"])).toBe("tail-fallback");
77
+ });
78
+
79
+ it("hadolint --format json (split) matches", async () => {
80
+ expect(await detect(["hadolint", "--format", "json", "Dockerfile"])).toBe("hadolint-json");
81
+ });
82
+
83
+ it("hadolint without --format does NOT match", async () => {
84
+ expect(await detect(["hadolint", "Dockerfile"])).toBe("tail-fallback");
85
+ });
86
+
87
+ it("tsc --pretty false (split) matches", async () => {
88
+ expect(await detect(["tsc", "--pretty", "false"])).toBe("tsc-text");
89
+ });
90
+
91
+ it("tsc --pretty=false (joined) matches", async () => {
92
+ expect(await detect(["tsc", "--pretty=false"])).toBe("tsc-text");
93
+ });
94
+
95
+ it("tsc without --pretty does NOT match", async () => {
96
+ expect(await detect(["tsc"])).toBe("tail-fallback");
97
+ });
98
+
99
+ it("mypy --output=json matches", async () => {
100
+ expect(await detect(["mypy", "--output=json", "src/"])).toBe("mypy-json");
101
+ });
102
+
103
+ it("mypy --output html does NOT false-positive", async () => {
104
+ expect(await detect(["mypy", "--output", "html", "src/"])).toBe("tail-fallback");
105
+ });
106
+
107
+ it("pylint --output-format=json matches", async () => {
108
+ expect(await detect(["pylint", "--output-format=json", "src/"])).toBe("pylint-json");
109
+ });
110
+
111
+ it("shellcheck --format=json matches", async () => {
112
+ expect(await detect(["shellcheck", "--format=json", "script.sh"])).toBe("shellcheck-json");
113
+ });
114
+
115
+ it("stylelint --formatter=json matches", async () => {
116
+ expect(await detect(["stylelint", "--formatter=json", "src/"])).toBe("stylelint-json");
117
+ });
118
+
119
+ it("dbt run --log-format=json matches", async () => {
120
+ expect(await detect(["dbt", "run", "--log-format=json"])).toBe("dbt-json");
121
+ });
122
+
123
+ it("dbt run --log-format json (split) matches", async () => {
124
+ expect(await detect(["dbt", "run", "--log-format", "json"])).toBe("dbt-json");
125
+ });
126
+
127
+ it("dbt run without --log-format does NOT match", async () => {
128
+ expect(await detect(["dbt", "run"])).toBe("tail-fallback");
129
+ });
130
+ });
131
+
132
+ describe("remaining flag-based detectors", () => {
133
+ it("rspec --format=json matches", async () => {
134
+ expect(await detect(["rspec", "--format=json"])).toBe("rspec-json");
135
+ });
136
+
137
+ it("cargo build --message-format=json matches", async () => {
138
+ expect(await detect(["cargo", "build", "--message-format=json"])).toBe("cargo-build");
139
+ });
140
+
141
+ it("pytest --junitxml matches junit-xml", async () => {
142
+ expect(await detect(["pytest", "--junitxml=report.xml"])).toBe("junit-xml");
143
+ });
144
+ });
145
+
146
+ describe("non-flag-based detectors still work", () => {
147
+ it("cargo test matches", async () => {
148
+ expect(await detect(["cargo", "test"])).toBe("cargo-test");
149
+ });
150
+
151
+ it("go test -json matches", async () => {
152
+ expect(await detect(["go", "test", "-json", "./..."])).toBe("go-test-json");
153
+ });
154
+
155
+ it("ava matches", async () => {
156
+ expect(await detect(["ava"])).toBe("ava-text");
157
+ });
158
+
159
+ it("swiftc -typecheck matches", async () => {
160
+ expect(await detect(["swiftc", "-typecheck", "main.swift"])).toBe("swiftc-text");
161
+ });
162
+
163
+ it("python3 -m unittest matches", async () => {
164
+ expect(await detect(["python3", "-m", "unittest"])).toBe("unittest-text");
165
+ });
166
+
167
+ it("vitest --reporter=json matches", async () => {
168
+ expect(await detect(["vitest", "run", "--reporter=json"])).toBe("vitest-json");
169
+ });
170
+ });
171
+ });
@@ -8,6 +8,19 @@ import minitestText from "../parsers/minitest-text";
8
8
  import junitXml from "../parsers/junit-xml";
9
9
  import cargoBuild from "../parsers/cargo-build";
10
10
  import cargoTest from "../parsers/cargo-test";
11
+ import dbtJson from "../parsers/dbt-json";
12
+ import mypyJson from "../parsers/mypy-json";
13
+ import tscText from "../parsers/tsc-text";
14
+ import pylintJson from "../parsers/pylint-json";
15
+ import shellcheckJson from "../parsers/shellcheck-json";
16
+ import rubocopJson from "../parsers/rubocop-json";
17
+ import swiftcText from "../parsers/swiftc-text";
18
+ import hadolintJson from "../parsers/hadolint-json";
19
+ import stylelintJson from "../parsers/stylelint-json";
20
+ import mochaJson from "../parsers/mocha-json";
21
+ import unittestText from "../parsers/unittest-text";
22
+ import goTestJson from "../parsers/go-test-json";
23
+ import avaText from "../parsers/ava-text";
11
24
  import tailFallback from "../parsers/tail-fallback";
12
25
 
13
26
  const builtIns: Record<string, ParserModule> = {
@@ -19,31 +32,51 @@ const builtIns: Record<string, ParserModule> = {
19
32
  "junit-xml": junitXml,
20
33
  "cargo-build": cargoBuild,
21
34
  "cargo-test": cargoTest,
35
+ "dbt-json": dbtJson,
36
+ "mypy-json": mypyJson,
37
+ "tsc-text": tscText,
38
+ "pylint-json": pylintJson,
39
+ "shellcheck-json": shellcheckJson,
40
+ "rubocop-json": rubocopJson,
41
+ "swiftc-text": swiftcText,
42
+ "hadolint-json": hadolintJson,
43
+ "stylelint-json": stylelintJson,
44
+ "mocha-json": mochaJson,
45
+ "unittest-text": unittestText,
46
+ "go-test-json": goTestJson,
47
+ "ava-text": avaText,
22
48
  "tail-fallback": tailFallback,
23
49
  };
24
50
 
51
+ /**
52
+ * Check whether argv contains `--flag=value` (joined) or `--flag value` (adjacent).
53
+ * Avoids false positives from bare `value` tokens appearing elsewhere in argv.
54
+ */
55
+ function hasFlag(argv: string[], flag: string, value: string): boolean {
56
+ if (argv.includes(`${flag}=${value}`)) return true;
57
+ for (let i = 0; i < argv.length - 1; i++) {
58
+ if (argv[i] === flag && argv[i + 1] === value) return true;
59
+ }
60
+ return false;
61
+ }
62
+
25
63
  /** Built-in detection patterns — fire when no explicit parseAs or project registration matched. */
26
64
  const AUTO_DETECT: Array<{ parserId: string; detect: (argv: string[]) => boolean }> = [
27
65
  {
28
66
  parserId: "eslint-json",
29
- detect: (argv) => argv.includes("eslint") && argv.includes("-f") && argv.includes("json"),
67
+ detect: (argv) => argv.includes("eslint") && hasFlag(argv, "-f", "json"),
30
68
  },
31
69
  {
32
70
  parserId: "ruff-json",
33
- detect: (argv) =>
34
- argv.includes("ruff") &&
35
- argv.some((a) => a === "--output-format=json" || a === "json") &&
36
- (argv.includes("--output-format=json") || argv.includes("--output-format")),
71
+ detect: (argv) => argv.includes("ruff") && hasFlag(argv, "--output-format", "json"),
37
72
  },
38
73
  {
39
74
  parserId: "vitest-json",
40
- detect: (argv) => argv.includes("vitest") && argv.includes("--reporter=json"),
75
+ detect: (argv) => argv.includes("vitest") && hasFlag(argv, "--reporter", "json"),
41
76
  },
42
77
  {
43
78
  parserId: "rspec-json",
44
- detect: (argv) =>
45
- argv.includes("rspec") &&
46
- (argv.includes("--format=json") || (argv.includes("--format") && argv.includes("json"))),
79
+ detect: (argv) => argv.includes("rspec") && hasFlag(argv, "--format", "json"),
47
80
  },
48
81
  {
49
82
  parserId: "junit-xml",
@@ -52,15 +85,68 @@ const AUTO_DETECT: Array<{ parserId: string; detect: (argv: string[]) => boolean
52
85
  },
53
86
  {
54
87
  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"),
88
+ detect: (argv) => argv.includes("cargo") && argv.includes("build") && hasFlag(argv, "--message-format", "json"),
59
89
  },
60
90
  {
61
91
  parserId: "cargo-test",
62
92
  detect: (argv) => argv.includes("cargo") && argv.includes("test"),
63
93
  },
94
+ {
95
+ parserId: "dbt-json",
96
+ detect: (argv) =>
97
+ argv.includes("dbt") &&
98
+ (argv.includes("run") || argv.includes("test") || argv.includes("compile")) &&
99
+ hasFlag(argv, "--log-format", "json"),
100
+ },
101
+ {
102
+ parserId: "mypy-json",
103
+ detect: (argv) => argv.includes("mypy") && hasFlag(argv, "--output", "json"),
104
+ },
105
+ {
106
+ parserId: "tsc-text",
107
+ detect: (argv) => argv.includes("tsc") && hasFlag(argv, "--pretty", "false"),
108
+ },
109
+ {
110
+ parserId: "pylint-json",
111
+ detect: (argv) => argv.includes("pylint") && hasFlag(argv, "--output-format", "json"),
112
+ },
113
+ {
114
+ parserId: "shellcheck-json",
115
+ detect: (argv) => argv.includes("shellcheck") && hasFlag(argv, "--format", "json"),
116
+ },
117
+ {
118
+ parserId: "rubocop-json",
119
+ detect: (argv) => argv.includes("rubocop") && hasFlag(argv, "--format", "json"),
120
+ },
121
+ {
122
+ parserId: "swiftc-text",
123
+ detect: (argv) => argv.includes("swiftc") && argv.includes("-typecheck"),
124
+ },
125
+ {
126
+ parserId: "hadolint-json",
127
+ detect: (argv) => argv.includes("hadolint") && hasFlag(argv, "--format", "json"),
128
+ },
129
+ {
130
+ parserId: "stylelint-json",
131
+ detect: (argv) => argv.includes("stylelint") && hasFlag(argv, "--formatter", "json"),
132
+ },
133
+ {
134
+ parserId: "mocha-json",
135
+ detect: (argv) => argv.includes("mocha") && hasFlag(argv, "--reporter", "json"),
136
+ },
137
+ {
138
+ parserId: "unittest-text",
139
+ detect: (argv) =>
140
+ argv.includes("unittest") || (argv.includes("python3") && argv.includes("-m") && argv.includes("unittest")),
141
+ },
142
+ {
143
+ parserId: "go-test-json",
144
+ detect: (argv) => argv.includes("go") && argv.includes("test") && argv.includes("-json"),
145
+ },
146
+ {
147
+ parserId: "ava-text",
148
+ detect: (argv) => argv.includes("ava"),
149
+ },
64
150
  ];
65
151
 
66
152
  export function listParsers(): { id: string; autoDetect: boolean }[] {
@@ -1,3 +1,6 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
1
4
  import { describe, it, expect } from "vitest";
2
5
  import { stripCdPrefix, formatResult, finalizeResult } from "./index";
3
6
 
@@ -95,4 +98,55 @@ describe("finalizeResult", () => {
95
98
  );
96
99
  expect(result.cwd).toBe("/project");
97
100
  });
101
+
102
+ it("appends rawTail when parser reports failures but extracts no details", () => {
103
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "finalize-test-"));
104
+ const logPath = path.join(dir, "combined.log");
105
+ fs.writeFileSync(logPath, "line1\nline2\nFAIL: something broke\n");
106
+ const result = finalizeResult(
107
+ { tool: "ava", status: "fail", summary: "2 failed, 1 passed", failures: [] },
108
+ 1,
109
+ logPath,
110
+ "/project"
111
+ );
112
+ expect(result.rawTail).toContain("FAIL: something broke");
113
+ });
114
+
115
+ it("does not overwrite rawTail when parser already set it", () => {
116
+ const result = finalizeResult(
117
+ { tool: "dbt", status: "fail", summary: "1 error", failures: [], rawTail: "SELECT * FROM ..." },
118
+ 1,
119
+ "/nonexistent/log",
120
+ "/project"
121
+ );
122
+ expect(result.rawTail).toBe("SELECT * FROM ...");
123
+ });
124
+ });
125
+
126
+ describe("formatResult safety net", () => {
127
+ it("surfaces log path and rawTail when failures detected but no details parsed", () => {
128
+ const result = formatResult({
129
+ tool: "ava",
130
+ exitCode: 1,
131
+ status: "fail",
132
+ summary: "2 failed, 1 passed",
133
+ failures: [],
134
+ logPath: "/tmp/ava-run.log",
135
+ rawTail: "FAIL: test_multiply\nexpected 99, got 12",
136
+ });
137
+ expect(result).toContain("log: /tmp/ava-run.log");
138
+ expect(result).toContain("expected 99, got 12");
139
+ });
140
+
141
+ it("does not surface log path when failures have details", () => {
142
+ const result = formatResult({
143
+ tool: "ava",
144
+ exitCode: 1,
145
+ status: "fail",
146
+ summary: "1 failed",
147
+ failures: [{ id: "test1", file: "test.js", line: 5, message: "boom" }],
148
+ logPath: "/tmp/ava-run.log",
149
+ });
150
+ expect(result).not.toContain("log:");
151
+ });
98
152
  });
@@ -8,6 +8,7 @@ import type { ObservedRunArgs, ParsedResult, RunContext } from "./types";
8
8
  import { ensureRunDir, writeRunArtifacts } from "./storage/log-store";
9
9
  import { loadProjectConfig } from "./config/project-config";
10
10
  import { resolveParser, listParsers } from "./config/registry";
11
+ import { safeReadFile } from "./parsers/utils";
11
12
 
12
13
  export default function structuredReturn(pi: ExtensionAPI) {
13
14
  pi.registerCommand("sr-parsers", {
@@ -41,19 +42,14 @@ export default function structuredReturn(pi: ExtensionAPI) {
41
42
  },
42
43
  });
43
44
 
44
- pi.on("before_agent_start", async (event) => {
45
- return {
46
- systemPrompt:
47
- event.systemPrompt +
48
- "\n\nWhen running lint, test, build, or other shell commands, load and follow the `structured-return` skill before choosing how to invoke them.",
49
- };
50
- });
51
-
52
45
  pi.registerTool({
53
46
  name: "structured_return",
54
47
  label: "Structured Return",
55
48
  description:
56
49
  "Run a command, store full logs, apply an explicit or registered parser when available, and fall back to tail + log path.",
50
+ promptGuidelines: [
51
+ "Prefer structured_return over bash for test suites, linters, type checkers, and build commands - it returns compact results. Check the structured-return skill for the right flags and parseAs value for each tool.",
52
+ ],
57
53
  parameters: Type.Object({
58
54
  command: Type.String(),
59
55
  cwd: Type.Optional(Type.String()),
@@ -112,6 +108,12 @@ export function formatResult(result: ParsedResult): string {
112
108
  lines.push(` ${location} ${msgLines[0]}${rule}`);
113
109
  for (const extra of msgLines.slice(1)) lines.push(` ${extra}`);
114
110
  }
111
+ // If the parser detected failures but couldn't extract details, surface the
112
+ // log path and raw tail so the model has a path forward instead of a dead end.
113
+ if (result.status === "fail" && (result.failures ?? []).length === 0) {
114
+ if (result.logPath) lines.push(`log: ${result.logPath}`);
115
+ if (result.rawTail) lines.push(result.rawTail);
116
+ }
115
117
  return lines.join("\n");
116
118
  }
117
119
 
@@ -157,5 +159,14 @@ export function finalizeResult(
157
159
  logPath,
158
160
  };
159
161
  }
160
- return { ...result, exitCode, cwd, logPath };
162
+ const finalized: ParsedResult = { ...result, exitCode, cwd, logPath };
163
+ // Safety net: if the parser reports failures but couldn't extract any details
164
+ // (e.g., tool output format changed), append the log tail so the model isn't
165
+ // left with "2 failed" and nothing actionable.
166
+ if (finalized.status === "fail" && (finalized.failures ?? []).length === 0 && !finalized.rawTail) {
167
+ const log = safeReadFile(logPath);
168
+ const lines = log.split(/\r?\n/);
169
+ finalized.rawTail = lines.slice(-200).join("\n");
170
+ }
171
+ return finalized;
161
172
  }