@robhowley/pi-structured-return 1.6.0 → 1.7.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
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
# pi-structured-return
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
|
|
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
|
|
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,55 +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
|
-
|
|
|
67
|
+
| Tool | Raw | Structured | Reduction | Notes |
|
|
68
|
+
|---|---|---|---|---|
|
|
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 |
|
|
60
89
|
|---|---|---|---|---|
|
|
61
|
-
| `
|
|
62
|
-
| `
|
|
63
|
-
| `
|
|
64
|
-
| `
|
|
65
|
-
| `
|
|
66
|
-
| `
|
|
67
|
-
| `
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
| `junit-xml` (pytest) | 289 | 71 | **75%** | verbose output with source snippets and summary footer |
|
|
71
|
-
| `rspec-json` | 212 | 55 | **74%** | default output with backtrace |
|
|
72
|
-
| `junit-xml` (gradle) | 263 | 81 | **69%** | gradle console output with build lifecycle noise |
|
|
73
|
-
| `mocha-json` | 180 | 55 | **69%** | stack traces + assertion diff formatting; expected/actual preserved |
|
|
74
|
-
| `junit-xml` (jest) | 309 | 99 | **68%** | source annotations with deep jest-circus stack traces per failure |
|
|
75
|
-
| `minitest-text` | 168 | 59 | **65%** | default output with backtrace |
|
|
76
|
-
|
|
77
|
-
### Linters, type checkers, and build tools
|
|
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
|
|
78
99
|
|
|
79
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.
|
|
80
101
|
|
|
81
|
-
|
|
|
102
|
+
| Tool | Raw | Structured | Reduction | Notes |
|
|
103
|
+
|---|---|---|---|---|
|
|
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 |
|
|
82
124
|
|---|---|---|---|---|
|
|
83
|
-
| `
|
|
84
|
-
| `
|
|
85
|
-
| `swiftc-text` | 161 | 58 | **64%** | source annotations with backtick markers deduplicated |
|
|
86
|
-
| `ruff-json` | 107 | 52 | **51%** | source context + help text per error |
|
|
87
|
-
| `shellcheck-json` | 224 | 117 | **48%** | strips source snippets, carets, suggestions, wiki URLs |
|
|
88
|
-
| `rubocop-json` | 149 | 90 | **40%** | strips source snippets, caret indicators, summary line |
|
|
89
|
-
| `tsc-text` | 107 | 72 | **33%** | vs `--pretty true` default; source snippets and underlines stripped |
|
|
90
|
-
| `stylelint-json` | 70 | 51 | **27%** | strips summary footer and fix hint |
|
|
91
|
-
| `pylint-json` | 141 | 120 | **15%** | strips header, score line, separator; scales with error count |
|
|
92
|
-
| `hadolint-json` | 178 | 156 | **12%** | strips ANSI color codes and level labels; measured vs colored output |
|
|
93
|
-
| `prettier-text` | 38 | 33 | **13%** | strips preamble, [warn] prefixes, footer hint; scales with file count |
|
|
94
|
-
| `eslint-json` | 64 | 59 | **8%** | already compact formatter |
|
|
95
|
-
| `jsonlint-text` | 148 | 28 | **81%** | strips stack trace, source pointer line; preserves line number and expecting message |
|
|
96
|
-
| `npm-audit-json` | 158 | 50 | **68%** | strips advisory URLs, fix instructions, CVSS vectors; advisory titles joined per package |
|
|
97
|
-
| `isort-text` | 143 | 29 | **80%** | strips diff hunks, absolute paths, timestamps; lists files with unsorted imports |
|
|
98
|
-
| `htmlhint-json` | 174 | 92 | **47%** | strips ANSI codes, source evidence, rule descriptions, URLs |
|
|
99
|
-
| `tidy-text` | 233 | 51 | **78%** | strips remediation advice, accessibility tips, HTML output, Info lines |
|
|
100
|
-
| `bandit-json` | 402 | 99 | **75%** | strips source snippets, CWE URLs, run metrics, confidence labels |
|
|
101
|
-
| `markdownlint-json` | 199 | 117 | **41%** | strips context quotes, URLs, fix info, error ranges |
|
|
102
|
-
| `vale-json` | 141 | 79 | **44%** | strips ANSI codes, Action/Span/Description fields, column-aligned formatting |
|
|
103
|
-
| `pyright-json` | 100 | 59 | **41%** | strips version, timing, absolute paths; detail lines collapsed |
|
|
104
|
-
| `clang-text` | 109 | 77 | **29%** | strips source snippets, caret indicators, line numbers from gutter |
|
|
105
|
-
| `javac-text` | 79 | 66 | **16%** | strips source snippets, caret indicators; folds symbol/location into message |
|
|
106
|
-
| `mypy-json` | 75 | 72 | **4%** | mypy text is already compact; notes folded into parent errors |
|
|
107
|
-
| `black-text` | 155 | 31 | **80%** | strips diff hunks, emoji, timestamps; lists files needing reformatting |
|
|
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 |
|
|
108
127
|
|
|
109
128
|
### Pipeline tools
|
|
110
129
|
|
|
@@ -112,12 +131,12 @@ dbt output is the noisiest tool in this repo relative to useful signal. Every ru
|
|
|
112
131
|
|
|
113
132
|
The numbers below use 3–4 model toy examples; real projects run hundreds of models where the noise scales linearly and reduction compounds.
|
|
114
133
|
|
|
115
|
-
|
|
|
134
|
+
| Tool | Raw | Structured | Reduction | Notes |
|
|
116
135
|
|---|---|---|---|---|
|
|
117
|
-
| `dbt
|
|
118
|
-
| `dbt
|
|
119
|
-
| `dbt
|
|
120
|
-
| `dbt
|
|
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 |
|
|
121
140
|
|
|
122
141
|
At 12 models, run failures hit 85% reduction. An 18-model DAG success: 1,645 → 20 tokens (99%).
|
|
123
142
|
|
|
@@ -131,33 +150,10 @@ Evaluated for structured parsing but raw output is already compact enough that a
|
|
|
131
150
|
| `flake8` | 75 | `file:line:col: CODE message` | no JSON without a plugin; text is already one line per violation |
|
|
132
151
|
| `yamllint` | 72 | `file:line:col level message (rule)` | filename printed once; one line per issue |
|
|
133
152
|
| `golangci-lint` | 59 | `file:line:col: message (linter)` | text output already minimal; JSON includes massive linter report |
|
|
134
|
-
| `go vet` | ~60 | `file:line:col: message` | same format as go build |
|
|
153
|
+
| `go vet` | ~60 | `file:line:col: message` | same format as `go build` |
|
|
135
154
|
| `vulture` | 58 | `file:line: message (confidence%)` | single line per finding |
|
|
136
155
|
| `pydocstyle` | 48 | `file:line context + CODE: message` | two lines per issue; structured format would repeat file paths |
|
|
137
156
|
|
|
138
|
-
## Built-in parsers
|
|
139
|
-
|
|
140
|
-
**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`, `node-test-text`
|
|
141
|
-
|
|
142
|
-
**Linters & type checkers:** `ruff-json`, `eslint-json`, `mypy-json`, `pyright-json`, `tsc-text`, `pylint-json`, `shellcheck-json`, `rubocop-json`, `swiftc-text`, `hadolint-json`, `stylelint-json`, `black-text`, `markdownlint-json`, `prettier-text`, `vale-json`, `tidy-text`, `jsonlint-text`, `isort-text`, `htmlhint-json`
|
|
143
|
-
|
|
144
|
-
**Build tools:** `cargo-build`, `javac-text`, `dotnet-build-text`, `clang-text`
|
|
145
|
-
|
|
146
|
-
**Security & audit:** `bandit-json`, `npm-audit-json`
|
|
147
|
-
|
|
148
|
-
**Pipeline tools:** `dbt-json` (run, test, compile)
|
|
149
|
-
|
|
150
|
-
Run `/sr-parsers` in a pi session to see all registered parsers with their match rules.
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
## Installation
|
|
154
|
-
|
|
155
|
-
Install the skill and extension:
|
|
156
|
-
|
|
157
|
-
```bash
|
|
158
|
-
pi install npm:@robhowley/pi-structured-return
|
|
159
|
-
```
|
|
160
|
-
|
|
161
157
|
## How it works
|
|
162
158
|
|
|
163
159
|
1. The agent runs commands through `structured_return` when it would reduce noise and token usage.
|
|
@@ -165,6 +161,9 @@ pi install npm:@robhowley/pi-structured-return
|
|
|
165
161
|
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.
|
|
166
162
|
4. The agent receives the structured result in context — signal only, no noise.
|
|
167
163
|
5. The full log is always available on disk for both the agent and humans to inspect.
|
|
164
|
+
6. Run `/sr-stats` to see how many tokens structured-return has saved — both in the current session and across all sessions.
|
|
165
|
+
|
|
166
|
+
Run `/sr-parsers` in a pi session to see all registered parsers with their match rules. Run `/sr-stats` to see token savings for the current session and lifetime.
|
|
168
167
|
|
|
169
168
|
## Extending with project-local parsers
|
|
170
169
|
|
|
@@ -245,8 +244,3 @@ Every parser returns the same shape. The model always knows where to look.
|
|
|
245
244
|
| `artifact` | `string?` | Path to the saved report file, if one was written |
|
|
246
245
|
| `logPath` | `string` | Path to full stdout+stderr log |
|
|
247
246
|
| `rawTail` | `string?` | Last 200 lines of log, included on fallback when no parser matched |
|
|
248
|
-
|
|
249
|
-
## Design
|
|
250
|
-
|
|
251
|
-
`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.
|
|
252
|
-
|
|
@@ -9,6 +9,7 @@ import { ensureRunDir, writeRunArtifacts } from "./storage/log-store";
|
|
|
9
9
|
import { loadProjectConfig } from "./config/project-config";
|
|
10
10
|
import { resolveParser, listParsers } from "./config/registry";
|
|
11
11
|
import { safeReadFile } from "./parsers/utils";
|
|
12
|
+
import { appendRun, readLifetimeStats, formatStatsBlock, type AggregatedStats } from "./storage/session-stats";
|
|
12
13
|
|
|
13
14
|
export default function structuredReturn(pi: ExtensionAPI) {
|
|
14
15
|
pi.registerCommand("sr-parsers", {
|
|
@@ -42,6 +43,40 @@ export default function structuredReturn(pi: ExtensionAPI) {
|
|
|
42
43
|
},
|
|
43
44
|
});
|
|
44
45
|
|
|
46
|
+
pi.registerCommand("sr-stats", {
|
|
47
|
+
description: "Show token savings from structured-return (current session + lifetime)",
|
|
48
|
+
handler: async (_args, ctx) => {
|
|
49
|
+
// Current session: walk session entries for our tool results
|
|
50
|
+
const sessionStats: AggregatedStats = { runs: 0, rawBytes: 0, parsedBytes: 0 };
|
|
51
|
+
try {
|
|
52
|
+
const entries = ctx.sessionManager?.getEntries?.() ?? [];
|
|
53
|
+
for (const entry of entries) {
|
|
54
|
+
if (entry.type !== "message") continue;
|
|
55
|
+
const msg = (entry as any).message;
|
|
56
|
+
if (msg?.role !== "toolResult" || msg?.toolName !== "structured_return") continue;
|
|
57
|
+
const details = msg.details;
|
|
58
|
+
if (details?.rawBytes != null && details?.parsedBytes != null) {
|
|
59
|
+
sessionStats.runs++;
|
|
60
|
+
sessionStats.rawBytes += details.rawBytes;
|
|
61
|
+
sessionStats.parsedBytes += details.parsedBytes;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
// session access may fail in some modes
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Lifetime: read all JSONL files
|
|
69
|
+
const lifetime = readLifetimeStats();
|
|
70
|
+
|
|
71
|
+
const lines: string[] = ["structured-return stats", ""];
|
|
72
|
+
lines.push(...formatStatsBlock("session", sessionStats));
|
|
73
|
+
lines.push("");
|
|
74
|
+
lines.push(...formatStatsBlock("lifetime", lifetime));
|
|
75
|
+
|
|
76
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
|
|
45
80
|
pi.registerTool({
|
|
46
81
|
name: "structured_return",
|
|
47
82
|
label: "Structured Return",
|
|
@@ -81,10 +116,26 @@ export default function structuredReturn(pi: ExtensionAPI) {
|
|
|
81
116
|
const parser = await resolveParser({ cwd, parseAs: args.parseAs, argv, registrations });
|
|
82
117
|
const parsed = await parser.parse(runCtx);
|
|
83
118
|
const result = finalizeResult(parsed, exitCode, logs.logPath, cwd);
|
|
119
|
+
const resultText = formatResult(result);
|
|
120
|
+
|
|
121
|
+
const rawBytes = stdout.length + stderr.length;
|
|
122
|
+
const parsedBytes = resultText.length;
|
|
123
|
+
try {
|
|
124
|
+
appendRun({
|
|
125
|
+
ts: new Date().toISOString(),
|
|
126
|
+
session: ctx.sessionManager?.getSessionFile?.() ?? undefined,
|
|
127
|
+
parser: parser.id,
|
|
128
|
+
rawBytes,
|
|
129
|
+
parsedBytes,
|
|
130
|
+
command: stripCdPrefix(args.command),
|
|
131
|
+
});
|
|
132
|
+
} catch {
|
|
133
|
+
// stats are best-effort — never block the tool result
|
|
134
|
+
}
|
|
84
135
|
|
|
85
136
|
return {
|
|
86
|
-
content: [{ type: "text" as const, text: `${stripCdPrefix(args.command)} → ${
|
|
87
|
-
details: { exitCode, logPath: logs.logPath, parser: parser.id },
|
|
137
|
+
content: [{ type: "text" as const, text: `${stripCdPrefix(args.command)} → ${resultText}` }],
|
|
138
|
+
details: { exitCode, logPath: logs.logPath, parser: parser.id, rawBytes, parsedBytes },
|
|
88
139
|
};
|
|
89
140
|
},
|
|
90
141
|
renderCall(args: ObservedRunArgs) {
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import {
|
|
6
|
+
appendRun,
|
|
7
|
+
readLifetimeStats,
|
|
8
|
+
formatBytes,
|
|
9
|
+
estimateTokens,
|
|
10
|
+
formatStatsBlock,
|
|
11
|
+
type StatsEntry,
|
|
12
|
+
} from "./session-stats";
|
|
13
|
+
|
|
14
|
+
// Use a temp dir to avoid polluting ~/.pi during tests
|
|
15
|
+
let tempDir: string;
|
|
16
|
+
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "sr-stats-test-"));
|
|
19
|
+
// Override homedir so statsDir() resolves to our temp
|
|
20
|
+
vi.spyOn(os, "homedir").mockReturnValue(tempDir);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
afterEach(() => {
|
|
24
|
+
vi.restoreAllMocks();
|
|
25
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
function makeEntry(overrides: Partial<StatsEntry> = {}): StatsEntry {
|
|
29
|
+
return {
|
|
30
|
+
ts: new Date().toISOString(),
|
|
31
|
+
session: "/test/session.jsonl",
|
|
32
|
+
parser: "vitest-json",
|
|
33
|
+
rawBytes: 10000,
|
|
34
|
+
parsedBytes: 200,
|
|
35
|
+
command: "vitest run",
|
|
36
|
+
...overrides,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
describe("appendRun", () => {
|
|
41
|
+
it("creates the stats file on first append", () => {
|
|
42
|
+
appendRun(makeEntry());
|
|
43
|
+
const file = path.join(tempDir, ".pi", "structured-return-stats.000.jsonl");
|
|
44
|
+
expect(fs.existsSync(file)).toBe(true);
|
|
45
|
+
const lines = fs.readFileSync(file, "utf-8").trim().split("\n");
|
|
46
|
+
expect(lines).toHaveLength(1);
|
|
47
|
+
expect(JSON.parse(lines[0]).parser).toBe("vitest-json");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("appends multiple entries to the same file", () => {
|
|
51
|
+
appendRun(makeEntry({ command: "first" }));
|
|
52
|
+
appendRun(makeEntry({ command: "second" }));
|
|
53
|
+
appendRun(makeEntry({ command: "third" }));
|
|
54
|
+
const file = path.join(tempDir, ".pi", "structured-return-stats.000.jsonl");
|
|
55
|
+
const lines = fs.readFileSync(file, "utf-8").trim().split("\n");
|
|
56
|
+
expect(lines).toHaveLength(3);
|
|
57
|
+
expect(JSON.parse(lines[1]).command).toBe("second");
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("spills over to a new file when current exceeds 3MB", () => {
|
|
61
|
+
const statsDir = path.join(tempDir, ".pi");
|
|
62
|
+
fs.mkdirSync(statsDir, { recursive: true });
|
|
63
|
+
// Create a file just at the threshold
|
|
64
|
+
const bigContent = "x".repeat(3 * 1024 * 1024);
|
|
65
|
+
fs.writeFileSync(path.join(statsDir, "structured-return-stats.000.jsonl"), bigContent);
|
|
66
|
+
|
|
67
|
+
appendRun(makeEntry());
|
|
68
|
+
|
|
69
|
+
const newFile = path.join(statsDir, "structured-return-stats.001.jsonl");
|
|
70
|
+
expect(fs.existsSync(newFile)).toBe(true);
|
|
71
|
+
const lines = fs.readFileSync(newFile, "utf-8").trim().split("\n");
|
|
72
|
+
expect(lines).toHaveLength(1);
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
describe("readLifetimeStats", () => {
|
|
77
|
+
it("returns zeros when no files exist", () => {
|
|
78
|
+
const stats = readLifetimeStats();
|
|
79
|
+
expect(stats).toEqual({ runs: 0, rawBytes: 0, parsedBytes: 0 });
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("sums entries across multiple files", () => {
|
|
83
|
+
const statsDir = path.join(tempDir, ".pi");
|
|
84
|
+
fs.mkdirSync(statsDir, { recursive: true });
|
|
85
|
+
|
|
86
|
+
const entry1 = JSON.stringify({ rawBytes: 1000, parsedBytes: 100 });
|
|
87
|
+
const entry2 = JSON.stringify({ rawBytes: 2000, parsedBytes: 200 });
|
|
88
|
+
const entry3 = JSON.stringify({ rawBytes: 3000, parsedBytes: 300 });
|
|
89
|
+
|
|
90
|
+
fs.writeFileSync(path.join(statsDir, "structured-return-stats.000.jsonl"), entry1 + "\n" + entry2 + "\n");
|
|
91
|
+
fs.writeFileSync(path.join(statsDir, "structured-return-stats.001.jsonl"), entry3 + "\n");
|
|
92
|
+
|
|
93
|
+
const stats = readLifetimeStats();
|
|
94
|
+
expect(stats.runs).toBe(3);
|
|
95
|
+
expect(stats.rawBytes).toBe(6000);
|
|
96
|
+
expect(stats.parsedBytes).toBe(600);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it("skips malformed lines", () => {
|
|
100
|
+
const statsDir = path.join(tempDir, ".pi");
|
|
101
|
+
fs.mkdirSync(statsDir, { recursive: true });
|
|
102
|
+
|
|
103
|
+
const content = [
|
|
104
|
+
JSON.stringify({ rawBytes: 1000, parsedBytes: 100 }),
|
|
105
|
+
"not valid json",
|
|
106
|
+
JSON.stringify({ rawBytes: 2000, parsedBytes: 200 }),
|
|
107
|
+
].join("\n");
|
|
108
|
+
fs.writeFileSync(path.join(statsDir, "structured-return-stats.000.jsonl"), content + "\n");
|
|
109
|
+
|
|
110
|
+
const stats = readLifetimeStats();
|
|
111
|
+
expect(stats.runs).toBe(2);
|
|
112
|
+
expect(stats.rawBytes).toBe(3000);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
describe("formatBytes", () => {
|
|
117
|
+
it("formats bytes", () => expect(formatBytes(500)).toBe("500 B"));
|
|
118
|
+
it("formats kilobytes", () => expect(formatBytes(2048)).toBe("2.0 KB"));
|
|
119
|
+
it("formats megabytes", () => expect(formatBytes(5 * 1024 * 1024)).toBe("5.0 MB"));
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
describe("estimateTokens", () => {
|
|
123
|
+
it("formats small counts", () => expect(estimateTokens(100)).toBe("25"));
|
|
124
|
+
it("formats thousands", () => expect(estimateTokens(40000)).toBe("10.0k"));
|
|
125
|
+
it("formats millions", () => expect(estimateTokens(8000000)).toBe("2.0M"));
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
describe("formatStatsBlock", () => {
|
|
129
|
+
it("formats a labeled stats block", () => {
|
|
130
|
+
const block = formatStatsBlock("session", { runs: 5, rawBytes: 50000, parsedBytes: 1000 });
|
|
131
|
+
expect(block[0]).toBe("session:");
|
|
132
|
+
expect(block[1]).toContain("runs: 5");
|
|
133
|
+
expect(block[4]).toContain("98.0% reduction");
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("handles zero runs gracefully", () => {
|
|
137
|
+
const block = formatStatsBlock("lifetime", { runs: 0, rawBytes: 0, parsedBytes: 0 });
|
|
138
|
+
expect(block[1]).toContain("runs: 0");
|
|
139
|
+
expect(block[4]).toContain("0.0%");
|
|
140
|
+
});
|
|
141
|
+
});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
|
|
5
|
+
const FILE_PREFIX = "structured-return-stats.";
|
|
6
|
+
const FILE_SUFFIX = ".jsonl";
|
|
7
|
+
const MAX_FILE_BYTES = 3 * 1024 * 1024; // 3MB
|
|
8
|
+
|
|
9
|
+
function statsDir(): string {
|
|
10
|
+
return path.join(os.homedir(), ".pi");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type StatsEntry = {
|
|
14
|
+
ts: string;
|
|
15
|
+
session: string | undefined;
|
|
16
|
+
parser: string;
|
|
17
|
+
rawBytes: number;
|
|
18
|
+
parsedBytes: number;
|
|
19
|
+
command: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type AggregatedStats = {
|
|
23
|
+
runs: number;
|
|
24
|
+
rawBytes: number;
|
|
25
|
+
parsedBytes: number;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function statsFileName(index: number): string {
|
|
29
|
+
return `${FILE_PREFIX}${String(index).padStart(3, "0")}${FILE_SUFFIX}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function statsFilePath(index: number): string {
|
|
33
|
+
return path.join(statsDir(), statsFileName(index));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Find all stats files sorted by index. */
|
|
37
|
+
function listStatsFiles(): string[] {
|
|
38
|
+
const dir = statsDir();
|
|
39
|
+
if (!fs.existsSync(dir)) return [];
|
|
40
|
+
const files = fs
|
|
41
|
+
.readdirSync(dir)
|
|
42
|
+
.filter((f) => f.startsWith(FILE_PREFIX) && f.endsWith(FILE_SUFFIX))
|
|
43
|
+
.sort();
|
|
44
|
+
return files.map((f) => path.join(dir, f));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Get the current (latest) file index, creating 000 if none exist. */
|
|
48
|
+
function currentFileIndex(): number {
|
|
49
|
+
const files = listStatsFiles();
|
|
50
|
+
if (files.length === 0) return 0;
|
|
51
|
+
const last = path.basename(files[files.length - 1]);
|
|
52
|
+
const match = last.match(/\.(\d{3})\./);
|
|
53
|
+
return match ? parseInt(match[1], 10) : 0;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Append a stats entry, spilling over to a new file if needed. */
|
|
57
|
+
export function appendRun(entry: StatsEntry): void {
|
|
58
|
+
fs.mkdirSync(statsDir(), { recursive: true });
|
|
59
|
+
let index = currentFileIndex();
|
|
60
|
+
let filePath = statsFilePath(index);
|
|
61
|
+
|
|
62
|
+
// Check spillover
|
|
63
|
+
if (fs.existsSync(filePath)) {
|
|
64
|
+
const stat = fs.statSync(filePath);
|
|
65
|
+
if (stat.size >= MAX_FILE_BYTES) {
|
|
66
|
+
index++;
|
|
67
|
+
filePath = statsFilePath(index);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const line = JSON.stringify(entry) + "\n";
|
|
72
|
+
fs.appendFileSync(filePath, line);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Read and aggregate all stats files for lifetime totals. */
|
|
76
|
+
export function readLifetimeStats(): AggregatedStats {
|
|
77
|
+
const files = listStatsFiles();
|
|
78
|
+
const totals: AggregatedStats = { runs: 0, rawBytes: 0, parsedBytes: 0 };
|
|
79
|
+
|
|
80
|
+
for (const file of files) {
|
|
81
|
+
const content = fs.readFileSync(file, "utf-8");
|
|
82
|
+
for (const line of content.split("\n")) {
|
|
83
|
+
if (!line.trim()) continue;
|
|
84
|
+
try {
|
|
85
|
+
const entry: StatsEntry = JSON.parse(line);
|
|
86
|
+
totals.runs++;
|
|
87
|
+
totals.rawBytes += entry.rawBytes;
|
|
88
|
+
totals.parsedBytes += entry.parsedBytes;
|
|
89
|
+
} catch {
|
|
90
|
+
// skip malformed lines
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return totals;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function formatBytes(bytes: number): string {
|
|
99
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
100
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
101
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Approximate token count: ~4 bytes per token for English text across common tokenizers (GPT/Claude). */
|
|
105
|
+
export function estimateTokens(bytes: number): string {
|
|
106
|
+
const tokens = Math.round(bytes / 4);
|
|
107
|
+
if (tokens < 1000) return `${tokens}`;
|
|
108
|
+
if (tokens < 1_000_000) return `${(tokens / 1000).toFixed(1)}k`;
|
|
109
|
+
return `${(tokens / 1_000_000).toFixed(1)}M`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function formatStatsBlock(label: string, stats: AggregatedStats): string[] {
|
|
113
|
+
const saved = stats.rawBytes - stats.parsedBytes;
|
|
114
|
+
const pct = stats.rawBytes > 0 ? ((saved / stats.rawBytes) * 100).toFixed(1) : "0.0";
|
|
115
|
+
return [
|
|
116
|
+
`${label}:`,
|
|
117
|
+
` runs: ${stats.runs}`,
|
|
118
|
+
` raw output: ${formatBytes(stats.rawBytes)} (~${estimateTokens(stats.rawBytes)} tokens)`,
|
|
119
|
+
` parsed output: ${formatBytes(stats.parsedBytes)} (~${estimateTokens(stats.parsedBytes)} tokens)`,
|
|
120
|
+
` saved: ${formatBytes(saved)} (~${estimateTokens(saved)} tokens, ${pct}% reduction)`,
|
|
121
|
+
];
|
|
122
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@robhowley/pi-structured-return",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.7.0",
|
|
4
|
+
"description": "Turn noisy CLI output into compact structured results (fewer tokens), full logs preserved.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -12,7 +12,12 @@
|
|
|
12
12
|
"url": "https://github.com/robhowley/pi-structured-return/issues"
|
|
13
13
|
},
|
|
14
14
|
"keywords": [
|
|
15
|
-
"pi-package"
|
|
15
|
+
"pi-package",
|
|
16
|
+
"pi-coding-agent",
|
|
17
|
+
"pi",
|
|
18
|
+
"pi-extension",
|
|
19
|
+
"token-reduction",
|
|
20
|
+
"structured-output"
|
|
16
21
|
],
|
|
17
22
|
"files": [
|
|
18
23
|
"extensions",
|