@robhowley/pi-structured-return 1.7.3 → 1.8.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
@@ -161,9 +161,9 @@ Evaluated for structured parsing but raw output is already compact enough that a
161
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.
162
162
  4. The agent receives the structured result in context — signal only, no noise.
163
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.
164
+ 6. Run `/sr-stats` to see how many tokens structured-return has saved — for the current session, the current working directory, and lifetime across all sessions.
165
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.
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, cwd lifetime, and lifetime.
167
167
 
168
168
  ## Extending with project-local parsers
169
169
 
@@ -173,6 +173,19 @@ describe("expandArtifactPaths", () => {
173
173
  ]);
174
174
  });
175
175
 
176
+ it("expands globs with * in directory positions (multi-module Gradle)", () => {
177
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "expand-dirglob-"));
178
+ const modA = path.join(dir, "moduleA", "build", "test-results", "test");
179
+ const modB = path.join(dir, "moduleB", "build", "test-results", "test");
180
+ fs.mkdirSync(modA, { recursive: true });
181
+ fs.mkdirSync(modB, { recursive: true });
182
+ fs.writeFileSync(path.join(modA, "TEST-FooTest.xml"), "<foo/>");
183
+ fs.writeFileSync(path.join(modB, "TEST-BarTest.xml"), "<bar/>");
184
+
185
+ const result = expandArtifactPaths(["*/build/test-results/test/TEST-*.xml"], dir);
186
+ expect(result).toEqual([path.join(modA, "TEST-FooTest.xml"), path.join(modB, "TEST-BarTest.xml")]);
187
+ });
188
+
176
189
  it("returns empty array for empty input", () => {
177
190
  expect(expandArtifactPaths([], "/any")).toEqual([]);
178
191
  });
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
- import fs from "node:fs";
3
2
  import path from "node:path";
4
3
  import { randomUUID } from "node:crypto";
4
+ import { globSync } from "glob";
5
5
  import { Type } from "@sinclair/typebox";
6
6
  import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
7
7
  import { Text } from "@mariozechner/pi-tui";
@@ -45,15 +45,25 @@ export default function structuredReturn(pi: ExtensionAPI) {
45
45
  });
46
46
 
47
47
  pi.registerCommand("sr-stats", {
48
- description: "Show token savings from structured-return (current session + lifetime)",
48
+ description: "Show token savings from structured-return (current session + cwd lifetime + lifetime)",
49
49
  handler: async (_args, ctx) => {
50
+ const currentCwd = ctx.cwd ?? process.cwd();
51
+
50
52
  // Current session: walk session entries for our tool results
51
53
  const sessionStats: AggregatedStats = { runs: 0, rawBytes: 0, parsedBytes: 0 };
52
54
  try {
53
55
  const entries = ctx.sessionManager?.getEntries?.() ?? [];
54
56
  for (const entry of entries) {
55
57
  if (entry.type !== "message") continue;
56
- const msg = (entry as any).message;
58
+ const msg = (
59
+ entry as {
60
+ message?: {
61
+ role?: string;
62
+ toolName?: string;
63
+ details?: { rawBytes?: number; parsedBytes?: number };
64
+ };
65
+ }
66
+ ).message;
57
67
  if (msg?.role !== "toolResult" || msg?.toolName !== "structured_return") continue;
58
68
  const details = msg.details;
59
69
  if (details?.rawBytes != null && details?.parsedBytes != null) {
@@ -66,12 +76,16 @@ export default function structuredReturn(pi: ExtensionAPI) {
66
76
  // session access may fail in some modes
67
77
  }
68
78
 
79
+ const cwdLifetime = readLifetimeStats({ cwd: currentCwd });
80
+
69
81
  // Lifetime: read all JSONL files
70
82
  const lifetime = readLifetimeStats();
71
83
 
72
84
  const lines: string[] = ["structured-return stats", ""];
73
85
  lines.push(...formatStatsBlock("session", sessionStats));
74
86
  lines.push("");
87
+ lines.push(...formatStatsBlock("cwd lifetime", cwdLifetime));
88
+ lines.push("");
75
89
  lines.push(...formatStatsBlock("lifetime", lifetime));
76
90
 
77
91
  ctx.ui.notify(lines.join("\n"), "info");
@@ -129,6 +143,7 @@ export default function structuredReturn(pi: ExtensionAPI) {
129
143
  rawBytes,
130
144
  parsedBytes,
131
145
  command: stripCdPrefix(args.command),
146
+ cwd,
132
147
  });
133
148
  } catch {
134
149
  // stats are best-effort — never block the tool result
@@ -173,7 +188,7 @@ export function formatResult(result: ParsedResult): string {
173
188
  export function expandArtifactPaths(raw: string[], cwd: string): string[] {
174
189
  return raw.flatMap((p) => {
175
190
  const resolved = path.isAbsolute(p) ? p : path.join(cwd, p);
176
- const expanded = fs.globSync(resolved);
191
+ const expanded = globSync(resolved);
177
192
  return expanded.length > 0 ? expanded.sort() : [resolved];
178
193
  });
179
194
  }
@@ -111,6 +111,21 @@ describe("readLifetimeStats", () => {
111
111
  expect(stats.runs).toBe(2);
112
112
  expect(stats.rawBytes).toBe(3000);
113
113
  });
114
+
115
+ it("can filter lifetime stats by cwd", () => {
116
+ const statsDir = path.join(tempDir, ".pi");
117
+ fs.mkdirSync(statsDir, { recursive: true });
118
+
119
+ const content = [
120
+ JSON.stringify({ rawBytes: 1000, parsedBytes: 100, cwd: "/repo/a" }),
121
+ JSON.stringify({ rawBytes: 2000, parsedBytes: 200, cwd: "/repo/b" }),
122
+ JSON.stringify({ rawBytes: 3000, parsedBytes: 300, cwd: "/repo/a" }),
123
+ ].join("\n");
124
+ fs.writeFileSync(path.join(statsDir, "structured-return-stats.000.jsonl"), content + "\n");
125
+
126
+ const stats = readLifetimeStats({ cwd: "/repo/a" });
127
+ expect(stats).toEqual({ runs: 2, rawBytes: 4000, parsedBytes: 400 });
128
+ });
114
129
  });
115
130
 
116
131
  describe("formatBytes", () => {
@@ -17,6 +17,7 @@ export type StatsEntry = {
17
17
  rawBytes: number;
18
18
  parsedBytes: number;
19
19
  command: string;
20
+ cwd?: string;
20
21
  };
21
22
 
22
23
  export type AggregatedStats = {
@@ -72,8 +73,8 @@ export function appendRun(entry: StatsEntry): void {
72
73
  fs.appendFileSync(filePath, line);
73
74
  }
74
75
 
75
- /** Read and aggregate all stats files for lifetime totals. */
76
- export function readLifetimeStats(): AggregatedStats {
76
+ /** Read and aggregate all stats files for lifetime totals, optionally filtered by cwd. */
77
+ export function readLifetimeStats(opts: { cwd?: string } = {}): AggregatedStats {
77
78
  const files = listStatsFiles();
78
79
  const totals: AggregatedStats = { runs: 0, rawBytes: 0, parsedBytes: 0 };
79
80
 
@@ -83,6 +84,7 @@ export function readLifetimeStats(): AggregatedStats {
83
84
  if (!line.trim()) continue;
84
85
  try {
85
86
  const entry: StatsEntry = JSON.parse(line);
87
+ if (opts.cwd && entry.cwd !== opts.cwd) continue;
86
88
  totals.runs++;
87
89
  totals.rawBytes += entry.rawBytes;
88
90
  totals.parsedBytes += entry.parsedBytes;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robhowley/pi-structured-return",
3
- "version": "1.7.3",
3
+ "version": "1.8.0",
4
4
  "description": "Turn noisy CLI output into compact structured results (fewer tokens), full logs preserved.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -51,7 +51,8 @@
51
51
  "prepare": "node -e \"if (process.env.CI || process.env.GITHUB_ACTIONS) process.exit(0)\" || husky"
52
52
  },
53
53
  "dependencies": {
54
- "fast-xml-parser": "^5.4.1"
54
+ "fast-xml-parser": "^5.4.1",
55
+ "glob": "^11.0.0"
55
56
  },
56
57
  "devDependencies": {
57
58
  "@mariozechner/pi-coding-agent": "*",
@@ -150,14 +150,14 @@ Gradle writes one XML file per test class — there is no single-file option. Al
150
150
 
151
151
  - `structured_return({ command: "gradle test", parseAs: "junit-xml", artifactPaths: ["build/test-results/test/TEST-*.xml"] })` — full test suite; results aggregated across all matched files
152
152
  - `structured_return({ command: "gradle test --tests 'com.example.FooTest'", parseAs: "junit-xml", artifactPaths: ["build/test-results/test/TEST-*.xml"] })` — single class; glob still works (matches the one file)
153
- - For multi-module projects: `structured_return({ command: "gradle :module:test", parseAs: "junit-xml", artifactPaths: ["module/build/test-results/test/TEST-*.xml"] })` — scope the glob to the module's build dir
153
+ - For multi-module projects, use `*` in directory positions to match across modules: `structured_return({ command: "gradle test", parseAs: "junit-xml", artifactPaths: ["*/build/test-results/test/TEST-*.xml"] })` — or scope to one module: `structured_return({ command: "gradle :module:test", parseAs: "junit-xml", artifactPaths: ["module/build/test-results/test/TEST-*.xml"] })`
154
154
 
155
155
  #### Maven
156
156
 
157
157
  Maven Surefire writes one XML per test class — same as Gradle. Always use a glob pattern.
158
158
 
159
159
  - `structured_return({ command: "mvn test", parseAs: "junit-xml", artifactPaths: ["target/surefire-reports/TEST-*.xml"] })` — full test suite; any maven args (e.g. `-pl module`, `-Dtest=ClassName`) go before `test`
160
- - For multi-module projects: `structured_return({ command: "mvn test -pl module", parseAs: "junit-xml", artifactPaths: ["module/target/surefire-reports/TEST-*.xml"] })` — scope the glob to the module
160
+ - For multi-module projects, use `*` in directory positions: `structured_return({ command: "mvn test", parseAs: "junit-xml", artifactPaths: ["*/target/surefire-reports/TEST-*.xml"] })` — or scope to one module: `structured_return({ command: "mvn test -pl module", parseAs: "junit-xml", artifactPaths: ["module/target/surefire-reports/TEST-*.xml"] })`
161
161
 
162
162
  #### .NET / xUnit
163
163