@ulrichc1/sparn 1.2.1 → 1.4.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 (42) hide show
  1. package/PRIVACY.md +1 -1
  2. package/README.md +136 -642
  3. package/SECURITY.md +1 -1
  4. package/dist/cli/dashboard.cjs +3977 -0
  5. package/dist/cli/dashboard.cjs.map +1 -0
  6. package/dist/cli/dashboard.d.cts +17 -0
  7. package/dist/cli/dashboard.d.ts +17 -0
  8. package/dist/cli/dashboard.js +3932 -0
  9. package/dist/cli/dashboard.js.map +1 -0
  10. package/dist/cli/index.cjs +3855 -486
  11. package/dist/cli/index.cjs.map +1 -1
  12. package/dist/cli/index.js +3812 -459
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/daemon/index.cjs +411 -99
  15. package/dist/daemon/index.cjs.map +1 -1
  16. package/dist/daemon/index.js +423 -103
  17. package/dist/daemon/index.js.map +1 -1
  18. package/dist/hooks/post-tool-result.cjs +129 -225
  19. package/dist/hooks/post-tool-result.cjs.map +1 -1
  20. package/dist/hooks/post-tool-result.js +129 -225
  21. package/dist/hooks/post-tool-result.js.map +1 -1
  22. package/dist/hooks/pre-prompt.cjs +206 -242
  23. package/dist/hooks/pre-prompt.cjs.map +1 -1
  24. package/dist/hooks/pre-prompt.js +192 -243
  25. package/dist/hooks/pre-prompt.js.map +1 -1
  26. package/dist/hooks/stop-docs-refresh.cjs +123 -0
  27. package/dist/hooks/stop-docs-refresh.cjs.map +1 -0
  28. package/dist/hooks/stop-docs-refresh.d.cts +1 -0
  29. package/dist/hooks/stop-docs-refresh.d.ts +1 -0
  30. package/dist/hooks/stop-docs-refresh.js +126 -0
  31. package/dist/hooks/stop-docs-refresh.js.map +1 -0
  32. package/dist/index.cjs +1756 -339
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +540 -41
  35. package/dist/index.d.ts +540 -41
  36. package/dist/index.js +1739 -331
  37. package/dist/index.js.map +1 -1
  38. package/dist/mcp/index.cjs +306 -73
  39. package/dist/mcp/index.cjs.map +1 -1
  40. package/dist/mcp/index.js +310 -73
  41. package/dist/mcp/index.js.map +1 -1
  42. package/package.json +10 -3
@@ -1,11 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
 
4
+ // src/hooks/post-tool-result.ts
5
+ var import_node_fs = require("fs");
6
+ var import_node_os = require("os");
7
+ var import_node_path = require("path");
8
+
4
9
  // src/utils/tokenizer.ts
10
+ var import_gpt_tokenizer = require("gpt-tokenizer");
11
+ var usePrecise = false;
5
12
  function estimateTokens(text) {
6
13
  if (!text || text.length === 0) {
7
14
  return 0;
8
15
  }
16
+ if (usePrecise) {
17
+ return (0, import_gpt_tokenizer.encode)(text).length;
18
+ }
9
19
  const words = text.split(/\s+/).filter((w) => w.length > 0);
10
20
  const wordCount = words.length;
11
21
  const charCount = text.length;
@@ -15,238 +25,87 @@ function estimateTokens(text) {
15
25
  }
16
26
 
17
27
  // src/hooks/post-tool-result.ts
18
- function exitSuccess(output) {
19
- process.stdout.write(output);
20
- process.exit(0);
21
- }
22
- var COMPRESSION_THRESHOLD = 5e3;
23
- var TOOL_PATTERNS = {
24
- fileRead: /<file_path>(.*?)<\/file_path>[\s\S]*?<content>([\s\S]*?)<\/content>/,
25
- grepResult: /<pattern>(.*?)<\/pattern>[\s\S]*?<matches>([\s\S]*?)<\/matches>/,
26
- gitDiff: /^diff --git/m,
27
- buildOutput: /(error|warning|failed|failure)/i,
28
- npmInstall: /^(npm|pnpm|yarn) (install|add|i)/m,
29
- dockerLogs: /^\[?\d{4}-\d{2}-\d{2}/m,
30
- testResults: /(PASS|FAIL|SKIP).*?\.test\./i,
31
- typescriptErrors: /^.*\(\d+,\d+\): error TS\d+:/m,
32
- webpackBuild: /webpack \d+\.\d+\.\d+/i
33
- };
34
- function compressFileRead(content, maxLines = 100) {
35
- const lines = content.split("\n");
36
- if (lines.length <= maxLines * 2) {
37
- return content;
28
+ var DEBUG = process.env["SPARN_DEBUG"] === "true";
29
+ var LOG_FILE = process.env["SPARN_LOG_FILE"] || (0, import_node_path.join)((0, import_node_os.homedir)(), ".sparn-hook.log");
30
+ var SUMMARY_THRESHOLD = 3e3;
31
+ function log(message) {
32
+ if (DEBUG) {
33
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
34
+ (0, import_node_fs.appendFileSync)(LOG_FILE, `[${timestamp}] [post-tool] ${message}
35
+ `);
38
36
  }
39
- const head = lines.slice(0, maxLines);
40
- const tail = lines.slice(-maxLines);
41
- const omitted = lines.length - maxLines * 2;
42
- return [...head, "", `... [${omitted} lines omitted] ...`, "", ...tail].join("\n");
43
37
  }
44
- function compressGrepResults(content, maxMatchesPerFile = 5) {
45
- const lines = content.split("\n");
46
- const fileMatches = /* @__PURE__ */ new Map();
47
- for (const line of lines) {
48
- const match = line.match(/^(.*?):(\d+):(.*)/);
49
- if (match?.[1] && match[2] && match[3]) {
50
- const file = match[1];
51
- const lineNum = match[2];
52
- const text = match[3];
53
- if (!fileMatches.has(file)) {
54
- fileMatches.set(file, []);
55
- }
56
- fileMatches.get(file)?.push(` Line ${lineNum}: ${text.trim()}`);
57
- }
38
+ function extractText(response) {
39
+ if (typeof response === "string") return response;
40
+ if (response && typeof response === "object") {
41
+ return JSON.stringify(response);
58
42
  }
59
- const compressed = [];
60
- for (const [file, matches] of fileMatches.entries()) {
61
- compressed.push(`${file} (${matches.length} matches):`);
62
- if (matches.length <= maxMatchesPerFile) {
63
- compressed.push(...matches);
64
- } else {
65
- compressed.push(...matches.slice(0, maxMatchesPerFile));
66
- compressed.push(` ... and ${matches.length - maxMatchesPerFile} more matches`);
67
- }
68
- compressed.push("");
69
- }
70
- return compressed.join("\n");
43
+ return String(response ?? "");
71
44
  }
72
- function compressGitDiff(content) {
73
- const lines = content.split("\n");
74
- const files = /* @__PURE__ */ new Map();
75
- let currentFile = "";
76
- for (const line of lines) {
77
- if (line.startsWith("diff --git")) {
78
- const match = line.match(/diff --git a\/(.*?) b\/(.*)/);
79
- if (match) {
80
- currentFile = match[2] || "";
81
- files.set(currentFile, { added: 0, removed: 0 });
82
- }
83
- } else if (line.startsWith("+") && !line.startsWith("+++")) {
84
- const stats = files.get(currentFile);
85
- if (stats) stats.added++;
86
- } else if (line.startsWith("-") && !line.startsWith("---")) {
87
- const stats = files.get(currentFile);
88
- if (stats) stats.removed++;
45
+ function summarizeBash(text, command) {
46
+ const lines = text.split("\n");
47
+ if (/\d+ (pass|fail|skip)/i.test(text) || /Tests?:/i.test(text)) {
48
+ const resultLines = lines.filter(
49
+ (l) => /(pass|fail|skip|error|Tests?:|Test Suites?:)/i.test(l) || /^\s*(PASS|FAIL)\s/.test(l)
50
+ );
51
+ if (resultLines.length > 0) {
52
+ return `[sparn] Test output summary (${lines.length} lines):
53
+ ${resultLines.slice(0, 15).join("\n")}`;
89
54
  }
90
55
  }
91
- const summary = ["Git diff summary:"];
92
- for (const [file, stats] of files.entries()) {
93
- summary.push(` ${file}: +${stats.added} -${stats.removed}`);
94
- }
95
- return summary.join("\n");
96
- }
97
- function compressBuildOutput(content) {
98
- const lines = content.split("\n");
99
- const important = [];
100
- for (const line of lines) {
101
- if (/(error|warning|failed|failure|fatal)/i.test(line)) {
102
- important.push(line);
103
- }
104
- }
105
- if (important.length === 0) {
106
- return "Build output: No errors or warnings found";
107
- }
108
- return ["Build errors/warnings:", ...important].join("\n");
109
- }
110
- function compressNpmInstall(content) {
111
- const lines = content.split("\n");
112
- const summary = [];
113
- const warnings = [];
114
- const errors = [];
115
- for (const line of lines) {
116
- if (/added \d+ packages?/i.test(line)) {
117
- summary.push(line.trim());
118
- }
119
- if (/warn/i.test(line)) {
120
- warnings.push(line.trim());
121
- }
122
- if (/error/i.test(line)) {
123
- errors.push(line.trim());
124
- }
125
- }
126
- if (errors.length > 0) {
127
- return ["Package installation errors:", ...errors.slice(0, 5)].join("\n");
128
- }
129
- if (warnings.length > 0) {
130
- return [
131
- "Package installation completed with warnings:",
132
- ...warnings.slice(0, 3),
133
- warnings.length > 3 ? `... and ${warnings.length - 3} more warnings` : ""
134
- ].filter(Boolean).join("\n");
135
- }
136
- return summary.length > 0 ? summary.join("\n") : "Package installation completed successfully";
137
- }
138
- function compressDockerLogs(content) {
139
- const lines = content.split("\n");
140
- const logMap = /* @__PURE__ */ new Map();
141
- for (const line of lines) {
142
- const normalized = line.replace(/^\[?\d{4}-\d{2}-\d{2}.*?\]\s*/, "").trim();
143
- if (normalized) {
144
- logMap.set(normalized, (logMap.get(normalized) || 0) + 1);
56
+ if (/(error|warning|failed)/i.test(text)) {
57
+ const errorLines = lines.filter((l) => /(error|warning|failed|fatal)/i.test(l));
58
+ if (errorLines.length > 0) {
59
+ return `[sparn] Build output summary (${errorLines.length} errors/warnings from ${lines.length} lines):
60
+ ${errorLines.slice(0, 10).join("\n")}`;
145
61
  }
146
62
  }
147
- const summary = ["Docker logs (deduplicated):"];
148
- for (const [log, count] of Array.from(logMap.entries()).slice(0, 20)) {
149
- if (count > 1) {
150
- summary.push(` [${count}x] ${log}`);
151
- } else {
152
- summary.push(` ${log}`);
63
+ if (/^diff --git/m.test(text)) {
64
+ const files = [];
65
+ for (const line of lines) {
66
+ const match = line.match(/^diff --git a\/(.*?) b\/(.*)/);
67
+ if (match?.[2]) files.push(match[2]);
153
68
  }
69
+ return `[sparn] Git diff: ${files.length} files changed: ${files.join(", ")}`;
154
70
  }
155
- if (logMap.size > 20) {
156
- summary.push(` ... and ${logMap.size - 20} more unique log lines`);
157
- }
158
- return summary.join("\n");
71
+ return `[sparn] Command \`${command}\` produced ${lines.length} lines of output. First 3: ${lines.slice(0, 3).join(" | ")}`;
159
72
  }
160
- function compressTestResults(content) {
161
- const lines = content.split("\n");
162
- let passed = 0;
163
- let failed = 0;
164
- let skipped = 0;
165
- const failures = [];
166
- for (const line of lines) {
167
- if (/PASS/i.test(line)) passed++;
168
- if (/FAIL/i.test(line)) {
169
- failed++;
170
- failures.push(line.trim());
171
- }
172
- if (/SKIP/i.test(line)) skipped++;
173
- }
174
- const summary = [`Test Results: ${passed} passed, ${failed} failed, ${skipped} skipped`];
175
- if (failures.length > 0) {
176
- summary.push("", "Failed tests:");
177
- summary.push(...failures.slice(0, 10));
178
- if (failures.length > 10) {
179
- summary.push(`... and ${failures.length - 10} more failures`);
180
- }
181
- }
182
- return summary.join("\n");
73
+ function summarizeFileRead(text, filePath) {
74
+ const lines = text.split("\n");
75
+ const tokens = estimateTokens(text);
76
+ const exports2 = lines.filter((l) => /^export\s/.test(l.trim()));
77
+ const functions = lines.filter((l) => /function\s+\w+/.test(l));
78
+ const classes = lines.filter((l) => /class\s+\w+/.test(l));
79
+ const parts = [`[sparn] File ${filePath}: ${lines.length} lines, ~${tokens} tokens.`];
80
+ if (exports2.length > 0) {
81
+ parts.push(
82
+ `Exports: ${exports2.slice(0, 5).map((e) => e.trim().substring(0, 60)).join("; ")}`
83
+ );
84
+ }
85
+ if (functions.length > 0) {
86
+ parts.push(
87
+ `Functions: ${functions.slice(0, 5).map((f) => f.trim().substring(0, 40)).join(", ")}`
88
+ );
89
+ }
90
+ if (classes.length > 0) {
91
+ parts.push(`Classes: ${classes.map((c) => c.trim().substring(0, 40)).join(", ")}`);
92
+ }
93
+ return parts.join(" ");
183
94
  }
184
- function compressTypescriptErrors(content) {
185
- const lines = content.split("\n");
186
- const errorMap = /* @__PURE__ */ new Map();
95
+ function summarizeSearch(text, pattern) {
96
+ const lines = text.split("\n").filter((l) => l.trim().length > 0);
97
+ const fileMap = /* @__PURE__ */ new Map();
187
98
  for (const line of lines) {
188
- const match = line.match(/^(.*?)\(\d+,\d+\): error (TS\d+):/);
189
- if (match) {
190
- const file = match[1] || "unknown";
191
- const errorCode = match[2] || "TS0000";
192
- const key = `${file}:${errorCode}`;
193
- if (!errorMap.has(key)) {
194
- errorMap.set(key, []);
195
- }
196
- errorMap.get(key)?.push(line);
99
+ const match = line.match(/^(.*?):\d+:/);
100
+ if (match?.[1]) {
101
+ fileMap.set(match[1], (fileMap.get(match[1]) || 0) + 1);
197
102
  }
198
103
  }
199
- const summary = ["TypeScript Errors (grouped by file):"];
200
- for (const [key, errors] of errorMap.entries()) {
201
- summary.push(` ${key} (${errors.length} errors)`);
202
- summary.push(` ${errors[0]}`);
104
+ if (fileMap.size > 0) {
105
+ const summary = Array.from(fileMap.entries()).slice(0, 5).map(([f, c]) => `${f} (${c})`).join(", ");
106
+ return `[sparn] Search for "${pattern}": ${lines.length} matches across ${fileMap.size} files. Top files: ${summary}`;
203
107
  }
204
- return summary.join("\n");
205
- }
206
- function compressToolResult(input) {
207
- const tokens = estimateTokens(input);
208
- if (tokens < COMPRESSION_THRESHOLD) {
209
- return input;
210
- }
211
- if (TOOL_PATTERNS.fileRead.test(input)) {
212
- const match = input.match(TOOL_PATTERNS.fileRead);
213
- if (match?.[2]) {
214
- const content = match[2];
215
- const compressed = compressFileRead(content);
216
- return input.replace(content, compressed);
217
- }
218
- }
219
- if (TOOL_PATTERNS.grepResult.test(input)) {
220
- const match = input.match(TOOL_PATTERNS.grepResult);
221
- if (match?.[2]) {
222
- const matches = match[2];
223
- const compressed = compressGrepResults(matches);
224
- return input.replace(matches, compressed);
225
- }
226
- }
227
- if (TOOL_PATTERNS.gitDiff.test(input)) {
228
- return compressGitDiff(input);
229
- }
230
- if (TOOL_PATTERNS.buildOutput.test(input)) {
231
- return compressBuildOutput(input);
232
- }
233
- if (TOOL_PATTERNS.npmInstall.test(input)) {
234
- return compressNpmInstall(input);
235
- }
236
- if (TOOL_PATTERNS.dockerLogs.test(input)) {
237
- return compressDockerLogs(input);
238
- }
239
- if (TOOL_PATTERNS.testResults.test(input)) {
240
- return compressTestResults(input);
241
- }
242
- if (TOOL_PATTERNS.typescriptErrors.test(input)) {
243
- return compressTypescriptErrors(input);
244
- }
245
- const lines = input.split("\n");
246
- if (lines.length > 200) {
247
- return compressFileRead(input, 100);
248
- }
249
- return input;
108
+ return `[sparn] Search for "${pattern}": ${lines.length} result lines`;
250
109
  }
251
110
  async function main() {
252
111
  try {
@@ -254,16 +113,61 @@ async function main() {
254
113
  for await (const chunk of process.stdin) {
255
114
  chunks.push(chunk);
256
115
  }
257
- const input = Buffer.concat(chunks).toString("utf-8");
258
- const output = compressToolResult(input);
259
- exitSuccess(output);
260
- } catch (_error) {
261
- const chunks = [];
262
- for await (const chunk of process.stdin) {
263
- chunks.push(chunk);
116
+ const raw = Buffer.concat(chunks).toString("utf-8");
117
+ let input;
118
+ try {
119
+ input = JSON.parse(raw);
120
+ } catch {
121
+ log("Failed to parse JSON input");
122
+ process.exit(0);
123
+ return;
124
+ }
125
+ const toolName = input.tool_name ?? "unknown";
126
+ const text = extractText(input.tool_response);
127
+ const tokens = estimateTokens(text);
128
+ log(`Tool: ${toolName}, response tokens: ~${tokens}`);
129
+ if (tokens < SUMMARY_THRESHOLD) {
130
+ log("Under threshold, no summary needed");
131
+ process.exit(0);
132
+ return;
133
+ }
134
+ let summary = "";
135
+ switch (toolName) {
136
+ case "Bash": {
137
+ const command = String(input.tool_input?.["command"] ?? "");
138
+ summary = summarizeBash(text, command);
139
+ break;
140
+ }
141
+ case "Read": {
142
+ const filePath = String(input.tool_input?.["file_path"] ?? "");
143
+ summary = summarizeFileRead(text, filePath);
144
+ break;
145
+ }
146
+ case "Grep": {
147
+ const pattern = String(input.tool_input?.["pattern"] ?? "");
148
+ summary = summarizeSearch(text, pattern);
149
+ break;
150
+ }
151
+ default: {
152
+ const lines = text.split("\n");
153
+ summary = `[sparn] ${toolName} output: ${lines.length} lines, ~${tokens} tokens`;
154
+ break;
155
+ }
264
156
  }
265
- const input = Buffer.concat(chunks).toString("utf-8");
266
- exitSuccess(input);
157
+ if (summary) {
158
+ log(`Summary: ${summary.substring(0, 100)}`);
159
+ const output = JSON.stringify({
160
+ hookSpecificOutput: {
161
+ hookEventName: "PostToolUse",
162
+ additionalContext: summary
163
+ }
164
+ });
165
+ process.stdout.write(output);
166
+ }
167
+ process.exit(0);
168
+ } catch (error) {
169
+ log(`Error: ${error instanceof Error ? error.message : String(error)}`);
170
+ process.exit(0);
267
171
  }
268
172
  }
269
173
  main();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/tokenizer.ts","../../src/hooks/post-tool-result.ts"],"sourcesContent":["/**\n * Token estimation utilities.\n * Uses whitespace heuristic (~90% accuracy vs GPT tokenizer).\n */\n\n/**\n * Estimate token count for text using heuristic.\n *\n * Approximation: 1 token ≈ 4 chars or 0.75 words\n * Provides ~90% accuracy compared to GPT tokenizer, sufficient for optimization heuristics.\n *\n * @param text - Text to count\n * @returns Estimated token count\n *\n * @example\n * ```typescript\n * const tokens = estimateTokens('Hello world');\n * console.log(tokens); // ~2\n * ```\n */\nexport function estimateTokens(text: string): number {\n if (!text || text.length === 0) {\n return 0;\n }\n\n // Split on whitespace to get words\n const words = text.split(/\\s+/).filter((w) => w.length > 0);\n const wordCount = words.length;\n\n // Character-based estimate\n const charCount = text.length;\n const charEstimate = Math.ceil(charCount / 4);\n\n // Word-based estimate\n const wordEstimate = Math.ceil(wordCount * 0.75);\n\n // Return the maximum of both estimates (more conservative)\n return Math.max(wordEstimate, charEstimate);\n}\n","#!/usr/bin/env node\n/**\n * Post-Tool-Result Hook - Claude Code hook for compressing verbose tool output\n *\n * Compresses large tool results using type-specific strategies:\n * - File reads: Truncate long files, show first/last N lines\n * - Grep results: Group by file, show match count + samples\n * - Git diffs: Summarize file changes, show stats\n * - Build output: Extract errors/warnings only\n *\n * CRITICAL: Always exits 0 (never disrupts Claude Code).\n * Falls through unmodified on error or if already small.\n */\n\nimport { estimateTokens } from '../utils/tokenizer.js';\n\n// Exit 0 wrapper for all errors\nfunction exitSuccess(output: string): void {\n process.stdout.write(output);\n process.exit(0);\n}\n\n// Compression threshold (only compress if over this many tokens)\nconst COMPRESSION_THRESHOLD = 5000;\n\n// Tool result patterns\nconst TOOL_PATTERNS = {\n fileRead: /<file_path>(.*?)<\\/file_path>[\\s\\S]*?<content>([\\s\\S]*?)<\\/content>/,\n grepResult: /<pattern>(.*?)<\\/pattern>[\\s\\S]*?<matches>([\\s\\S]*?)<\\/matches>/,\n gitDiff: /^diff --git/m,\n buildOutput: /(error|warning|failed|failure)/i,\n npmInstall: /^(npm|pnpm|yarn) (install|add|i)/m,\n dockerLogs: /^\\[?\\d{4}-\\d{2}-\\d{2}/m,\n testResults: /(PASS|FAIL|SKIP).*?\\.test\\./i,\n typescriptErrors: /^.*\\(\\d+,\\d+\\): error TS\\d+:/m,\n webpackBuild: /webpack \\d+\\.\\d+\\.\\d+/i,\n};\n\n/**\n * Compress file read results\n */\nfunction compressFileRead(content: string, maxLines = 100): string {\n const lines = content.split('\\n');\n\n if (lines.length <= maxLines * 2) {\n return content; // Already small enough\n }\n\n const head = lines.slice(0, maxLines);\n const tail = lines.slice(-maxLines);\n const omitted = lines.length - maxLines * 2;\n\n return [...head, '', `... [${omitted} lines omitted] ...`, '', ...tail].join('\\n');\n}\n\n/**\n * Compress grep results\n */\nfunction compressGrepResults(content: string, maxMatchesPerFile = 5): string {\n const lines = content.split('\\n');\n const fileMatches = new Map<string, string[]>();\n\n // Group matches by file\n for (const line of lines) {\n const match = line.match(/^(.*?):(\\d+):(.*)/);\n if (match?.[1] && match[2] && match[3]) {\n const file = match[1];\n const lineNum = match[2];\n const text = match[3];\n if (!fileMatches.has(file)) {\n fileMatches.set(file, []);\n }\n fileMatches.get(file)?.push(` Line ${lineNum}: ${text.trim()}`);\n }\n }\n\n // Build compressed output\n const compressed: string[] = [];\n\n for (const [file, matches] of fileMatches.entries()) {\n compressed.push(`${file} (${matches.length} matches):`);\n\n if (matches.length <= maxMatchesPerFile) {\n compressed.push(...matches);\n } else {\n compressed.push(...matches.slice(0, maxMatchesPerFile));\n compressed.push(` ... and ${matches.length - maxMatchesPerFile} more matches`);\n }\n\n compressed.push('');\n }\n\n return compressed.join('\\n');\n}\n\n/**\n * Compress git diff results\n */\nfunction compressGitDiff(content: string): string {\n const lines = content.split('\\n');\n const files = new Map<string, { added: number; removed: number }>();\n let currentFile = '';\n\n for (const line of lines) {\n if (line.startsWith('diff --git')) {\n const match = line.match(/diff --git a\\/(.*?) b\\/(.*)/);\n if (match) {\n currentFile = match[2] || '';\n files.set(currentFile, { added: 0, removed: 0 });\n }\n } else if (line.startsWith('+') && !line.startsWith('+++')) {\n const stats = files.get(currentFile);\n if (stats) stats.added++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n const stats = files.get(currentFile);\n if (stats) stats.removed++;\n }\n }\n\n // Build summary\n const summary: string[] = ['Git diff summary:'];\n\n for (const [file, stats] of files.entries()) {\n summary.push(` ${file}: +${stats.added} -${stats.removed}`);\n }\n\n return summary.join('\\n');\n}\n\n/**\n * Compress build output (extract errors/warnings only)\n */\nfunction compressBuildOutput(content: string): string {\n const lines = content.split('\\n');\n const important: string[] = [];\n\n for (const line of lines) {\n if (/(error|warning|failed|failure|fatal)/i.test(line)) {\n important.push(line);\n }\n }\n\n if (important.length === 0) {\n return 'Build output: No errors or warnings found';\n }\n\n return ['Build errors/warnings:', ...important].join('\\n');\n}\n\n/**\n * Compress npm/pnpm install output\n */\nfunction compressNpmInstall(content: string): string {\n const lines = content.split('\\n');\n const summary: string[] = [];\n\n // Extract package count and warnings/errors\n const warnings: string[] = [];\n const errors: string[] = [];\n\n for (const line of lines) {\n if (/added \\d+ packages?/i.test(line)) {\n summary.push(line.trim());\n }\n if (/warn/i.test(line)) {\n warnings.push(line.trim());\n }\n if (/error/i.test(line)) {\n errors.push(line.trim());\n }\n }\n\n if (errors.length > 0) {\n return ['Package installation errors:', ...errors.slice(0, 5)].join('\\n');\n }\n\n if (warnings.length > 0) {\n return [\n 'Package installation completed with warnings:',\n ...warnings.slice(0, 3),\n warnings.length > 3 ? `... and ${warnings.length - 3} more warnings` : '',\n ]\n .filter(Boolean)\n .join('\\n');\n }\n\n return summary.length > 0 ? summary.join('\\n') : 'Package installation completed successfully';\n}\n\n/**\n * Compress Docker logs\n */\nfunction compressDockerLogs(content: string): string {\n const lines = content.split('\\n');\n const logMap = new Map<string, number>();\n\n // Deduplicate and count repeated lines\n for (const line of lines) {\n // Strip timestamps for deduplication\n const normalized = line.replace(/^\\[?\\d{4}-\\d{2}-\\d{2}.*?\\]\\s*/, '').trim();\n if (normalized) {\n logMap.set(normalized, (logMap.get(normalized) || 0) + 1);\n }\n }\n\n const summary: string[] = ['Docker logs (deduplicated):'];\n\n for (const [log, count] of Array.from(logMap.entries()).slice(0, 20)) {\n if (count > 1) {\n summary.push(` [${count}x] ${log}`);\n } else {\n summary.push(` ${log}`);\n }\n }\n\n if (logMap.size > 20) {\n summary.push(` ... and ${logMap.size - 20} more unique log lines`);\n }\n\n return summary.join('\\n');\n}\n\n/**\n * Compress test results\n */\nfunction compressTestResults(content: string): string {\n const lines = content.split('\\n');\n let passed = 0;\n let failed = 0;\n let skipped = 0;\n const failures: string[] = [];\n\n for (const line of lines) {\n if (/PASS/i.test(line)) passed++;\n if (/FAIL/i.test(line)) {\n failed++;\n failures.push(line.trim());\n }\n if (/SKIP/i.test(line)) skipped++;\n }\n\n const summary = [`Test Results: ${passed} passed, ${failed} failed, ${skipped} skipped`];\n\n if (failures.length > 0) {\n summary.push('', 'Failed tests:');\n summary.push(...failures.slice(0, 10));\n if (failures.length > 10) {\n summary.push(`... and ${failures.length - 10} more failures`);\n }\n }\n\n return summary.join('\\n');\n}\n\n/**\n * Compress TypeScript errors\n */\nfunction compressTypescriptErrors(content: string): string {\n const lines = content.split('\\n');\n const errorMap = new Map<string, string[]>();\n\n for (const line of lines) {\n const match = line.match(/^(.*?)\\(\\d+,\\d+\\): error (TS\\d+):/);\n if (match) {\n const file = match[1] || 'unknown';\n const errorCode = match[2] || 'TS0000';\n const key = `${file}:${errorCode}`;\n\n if (!errorMap.has(key)) {\n errorMap.set(key, []);\n }\n errorMap.get(key)?.push(line);\n }\n }\n\n const summary = ['TypeScript Errors (grouped by file):'];\n\n for (const [key, errors] of errorMap.entries()) {\n summary.push(` ${key} (${errors.length} errors)`);\n summary.push(` ${errors[0]}`);\n }\n\n return summary.join('\\n');\n}\n\n/**\n * Main compression logic\n */\nfunction compressToolResult(input: string): string {\n const tokens = estimateTokens(input);\n\n // Only compress if over threshold\n if (tokens < COMPRESSION_THRESHOLD) {\n return input;\n }\n\n // Detect tool result type and compress accordingly\n if (TOOL_PATTERNS.fileRead.test(input)) {\n const match = input.match(TOOL_PATTERNS.fileRead);\n if (match?.[2]) {\n const content = match[2];\n const compressed = compressFileRead(content);\n return input.replace(content, compressed);\n }\n }\n\n if (TOOL_PATTERNS.grepResult.test(input)) {\n const match = input.match(TOOL_PATTERNS.grepResult);\n if (match?.[2]) {\n const matches = match[2];\n const compressed = compressGrepResults(matches);\n return input.replace(matches, compressed);\n }\n }\n\n if (TOOL_PATTERNS.gitDiff.test(input)) {\n return compressGitDiff(input);\n }\n\n if (TOOL_PATTERNS.buildOutput.test(input)) {\n return compressBuildOutput(input);\n }\n\n if (TOOL_PATTERNS.npmInstall.test(input)) {\n return compressNpmInstall(input);\n }\n\n if (TOOL_PATTERNS.dockerLogs.test(input)) {\n return compressDockerLogs(input);\n }\n\n if (TOOL_PATTERNS.testResults.test(input)) {\n return compressTestResults(input);\n }\n\n if (TOOL_PATTERNS.typescriptErrors.test(input)) {\n return compressTypescriptErrors(input);\n }\n\n // Unknown type or no compression pattern matched\n // Apply generic truncation as fallback\n const lines = input.split('\\n');\n if (lines.length > 200) {\n return compressFileRead(input, 100);\n }\n\n return input;\n}\n\n// Main hook logic\nasync function main(): Promise<void> {\n try {\n // Read stdin (tool result)\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n const input = Buffer.concat(chunks).toString('utf-8');\n\n // Compress if needed\n const output = compressToolResult(input);\n\n exitSuccess(output);\n } catch (_error) {\n // On any error, pass through original input\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n const input = Buffer.concat(chunks).toString('utf-8');\n exitSuccess(input);\n }\n}\n\n// Run hook\nmain();\n"],"mappings":";;;;AAoBO,SAAS,eAA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Q,OAAO,OAAO,MAAM,EAAE,SAAS,OAAO;AAGpD,UAAM,SAAS,mBAAmB,KAAK;AAEvC,gBAAY,MAAM;AAAA,EACpB,SAAS,QAAQ;AAEf,UAAM,SAAmB,CAAC;AAC1B,qBAAiB,SAAS,QAAQ,OAAO;AACvC,aAAO,KAAK,KAAK;AAAA,IACnB;AACA,UAAM,QAAQ,OAAO,OAAO,MAAM,EAAE,SAAS,OAAO;AACpD,gBAAY,KAAK;AAAA,EACnB;AACF;AAGA,KAAK;","names":[]}
1
+ {"version":3,"sources":["../../src/hooks/post-tool-result.ts","../../src/utils/tokenizer.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * PostToolUse Hook - Compresses verbose tool output\n *\n * After tools like Bash, Read, Grep execute, this hook checks if\n * the output is very large and adds a compressed summary as\n * additionalContext so Claude can quickly reference key information.\n *\n * CRITICAL: Always exits 0 (never disrupts Claude Code).\n */\n\nimport { appendFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { estimateTokens } from '../utils/tokenizer.js';\n\nconst DEBUG = process.env['SPARN_DEBUG'] === 'true';\nconst LOG_FILE = process.env['SPARN_LOG_FILE'] || join(homedir(), '.sparn-hook.log');\n\n// Only add summaries for outputs over this many estimated tokens\nconst SUMMARY_THRESHOLD = 3000;\n\nfunction log(message: string): void {\n if (DEBUG) {\n const timestamp = new Date().toISOString();\n appendFileSync(LOG_FILE, `[${timestamp}] [post-tool] ${message}\\n`);\n }\n}\n\ninterface HookInput {\n session_id?: string;\n hook_event_name?: string;\n tool_name?: string;\n tool_use_id?: string;\n tool_input?: Record<string, unknown>;\n tool_response?: unknown;\n}\n\nfunction extractText(response: unknown): string {\n if (typeof response === 'string') return response;\n if (response && typeof response === 'object') {\n return JSON.stringify(response);\n }\n return String(response ?? '');\n}\n\n/**\n * Summarize large bash output\n */\nfunction summarizeBash(text: string, command: string): string {\n const lines = text.split('\\n');\n\n // Check for test results\n if (/\\d+ (pass|fail|skip)/i.test(text) || /Tests?:/i.test(text)) {\n const resultLines = lines.filter(\n (l) => /(pass|fail|skip|error|Tests?:|Test Suites?:)/i.test(l) || /^\\s*(PASS|FAIL)\\s/.test(l),\n );\n if (resultLines.length > 0) {\n return `[sparn] Test output summary (${lines.length} lines):\\n${resultLines.slice(0, 15).join('\\n')}`;\n }\n }\n\n // Check for build errors\n if (/(error|warning|failed)/i.test(text)) {\n const errorLines = lines.filter((l) => /(error|warning|failed|fatal)/i.test(l));\n if (errorLines.length > 0) {\n return `[sparn] Build output summary (${errorLines.length} errors/warnings from ${lines.length} lines):\\n${errorLines.slice(0, 10).join('\\n')}`;\n }\n }\n\n // Check for git diff\n if (/^diff --git/m.test(text)) {\n const files: string[] = [];\n for (const line of lines) {\n const match = line.match(/^diff --git a\\/(.*?) b\\/(.*)/);\n if (match?.[2]) files.push(match[2]);\n }\n return `[sparn] Git diff: ${files.length} files changed: ${files.join(', ')}`;\n }\n\n // Generic: show line count and first/last few lines\n return `[sparn] Command \\`${command}\\` produced ${lines.length} lines of output. First 3: ${lines.slice(0, 3).join(' | ')}`;\n}\n\n/**\n * Summarize large file read\n */\nfunction summarizeFileRead(text: string, filePath: string): string {\n const lines = text.split('\\n');\n const tokens = estimateTokens(text);\n\n // Find key structures\n const exports = lines.filter((l) => /^export\\s/.test(l.trim()));\n const functions = lines.filter((l) => /function\\s+\\w+/.test(l));\n const classes = lines.filter((l) => /class\\s+\\w+/.test(l));\n\n const parts = [`[sparn] File ${filePath}: ${lines.length} lines, ~${tokens} tokens.`];\n\n if (exports.length > 0) {\n parts.push(\n `Exports: ${exports\n .slice(0, 5)\n .map((e) => e.trim().substring(0, 60))\n .join('; ')}`,\n );\n }\n if (functions.length > 0) {\n parts.push(\n `Functions: ${functions\n .slice(0, 5)\n .map((f) => f.trim().substring(0, 40))\n .join(', ')}`,\n );\n }\n if (classes.length > 0) {\n parts.push(`Classes: ${classes.map((c) => c.trim().substring(0, 40)).join(', ')}`);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Summarize grep/search results\n */\nfunction summarizeSearch(text: string, pattern: string): string {\n const lines = text.split('\\n').filter((l) => l.trim().length > 0);\n const fileMap = new Map<string, number>();\n\n for (const line of lines) {\n const match = line.match(/^(.*?):\\d+:/);\n if (match?.[1]) {\n fileMap.set(match[1], (fileMap.get(match[1]) || 0) + 1);\n }\n }\n\n if (fileMap.size > 0) {\n const summary = Array.from(fileMap.entries())\n .slice(0, 5)\n .map(([f, c]) => `${f} (${c})`)\n .join(', ');\n return `[sparn] Search for \"${pattern}\": ${lines.length} matches across ${fileMap.size} files. Top files: ${summary}`;\n }\n\n return `[sparn] Search for \"${pattern}\": ${lines.length} result lines`;\n}\n\nasync function main(): Promise<void> {\n try {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n const raw = Buffer.concat(chunks).toString('utf-8');\n\n let input: HookInput;\n try {\n input = JSON.parse(raw);\n } catch {\n log('Failed to parse JSON input');\n process.exit(0);\n return;\n }\n\n const toolName = input.tool_name ?? 'unknown';\n const text = extractText(input.tool_response);\n const tokens = estimateTokens(text);\n\n log(`Tool: ${toolName}, response tokens: ~${tokens}`);\n\n if (tokens < SUMMARY_THRESHOLD) {\n log('Under threshold, no summary needed');\n process.exit(0);\n return;\n }\n\n let summary = '';\n\n switch (toolName) {\n case 'Bash': {\n const command = String(input.tool_input?.['command'] ?? '');\n summary = summarizeBash(text, command);\n break;\n }\n case 'Read': {\n const filePath = String(input.tool_input?.['file_path'] ?? '');\n summary = summarizeFileRead(text, filePath);\n break;\n }\n case 'Grep': {\n const pattern = String(input.tool_input?.['pattern'] ?? '');\n summary = summarizeSearch(text, pattern);\n break;\n }\n default: {\n const lines = text.split('\\n');\n summary = `[sparn] ${toolName} output: ${lines.length} lines, ~${tokens} tokens`;\n break;\n }\n }\n\n if (summary) {\n log(`Summary: ${summary.substring(0, 100)}`);\n const output = JSON.stringify({\n hookSpecificOutput: {\n hookEventName: 'PostToolUse',\n additionalContext: summary,\n },\n });\n process.stdout.write(output);\n }\n\n process.exit(0);\n } catch (error) {\n log(`Error: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(0);\n }\n}\n\nmain();\n","/**\n * Token estimation utilities.\n * Supports both heuristic (~90% accuracy) and precise (GPT tokenizer, ~95%+ accuracy) modes.\n */\n\nimport { encode } from 'gpt-tokenizer';\n\n/** Module-level flag for precise token counting */\nlet usePrecise = false;\n\n/**\n * Enable or disable precise token counting using GPT tokenizer.\n * When enabled, estimateTokens() uses gpt-tokenizer for ~95%+ accuracy on code.\n * When disabled (default), uses fast whitespace heuristic.\n *\n * @param enabled - Whether to use precise counting\n */\nexport function setPreciseTokenCounting(enabled: boolean): void {\n usePrecise = enabled;\n}\n\n/**\n * Count tokens precisely using GPT tokenizer.\n *\n * @param text - Text to count\n * @returns Exact token count\n */\nexport function countTokensPrecise(text: string): number {\n if (!text || text.length === 0) {\n return 0;\n }\n return encode(text).length;\n}\n\n/**\n * Estimate token count for text.\n *\n * In default (heuristic) mode: ~90% accuracy, very fast.\n * In precise mode: ~95%+ accuracy using GPT tokenizer.\n *\n * @param text - Text to count\n * @returns Estimated token count\n */\nexport function estimateTokens(text: string): number {\n if (!text || text.length === 0) {\n return 0;\n }\n\n if (usePrecise) {\n return encode(text).length;\n }\n\n // Split on whitespace to get words\n const words = text.split(/\\s+/).filter((w) => w.length > 0);\n const wordCount = words.length;\n\n // Character-based estimate\n const charCount = text.length;\n const charEstimate = Math.ceil(charCount / 4);\n\n // Word-based estimate\n const wordEstimate = Math.ceil(wordCount * 0.75);\n\n // Return the maximum of both estimates (more conservative)\n return Math.max(wordEstimate, charEstimate);\n}\n"],"mappings":";;;;AAWA,qBAA+B;AAC/B,qBAAwB;AACxB,uBAAqB;;;ACRrB,2BAAuB;AAGvB,IAAI,aAAa;AAmCV,SAAS,eAAe,MAAsB;AACnD,MAAI,CAAC,QAAQ,KAAK,WAAW,GAAG;AAC9B,WAAO;AAAA,EACT;AAEA,MAAI,YAAY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