@robhowley/pi-structured-return 1.5.0 → 1.6.1

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 (34) hide show
  1. package/README.md +86 -63
  2. package/extensions/structured-return/src/config/registry.ts +92 -0
  3. package/extensions/structured-return/src/parsers/bandit-json.test.ts +90 -0
  4. package/extensions/structured-return/src/parsers/bandit-json.ts +78 -0
  5. package/extensions/structured-return/src/parsers/black-text.test.ts +67 -0
  6. package/extensions/structured-return/src/parsers/black-text.ts +74 -0
  7. package/extensions/structured-return/src/parsers/clang-text.test.ts +61 -0
  8. package/extensions/structured-return/src/parsers/clang-text.ts +59 -0
  9. package/extensions/structured-return/src/parsers/dotnet-build-text.test.ts +85 -0
  10. package/extensions/structured-return/src/parsers/dotnet-build-text.ts +48 -0
  11. package/extensions/structured-return/src/parsers/htmlhint-json.test.ts +72 -0
  12. package/extensions/structured-return/src/parsers/htmlhint-json.ts +72 -0
  13. package/extensions/structured-return/src/parsers/isort-text.test.ts +58 -0
  14. package/extensions/structured-return/src/parsers/isort-text.ts +64 -0
  15. package/extensions/structured-return/src/parsers/javac-text.test.ts +75 -0
  16. package/extensions/structured-return/src/parsers/javac-text.ts +81 -0
  17. package/extensions/structured-return/src/parsers/jsonlint-text.test.ts +52 -0
  18. package/extensions/structured-return/src/parsers/jsonlint-text.ts +64 -0
  19. package/extensions/structured-return/src/parsers/markdownlint-json.test.ts +76 -0
  20. package/extensions/structured-return/src/parsers/markdownlint-json.ts +73 -0
  21. package/extensions/structured-return/src/parsers/node-test-text.test.ts +117 -0
  22. package/extensions/structured-return/src/parsers/node-test-text.ts +90 -0
  23. package/extensions/structured-return/src/parsers/npm-audit-json.test.ts +83 -0
  24. package/extensions/structured-return/src/parsers/npm-audit-json.ts +88 -0
  25. package/extensions/structured-return/src/parsers/prettier-text.test.ts +76 -0
  26. package/extensions/structured-return/src/parsers/prettier-text.ts +63 -0
  27. package/extensions/structured-return/src/parsers/pyright-json.test.ts +112 -0
  28. package/extensions/structured-return/src/parsers/pyright-json.ts +81 -0
  29. package/extensions/structured-return/src/parsers/tidy-text.test.ts +74 -0
  30. package/extensions/structured-return/src/parsers/tidy-text.ts +67 -0
  31. package/extensions/structured-return/src/parsers/vale-json.test.ts +84 -0
  32. package/extensions/structured-return/src/parsers/vale-json.ts +80 -0
  33. package/package.json +8 -3
  34. package/skills/structured-return/SKILL.md +58 -6
package/README.md CHANGED
@@ -1,10 +1,8 @@
1
1
  # pi-structured-return
2
2
 
3
- Structured command execution for Pi agents: compact results for the model, full logs for humans.
3
+ A [Pi](https://pi.dev/) extension that adds a `structured_return` tool alongside `bash`, returning compact parsed results with full logs — 60–95% fewer tokens without losing signal.
4
4
 
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.
6
-
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.
5
+ A failing test run, before and after:
8
6
 
9
7
  **Raw pytest output (262 tokens):**
10
8
  ```
@@ -46,7 +44,17 @@ pytest test_math.py --junitxml=.tmp/report.xml → cwd: project
46
44
  test_math.py:8 ZeroDivisionError: division by zero
47
45
  ```
48
46
 
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.
47
+ 262 → 56 tokens on a 3-test example. Real test suites are much larger — the reduction scales with them, saving thousands of tokens per run.
48
+
49
+ ## Installation
50
+
51
+ ```bash
52
+ pi install npm:@robhowley/pi-structured-return
53
+ ```
54
+
55
+ ## Design
56
+
57
+ `structured_return` is a separate tool, not a wrapper around `bash`. Intercepting `bash` to silently rewrite commands would override a primitive the model and platform both rely on. Pi's philosophy is to extend rather than obfuscate: features are built on top of the platform, not hidden inside it. A dedicated tool honors that. It adds to the available surface, keeps `bash` honest, and leaves the choice explicit. The skill guides the model toward it; nothing is hijacked to get there.
50
58
 
51
59
  ## Token reduction
52
60
 
@@ -56,41 +64,66 @@ Measured with `cl100k_base` (tiktoken). All benchmarks use tiny fixtures — red
56
64
 
57
65
  Benchmark: 3 tests — 1 passing, 1 assertion failure, 1 unexpected error.
58
66
 
59
- | Parser | Raw | Structured | Reduction | Notes |
67
+ | Tool | Raw | Structured | Reduction | Notes |
60
68
  |---|---|---|---|---|
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
69
+ | `mvn test` | 1063 | 86 | **92%** | build lifecycle noise with surefire stack traces per failure |
70
+ | `node --test` | 629 | 64 | **90%** | strips full stack traces, assertion internals, timing; preserves expected/actual |
71
+ | `npx ava` | 483 | 56 | **88%** | source snippets, diffs, full stack traces stripped; expected/actual preserved |
72
+ | `go test` | 394 | 48 | **88%** | stack traces, goroutine frames, panic recovery noise stripped; file:line + expected/actual preserved |
73
+ | `dotnet test` | 487 | 107 | **78%** | build header and VSTest output with per-failure stack traces |
74
+ | `npx vitest` | 348 | 75 | **78%** | source diff with inline arrows and ANSI color codes per failure |
75
+ | `python -m unittest` | 231 | 52 | **78%** | full tracebacks with source annotations; expected/actual from AssertionError |
76
+ | `cargo test` | 285 | 68 | **76%** | cargo progress + test binary output with panic traces per failure |
77
+ | `pytest` | 289 | 71 | **75%** | verbose output with source snippets and summary footer |
78
+ | `rspec` | 212 | 55 | **74%** | default output with backtrace |
79
+ | `gradle test` | 263 | 81 | **69%** | gradle console output with build lifecycle noise |
80
+ | `npx mocha` | 180 | 55 | **69%** | stack traces + assertion diff formatting; expected/actual preserved |
81
+ | `npx jest` | 309 | 99 | **68%** | source annotations with deep jest-circus stack traces per failure |
82
+ | `ruby` (minitest) | 168 | 59 | **65%** | default output with backtrace |
83
+
84
+ ### Build tools and compilers
85
+
86
+ Benchmark: 1 file, 1–2 errors. Reduction scales with error count since raw output includes source snippets, caret indicators, and annotations per error.
87
+
88
+ | Tool | Raw | Structured | Reduction | Notes |
89
+ |---|---|---|---|---|
90
+ | `dotnet build` | 383 | 53 | **86%** | strips restore/timing noise, deduplicates repeated error lines, absolute paths relativized |
91
+ | `npx jsonlint` | 148 | 28 | **81%** | strips stack trace, source pointer line; preserves line number and expecting message |
92
+ | `tidy` | 233 | 51 | **78%** | strips remediation advice, accessibility tips, reformatted HTML output, Info lines |
93
+ | `cargo build` | 225 | 77 | **66%** | rustc error annotations with code spans and help text per error |
94
+ | `swiftc` | 161 | 58 | **64%** | source annotations with backtick markers deduplicated |
95
+ | `gcc` / `clang` | 109 | 77 | **29%** | strips source snippets, caret indicators, line numbers from gutter |
96
+ | `javac` | 79 | 66 | **16%** | strips source snippets, caret indicators; folds symbol/location into message |
97
+
98
+ ### Linters and type checkers
77
99
 
78
100
  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
101
 
80
- | Parser | Raw | Structured | Reduction | Notes |
102
+ | Tool | Raw | Structured | Reduction | Notes |
81
103
  |---|---|---|---|---|
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 |
104
+ | `isort --check` | 143 | 29 | **80%** | strips diff hunks, absolute paths, timestamps; lists files with unsorted imports |
105
+ | `black --check` | 155 | 31 | **80%** | strips diff hunks, emoji, timestamps; lists files needing reformatting |
106
+ | `ruff check` | 107 | 52 | **51%** | source context + help text per error |
107
+ | `shellcheck` | 224 | 117 | **48%** | strips source snippets, carets, suggestions, wiki URLs |
108
+ | `npx htmlhint` | 174 | 92 | **47%** | strips ANSI codes, source evidence, rule descriptions, URLs |
109
+ | `vale` | 141 | 79 | **44%** | strips ANSI codes, Action/Span metadata, column-aligned formatting |
110
+ | `markdownlint` | 199 | 117 | **41%** | strips context quotes, URLs, fix info, error ranges |
111
+ | `pyright` | 100 | 59 | **41%** | strips version, timing, absolute paths; detail lines collapsed |
112
+ | `rubocop` | 149 | 90 | **40%** | strips source snippets, caret indicators, summary line |
113
+ | `tsc` | 107 | 72 | **33%** | vs `--pretty true` default; source snippets and underlines stripped |
114
+ | `stylelint` | 70 | 51 | **27%** | strips summary footer and fix hint |
115
+ | `pylint` | 141 | 120 | **15%** | strips header, score line, separator; scales with error count |
116
+ | `prettier --check` | 38 | 33 | **13%** | strips preamble, [warn] prefixes, footer hint; scales with file count |
117
+ | `hadolint` | 178 | 156 | **12%** | strips ANSI color codes and level labels; measured vs colored output |
118
+ | `eslint` | 64 | 59 | **8%** | already compact formatter |
119
+ | `mypy` | 75 | 72 | **4%** | mypy text is already compact; notes folded into parent errors |
120
+
121
+ ### Security and audit
122
+
123
+ | Tool | Raw | Structured | Reduction | Notes |
124
+ |---|---|---|---|---|
125
+ | `bandit` | 402 | 99 | **75%** | strips source snippets, CWE URLs, run metrics, confidence labels |
126
+ | `npm audit` | 158 | 50 | **68%** | strips advisory URLs, fix instructions, CVSS vectors; advisory titles joined per package |
94
127
 
95
128
  ### Pipeline tools
96
129
 
@@ -98,35 +131,28 @@ dbt output is the noisiest tool in this repo relative to useful signal. Every ru
98
131
 
99
132
  The numbers below use 3–4 model toy examples; real projects run hundreds of models where the noise scales linearly and reduction compounds.
100
133
 
101
- | Parser | Raw | Structured | Reduction | Notes |
134
+ | Tool | Raw | Structured | Reduction | Notes |
102
135
  |---|---|---|---|---|
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 |
136
+ | `dbt run` (success) | 428 | 20 | **95%** | version, adapter, concurrency, per-model start/finish — all noise on success |
137
+ | `dbt run` (failure) | 618 | 198 | **68%** | error messages, model paths, compiled code paths preserved |
138
+ | `dbt test` | 720 | 274 | **62%** | unit test diff tables preserved verbatim; preamble stripped |
139
+ | `dbt compile` | 775 | 683 | **12%** | compiled SQL is the signal and returned verbatim |
107
140
 
108
141
  At 12 models, run failures hit 85% reduction. An 18-model DAG success: 1,645 → 20 tokens (99%).
109
142
 
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`
143
+ ### Already compact — use `bash` directly
113
144
 
114
- **Linters & type checkers:** `ruff-json`, `eslint-json`, `mypy-json`, `tsc-text`, `pylint-json`, `shellcheck-json`, `rubocop-json`, `swiftc-text`, `hadolint-json`, `stylelint-json`
145
+ Evaluated for structured parsing but raw output is already compact enough that a parser adds no reduction (or goes negative). Use `bash` instead of `structured_return` for these tools.
115
146
 
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
-
123
- ## Installation
124
-
125
- Install the skill and extension:
126
-
127
- ```bash
128
- pi install npm:@robhowley/pi-structured-return
129
- ```
147
+ | Tool | Raw tokens | Format | Why no parser |
148
+ |---|---|---|---|
149
+ | `go build` | 85 | `file:line:col: message` | one line per error, no decoration |
150
+ | `flake8` | 75 | `file:line:col: CODE message` | no JSON without a plugin; text is already one line per violation |
151
+ | `yamllint` | 72 | `file:line:col level message (rule)` | filename printed once; one line per issue |
152
+ | `golangci-lint` | 59 | `file:line:col: message (linter)` | text output already minimal; JSON includes massive linter report |
153
+ | `go vet` | ~60 | `file:line:col: message` | same format as `go build` |
154
+ | `vulture` | 58 | `file:line: message (confidence%)` | single line per finding |
155
+ | `pydocstyle` | 48 | `file:line context + CODE: message` | two lines per issue; structured format would repeat file paths |
130
156
 
131
157
  ## How it works
132
158
 
@@ -136,6 +162,8 @@ pi install npm:@robhowley/pi-structured-return
136
162
  4. The agent receives the structured result in context — signal only, no noise.
137
163
  5. The full log is always available on disk for both the agent and humans to inspect.
138
164
 
165
+ Run `/sr-parsers` in a pi session to see all registered parsers with their match rules.
166
+
139
167
  ## Extending with project-local parsers
140
168
 
141
169
  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.
@@ -215,8 +243,3 @@ Every parser returns the same shape. The model always knows where to look.
215
243
  | `artifact` | `string?` | Path to the saved report file, if one was written |
216
244
  | `logPath` | `string` | Path to full stdout+stderr log |
217
245
  | `rawTail` | `string?` | Last 200 lines of log, included on fallback when no parser matched |
218
-
219
- ## Design
220
-
221
- `structured_return` is a separate tool, not a wrapper around `bash`. Intercepting `bash` to silently rewrite commands would override a primitive the model and platform both rely on. Pi's philosophy is to extend rather than obfuscate: features are built on top of the platform, not hidden inside it. A dedicated tool honors that. It adds to the available surface, keeps `bash` honest, and leaves the choice explicit. The skill guides the model toward it; nothing is hijacked to get there.
222
-
@@ -21,6 +21,21 @@ import mochaJson from "../parsers/mocha-json";
21
21
  import unittestText from "../parsers/unittest-text";
22
22
  import goTestJson from "../parsers/go-test-json";
23
23
  import avaText from "../parsers/ava-text";
24
+ import pyrightJson from "../parsers/pyright-json";
25
+ import banditJson from "../parsers/bandit-json";
26
+ import javacText from "../parsers/javac-text";
27
+ import dotnetBuildText from "../parsers/dotnet-build-text";
28
+ import clangText from "../parsers/clang-text";
29
+ import nodeTestText from "../parsers/node-test-text";
30
+ import blackText from "../parsers/black-text";
31
+ import markdownlintJson from "../parsers/markdownlint-json";
32
+ import prettierText from "../parsers/prettier-text";
33
+ import valeJson from "../parsers/vale-json";
34
+ import tidyText from "../parsers/tidy-text";
35
+ import jsonlintText from "../parsers/jsonlint-text";
36
+ import npmAuditJson from "../parsers/npm-audit-json";
37
+ import isortText from "../parsers/isort-text";
38
+ import htmlhintJson from "../parsers/htmlhint-json";
24
39
  import tailFallback from "../parsers/tail-fallback";
25
40
 
26
41
  const builtIns: Record<string, ParserModule> = {
@@ -45,6 +60,21 @@ const builtIns: Record<string, ParserModule> = {
45
60
  "unittest-text": unittestText,
46
61
  "go-test-json": goTestJson,
47
62
  "ava-text": avaText,
63
+ "pyright-json": pyrightJson,
64
+ "bandit-json": banditJson,
65
+ "javac-text": javacText,
66
+ "dotnet-build-text": dotnetBuildText,
67
+ "clang-text": clangText,
68
+ "node-test-text": nodeTestText,
69
+ "black-text": blackText,
70
+ "markdownlint-json": markdownlintJson,
71
+ "prettier-text": prettierText,
72
+ "vale-json": valeJson,
73
+ "tidy-text": tidyText,
74
+ "jsonlint-text": jsonlintText,
75
+ "npm-audit-json": npmAuditJson,
76
+ "isort-text": isortText,
77
+ "htmlhint-json": htmlhintJson,
48
78
  "tail-fallback": tailFallback,
49
79
  };
50
80
 
@@ -147,6 +177,68 @@ const AUTO_DETECT: Array<{ parserId: string; detect: (argv: string[]) => boolean
147
177
  parserId: "ava-text",
148
178
  detect: (argv) => argv.includes("ava"),
149
179
  },
180
+ {
181
+ parserId: "pyright-json",
182
+ detect: (argv) => argv.includes("pyright") && argv.includes("--outputjson"),
183
+ },
184
+ {
185
+ parserId: "bandit-json",
186
+ detect: (argv) => argv.includes("bandit") && hasFlag(argv, "-f", "json"),
187
+ },
188
+ {
189
+ parserId: "javac-text",
190
+ detect: (argv) => argv.includes("javac") && !argv.includes("-version"),
191
+ },
192
+ {
193
+ parserId: "dotnet-build-text",
194
+ detect: (argv) => argv.includes("dotnet") && argv.includes("build"),
195
+ },
196
+ {
197
+ parserId: "node-test-text",
198
+ detect: (argv) => argv.includes("node") && argv.includes("--test"),
199
+ },
200
+ {
201
+ parserId: "black-text",
202
+ detect: (argv) => argv.includes("black") && argv.includes("--check"),
203
+ },
204
+ {
205
+ parserId: "markdownlint-json",
206
+ detect: (argv) => argv.includes("markdownlint") && argv.includes("--json"),
207
+ },
208
+ {
209
+ parserId: "prettier-text",
210
+ detect: (argv) => argv.includes("prettier") && argv.includes("--check"),
211
+ },
212
+ {
213
+ parserId: "tidy-text",
214
+ detect: (argv) => argv.includes("tidy"),
215
+ },
216
+ {
217
+ parserId: "jsonlint-text",
218
+ detect: (argv) => argv.includes("jsonlint"),
219
+ },
220
+ {
221
+ parserId: "htmlhint-json",
222
+ detect: (argv) => argv.includes("htmlhint") && hasFlag(argv, "--format", "json"),
223
+ },
224
+ {
225
+ parserId: "isort-text",
226
+ detect: (argv) => argv.includes("isort") && argv.includes("--check"),
227
+ },
228
+ {
229
+ parserId: "npm-audit-json",
230
+ detect: (argv) => argv.includes("npm") && argv.includes("audit") && argv.includes("--json"),
231
+ },
232
+ {
233
+ parserId: "vale-json",
234
+ detect: (argv) => argv.includes("vale") && hasFlag(argv, "--output", "JSON"),
235
+ },
236
+ {
237
+ parserId: "clang-text",
238
+ detect: (argv) =>
239
+ (argv.includes("gcc") || argv.includes("g++") || argv.includes("clang") || argv.includes("clang++")) &&
240
+ (argv.includes("-c") || argv.includes("-o")),
241
+ },
150
242
  ];
151
243
 
152
244
  export function listParsers(): { id: string; autoDetect: boolean }[] {
@@ -0,0 +1,90 @@
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 "./bandit-json";
6
+ import type { RunContext } from "../types";
7
+
8
+ function makeCtx(stdout: string, cwd = "/project"): RunContext {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bandit-test-"));
10
+ const stdoutPath = path.join(dir, "stdout");
11
+ fs.writeFileSync(stdoutPath, stdout);
12
+ return {
13
+ command: "bandit -f json .",
14
+ argv: ["bandit", "-f", "json", "."],
15
+ cwd,
16
+ artifactPaths: [],
17
+ stdoutPath,
18
+ stderrPath: path.join(dir, "stderr"),
19
+ logPath: path.join(dir, "log"),
20
+ };
21
+ }
22
+
23
+ describe("bandit-json parser", () => {
24
+ it("multiple issues → correct severity summary, relative paths, rule includes test_id and test_name", async () => {
25
+ const cwd = "/project";
26
+ const stdout = JSON.stringify({
27
+ results: [
28
+ {
29
+ filename: "/project/src/app.py",
30
+ line_number: 1,
31
+ issue_text: "Consider possible security implications associated with the subprocess module.",
32
+ issue_severity: "LOW",
33
+ issue_confidence: "HIGH",
34
+ test_id: "B404",
35
+ test_name: "blacklist",
36
+ },
37
+ {
38
+ filename: "/project/src/app.py",
39
+ line_number: 4,
40
+ issue_text: "subprocess call with shell=True identified, security issue.",
41
+ issue_severity: "HIGH",
42
+ issue_confidence: "HIGH",
43
+ test_id: "B602",
44
+ test_name: "subprocess_popen_with_shell_equals_true",
45
+ },
46
+ ],
47
+ });
48
+ const result = await parser.parse(makeCtx(stdout, cwd));
49
+ expect(result.status).toBe("fail");
50
+ expect(result.summary).toBe("2 issues (1 high, 1 low)");
51
+ expect(result.failures).toHaveLength(2);
52
+ expect(result.failures![0].file).toBe("src/app.py");
53
+ expect(result.failures![0].rule).toBe("B404:blacklist");
54
+ expect(result.failures![1].rule).toBe("B602:subprocess_popen_with_shell_equals_true");
55
+ });
56
+
57
+ it("no issues → status pass, empty failures", async () => {
58
+ const stdout = JSON.stringify({ results: [] });
59
+ const result = await parser.parse(makeCtx(stdout));
60
+ expect(result.status).toBe("pass");
61
+ expect(result.summary).toBe("no security issues");
62
+ expect(result.failures).toHaveLength(0);
63
+ });
64
+
65
+ it("empty stdout → no crash, status pass", async () => {
66
+ const result = await parser.parse(makeCtx(""));
67
+ expect(result.status).toBe("pass");
68
+ expect(result.failures).toHaveLength(0);
69
+ });
70
+
71
+ it("single high severity issue → singular 'issue' in summary", async () => {
72
+ const stdout = JSON.stringify({
73
+ results: [
74
+ {
75
+ filename: "/project/danger.py",
76
+ line_number: 10,
77
+ issue_text: "Possible hardcoded password.",
78
+ issue_severity: "HIGH",
79
+ issue_confidence: "MEDIUM",
80
+ test_id: "B105",
81
+ test_name: "hardcoded_password_string",
82
+ },
83
+ ],
84
+ });
85
+ const result = await parser.parse(makeCtx(stdout));
86
+ expect(result.status).toBe("fail");
87
+ expect(result.summary).toBe("1 issue (1 high)");
88
+ expect(result.failures).toHaveLength(1);
89
+ });
90
+ });
@@ -0,0 +1,78 @@
1
+ import path from "node:path";
2
+ import type { ParserModule, ParsedFailure } from "../types";
3
+ import { safeReadFile } from "./utils";
4
+
5
+ interface BanditResult {
6
+ filename: string;
7
+ line_number: number;
8
+ issue_text: string;
9
+ issue_severity: string;
10
+ test_id: string;
11
+ test_name: string;
12
+ }
13
+
14
+ interface BanditOutput {
15
+ results?: BanditResult[];
16
+ }
17
+
18
+ const parser: ParserModule = {
19
+ id: "bandit-json",
20
+ async parse(ctx) {
21
+ const stdout = safeReadFile(ctx.stdoutPath).trim();
22
+ if (!stdout) {
23
+ return {
24
+ tool: "bandit",
25
+ status: "pass",
26
+ summary: "no security issues",
27
+ failures: [],
28
+ logPath: ctx.logPath,
29
+ };
30
+ }
31
+
32
+ let output: BanditOutput;
33
+ try {
34
+ output = JSON.parse(stdout);
35
+ } catch {
36
+ return {
37
+ tool: "bandit",
38
+ status: "error",
39
+ summary: "failed to parse bandit JSON output",
40
+ logPath: ctx.logPath,
41
+ };
42
+ }
43
+
44
+ const results = output.results ?? [];
45
+ const failures: ParsedFailure[] = results.map((r) => {
46
+ const relPath = path.relative(ctx.cwd, r.filename);
47
+ return {
48
+ id: `${relPath}:${r.line_number}:${r.test_id}`,
49
+ file: relPath,
50
+ line: r.line_number,
51
+ message: r.issue_text,
52
+ rule: `${r.test_id}:${r.test_name}`,
53
+ };
54
+ });
55
+
56
+ const bySeverity: Record<string, number> = {};
57
+ for (const r of results) {
58
+ const sev = r.issue_severity.toLowerCase();
59
+ bySeverity[sev] = (bySeverity[sev] ?? 0) + 1;
60
+ }
61
+ const sevParts = ["high", "medium", "low"].filter((s) => bySeverity[s]).map((s) => `${bySeverity[s]} ${s}`);
62
+
63
+ const summary =
64
+ results.length > 0
65
+ ? `${results.length} issue${results.length !== 1 ? "s" : ""} (${sevParts.join(", ")})`
66
+ : "no security issues";
67
+
68
+ return {
69
+ tool: "bandit",
70
+ status: failures.length > 0 ? "fail" : "pass",
71
+ summary,
72
+ failures,
73
+ logPath: ctx.logPath,
74
+ };
75
+ },
76
+ };
77
+
78
+ export default parser;
@@ -0,0 +1,67 @@
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 "./black-text";
6
+ import type { RunContext } from "../types";
7
+
8
+ function makeCtx(stdout: string, stderr = "", cwd = "/project"): RunContext {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "black-test-"));
10
+ const stdoutPath = path.join(dir, "stdout");
11
+ const stderrPath = path.join(dir, "stderr");
12
+ fs.writeFileSync(stdoutPath, stdout);
13
+ fs.writeFileSync(stderrPath, stderr);
14
+ return {
15
+ command: "black --check .",
16
+ argv: ["black", "--check", "."],
17
+ cwd,
18
+ artifactPaths: [],
19
+ stdoutPath,
20
+ stderrPath,
21
+ logPath: path.join(dir, "log"),
22
+ };
23
+ }
24
+
25
+ describe("black-text parser", () => {
26
+ it("files needing reformat → strips emoji, lists files, status fail", async () => {
27
+ const cwd = "/project";
28
+ const stderr = `would reformat /project/src/app.py
29
+ would reformat /project/src/utils.py
30
+
31
+ Oh no! 💥 💔 💥
32
+ 2 files would be reformatted.`;
33
+ const result = await parser.parse(makeCtx("", stderr, cwd));
34
+ expect(result.status).toBe("fail");
35
+ expect(result.summary).toBe("2 files would be reformatted");
36
+ expect(result.failures).toHaveLength(2);
37
+ expect(result.failures![0].file).toBe("src/app.py");
38
+ expect(result.failures![1].file).toBe("src/utils.py");
39
+ expect(result.failures![0].message).toBe("would reformat");
40
+ });
41
+
42
+ it("all formatted → status pass", async () => {
43
+ const stderr = `All done! ✨ 🍰 ✨
44
+ 3 files would be left unchanged.`;
45
+ const result = await parser.parse(makeCtx("", stderr));
46
+ expect(result.status).toBe("pass");
47
+ expect(result.summary).toBe("all files formatted");
48
+ expect(result.failures).toHaveLength(0);
49
+ });
50
+
51
+ it("format errors → captured with message", async () => {
52
+ const stderr = `error: cannot format /project/bad.py: Cannot parse: 1:0:
53
+ Oh no! 💥 💔 💥
54
+ 1 file would fail to reformat.`;
55
+ const result = await parser.parse(makeCtx("", stderr));
56
+ expect(result.status).toBe("fail");
57
+ expect(result.failures).toHaveLength(1);
58
+ expect(result.failures![0].file).toBe("bad.py");
59
+ expect(result.failures![0].message).toContain("Cannot parse");
60
+ });
61
+
62
+ it("empty output → no crash, status pass", async () => {
63
+ const result = await parser.parse(makeCtx(""));
64
+ expect(result.status).toBe("pass");
65
+ expect(result.failures).toHaveLength(0);
66
+ });
67
+ });
@@ -0,0 +1,74 @@
1
+ import path from "node:path";
2
+ import type { ParserModule, ParsedFailure } from "../types";
3
+ import { safeReadFile } from "./utils";
4
+
5
+ const REFORMAT_LINE = /^would reformat (.+)$/;
6
+ const ERROR_FORMAT = /^error: cannot format (.+?): (.+)$/;
7
+
8
+ const parser: ParserModule = {
9
+ id: "black-text",
10
+ async parse(ctx) {
11
+ const combined = (safeReadFile(ctx.stdoutPath) + "\n" + safeReadFile(ctx.stderrPath)).trim();
12
+ if (!combined) {
13
+ return {
14
+ tool: "black",
15
+ status: "pass",
16
+ summary: "all files formatted",
17
+ failures: [],
18
+ logPath: ctx.logPath,
19
+ };
20
+ }
21
+
22
+ const lines = combined.split("\n");
23
+ const failures: ParsedFailure[] = [];
24
+ for (const line of lines) {
25
+ const reformatMatch = line.match(REFORMAT_LINE);
26
+ if (reformatMatch) {
27
+ const relPath = path.relative(ctx.cwd, reformatMatch[1]);
28
+ failures.push({
29
+ id: relPath,
30
+ file: relPath,
31
+ message: "would reformat",
32
+ });
33
+ continue;
34
+ }
35
+
36
+ const errorMatch = line.match(ERROR_FORMAT);
37
+ if (errorMatch) {
38
+ const relPath = path.relative(ctx.cwd, errorMatch[1]);
39
+ failures.push({
40
+ id: relPath,
41
+ file: relPath,
42
+ message: errorMatch[2],
43
+ });
44
+ continue;
45
+ }
46
+ }
47
+
48
+ // If "All done!" and no reformats needed
49
+ if (failures.length === 0 && combined.includes("All done!")) {
50
+ return {
51
+ tool: "black",
52
+ status: "pass",
53
+ summary: "all files formatted",
54
+ failures: [],
55
+ logPath: ctx.logPath,
56
+ };
57
+ }
58
+
59
+ const summary =
60
+ failures.length > 0
61
+ ? `${failures.length} file${failures.length !== 1 ? "s" : ""} would be reformatted`
62
+ : "all files formatted";
63
+
64
+ return {
65
+ tool: "black",
66
+ status: failures.length > 0 ? "fail" : "pass",
67
+ summary,
68
+ failures,
69
+ logPath: ctx.logPath,
70
+ };
71
+ },
72
+ };
73
+
74
+ export default parser;