@pimzino/sgrep 1.3.21 → 1.3.26

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.
@@ -1,183 +1,183 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const { execSync } = require("child_process");
6
- const os = require("os");
7
-
8
- const DEBUG_ENABLED = process.env.SGREP_DEBUG === "1" || process.env.SGREP_DEBUG === "true";
9
- const DEBUG_LOG_FILE = process.env.SGREP_ENHANCE_LOG || path.join(os.tmpdir(), "sgrep-enhance.log");
10
-
11
- // Lightweight reminder injected with every prompt (exploits recency bias)
12
- const SGREP_REMINDER = `<mandatory>Use sgrep "question" for explanations or sgrep search "query" for code snippets via Bash BEFORE Read/Grep/Glob.</mandatory>`;
13
-
14
- function debugLog(message) {
15
- if (!DEBUG_ENABLED) return;
16
- try {
17
- const dir = path.dirname(DEBUG_LOG_FILE);
18
- if (!fs.existsSync(dir)) {
19
- fs.mkdirSync(dir, { recursive: true });
20
- }
21
- const stamp = new Date().toISOString();
22
- fs.appendFileSync(DEBUG_LOG_FILE, `[${stamp}] ${message}\n`);
23
- } catch (e) {
24
- // Ignore errors
25
- }
26
- }
27
-
28
- function debugLogSection(title, content) {
29
- debugLog(`\n========== ${title} ==========`);
30
- debugLog(content);
31
- debugLog(`========== END ${title} ==========\n`);
32
- }
33
-
34
- function readHookInput() {
35
- return new Promise((resolve) => {
36
- let data = "";
37
- process.stdin.setEncoding("utf8");
38
- process.stdin.on("data", (chunk) => {
39
- data += chunk;
40
- });
41
- process.stdin.on("end", () => {
42
- if (!data.trim()) {
43
- debugLog("No input data received from stdin");
44
- resolve(null);
45
- return;
46
- }
47
- try {
48
- const parsed = JSON.parse(data);
49
- debugLogSection("RAW HOOK INPUT", JSON.stringify(parsed, null, 2));
50
- resolve(parsed);
51
- } catch (e) {
52
- debugLog(`Failed to decode JSON: ${e.message}`);
53
- debugLog(`Raw data: ${data}`);
54
- resolve(null);
55
- }
56
- });
57
- });
58
- }
59
-
60
- /**
61
- * Determine if enhancement should proceed.
62
- * Auto-confirms on all platforms (no user prompting).
63
- */
64
- function shouldEnhance(prompt) {
65
- debugLog("Auto-confirming enhancement (prompting disabled on all platforms)");
66
- return true;
67
- }
68
-
69
- /**
70
- * Output the hook response with optional enhanced context and mandatory reminder.
71
- * Always includes the sgrep reminder to exploit recency bias.
72
- */
73
- function outputResponse(enhancedContext = null) {
74
- const parts = [];
75
-
76
- if (enhancedContext) {
77
- parts.push(`[sgrep enhanced context]\n${enhancedContext}`);
78
- }
79
-
80
- // Always append the reminder (exploits recency bias - appears fresh with every prompt)
81
- parts.push(SGREP_REMINDER);
82
-
83
- const response = {
84
- hookSpecificOutput: {
85
- hookEventName: "UserPromptSubmit",
86
- additionalContext: parts.join("\n\n")
87
- }
88
- };
89
-
90
- debugLogSection("HOOK RESPONSE", JSON.stringify(response, null, 2));
91
- console.log(JSON.stringify(response));
92
- }
93
-
94
- async function main() {
95
- debugLog("\n\n====================================================");
96
- debugLog("SGREP ENHANCE HOOK TRIGGERED - UserPromptSubmit");
97
- debugLog("====================================================");
98
-
99
- const payload = await readHookInput();
100
- if (!payload) {
101
- debugLog("ERROR: No payload received - exiting");
102
- process.exit(0);
103
- }
104
-
105
- // Log all payload fields
106
- debugLog(`Hook Event: ${payload.hook_event_name || 'unknown'}`);
107
- debugLog(`Session ID: ${payload.session_id || 'unknown'}`);
108
- debugLog(`CWD: ${payload.cwd || 'unknown'}`);
109
- debugLog(`Permission Mode: ${payload.permission_mode || 'unknown'}`);
110
-
111
- const prompt = payload.prompt || "";
112
- debugLogSection("ORIGINAL PROMPT", prompt);
113
-
114
- // Skip enhancement for very short prompts or slash commands, but still inject reminder
115
- if (prompt.length < 10) {
116
- debugLog("SKIP enhancement: Prompt too short (< 10 chars), but injecting reminder");
117
- outputResponse(null);
118
- debugLog("====================================================\n");
119
- process.exit(0);
120
- }
121
- if (prompt.startsWith("/")) {
122
- debugLog("SKIP enhancement: Prompt is a slash command, but injecting reminder");
123
- outputResponse(null);
124
- debugLog("====================================================\n");
125
- process.exit(0);
126
- }
127
-
128
- // Check if enhancement should proceed (auto-confirms on all platforms)
129
- debugLog("Checking if enhancement should proceed...");
130
- const shouldProceed = shouldEnhance(prompt);
131
- debugLog(`Enhancement decision: ${shouldProceed ? 'proceeding' : 'skipped'}`);
132
-
133
- if (!shouldProceed) {
134
- debugLog("SKIP enhancement: Not proceeding, but injecting reminder");
135
- outputResponse(null);
136
- debugLog("====================================================\n");
137
- process.exit(0);
138
- }
139
-
140
- let enhancedContext = null;
141
-
142
- try {
143
- // Call sgrep enhance with JSON output
144
- debugLog("Calling: sgrep enhance --json \"<prompt>\"");
145
-
146
- // Escape the prompt for shell
147
- const escapedPrompt = prompt.replace(/"/g, '\\"').replace(/\n/g, ' ');
148
-
149
- const result = execSync(`sgrep enhance --json "${escapedPrompt}"`, {
150
- encoding: "utf8",
151
- timeout: 60000, // 60 second timeout
152
- stdio: ["pipe", "pipe", "pipe"],
153
- });
154
-
155
- debugLogSection("SGREP ENHANCE RAW RESULT", result);
156
-
157
- // Parse the JSON result
158
- const parsed = JSON.parse(result);
159
- const enhanced = parsed.enhanced || null;
160
-
161
- if (enhanced && enhanced !== prompt) {
162
- debugLogSection("ENHANCED PROMPT", enhanced);
163
- enhancedContext = enhanced;
164
- debugLog("SUCCESS: Enhancement complete");
165
- } else {
166
- debugLog("SKIP: No enhanced prompt or same as original");
167
- }
168
- } catch (e) {
169
- debugLog(`ERROR: Enhancement failed - ${e.message}`);
170
- if (e.stderr) {
171
- debugLog(`STDERR: ${e.stderr}`);
172
- }
173
- // Continue to output reminder even on error
174
- }
175
-
176
- // Always output response with reminder (and enhanced context if available)
177
- outputResponse(enhancedContext);
178
-
179
- debugLog("====================================================\n");
180
- process.exit(0);
181
- }
182
-
183
- main();
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { execSync } = require("child_process");
6
+ const os = require("os");
7
+
8
+ const DEBUG_ENABLED = process.env.SGREP_DEBUG === "1" || process.env.SGREP_DEBUG === "true";
9
+ const DEBUG_LOG_FILE = process.env.SGREP_ENHANCE_LOG || path.join(os.tmpdir(), "sgrep-enhance.log");
10
+
11
+ // Lightweight reminder injected with every prompt (exploits recency bias)
12
+ const SGREP_REMINDER = `<mandatory>Use sgrep "question" for explanations or sgrep search "query" for code snippets via Bash BEFORE Read/Grep/Glob.</mandatory>`;
13
+
14
+ function debugLog(message) {
15
+ if (!DEBUG_ENABLED) return;
16
+ try {
17
+ const dir = path.dirname(DEBUG_LOG_FILE);
18
+ if (!fs.existsSync(dir)) {
19
+ fs.mkdirSync(dir, { recursive: true });
20
+ }
21
+ const stamp = new Date().toISOString();
22
+ fs.appendFileSync(DEBUG_LOG_FILE, `[${stamp}] ${message}\n`);
23
+ } catch (e) {
24
+ // Ignore errors
25
+ }
26
+ }
27
+
28
+ function debugLogSection(title, content) {
29
+ debugLog(`\n========== ${title} ==========`);
30
+ debugLog(content);
31
+ debugLog(`========== END ${title} ==========\n`);
32
+ }
33
+
34
+ function readHookInput() {
35
+ return new Promise((resolve) => {
36
+ let data = "";
37
+ process.stdin.setEncoding("utf8");
38
+ process.stdin.on("data", (chunk) => {
39
+ data += chunk;
40
+ });
41
+ process.stdin.on("end", () => {
42
+ if (!data.trim()) {
43
+ debugLog("No input data received from stdin");
44
+ resolve(null);
45
+ return;
46
+ }
47
+ try {
48
+ const parsed = JSON.parse(data);
49
+ debugLogSection("RAW HOOK INPUT", JSON.stringify(parsed, null, 2));
50
+ resolve(parsed);
51
+ } catch (e) {
52
+ debugLog(`Failed to decode JSON: ${e.message}`);
53
+ debugLog(`Raw data: ${data}`);
54
+ resolve(null);
55
+ }
56
+ });
57
+ });
58
+ }
59
+
60
+ /**
61
+ * Determine if enhancement should proceed.
62
+ * Auto-confirms on all platforms (no user prompting).
63
+ */
64
+ function shouldEnhance(prompt) {
65
+ debugLog("Auto-confirming enhancement (prompting disabled on all platforms)");
66
+ return true;
67
+ }
68
+
69
+ /**
70
+ * Output the hook response with optional enhanced context and mandatory reminder.
71
+ * Always includes the sgrep reminder to exploit recency bias.
72
+ */
73
+ function outputResponse(enhancedContext = null) {
74
+ const parts = [];
75
+
76
+ if (enhancedContext) {
77
+ parts.push(`[sgrep enhanced context]\n${enhancedContext}`);
78
+ }
79
+
80
+ // Always append the reminder (exploits recency bias - appears fresh with every prompt)
81
+ parts.push(SGREP_REMINDER);
82
+
83
+ const response = {
84
+ hookSpecificOutput: {
85
+ hookEventName: "UserPromptSubmit",
86
+ additionalContext: parts.join("\n\n")
87
+ }
88
+ };
89
+
90
+ debugLogSection("HOOK RESPONSE", JSON.stringify(response, null, 2));
91
+ console.log(JSON.stringify(response));
92
+ }
93
+
94
+ async function main() {
95
+ debugLog("\n\n====================================================");
96
+ debugLog("SGREP ENHANCE HOOK TRIGGERED - UserPromptSubmit");
97
+ debugLog("====================================================");
98
+
99
+ const payload = await readHookInput();
100
+ if (!payload) {
101
+ debugLog("ERROR: No payload received - exiting");
102
+ process.exit(0);
103
+ }
104
+
105
+ // Log all payload fields
106
+ debugLog(`Hook Event: ${payload.hook_event_name || 'unknown'}`);
107
+ debugLog(`Session ID: ${payload.session_id || 'unknown'}`);
108
+ debugLog(`CWD: ${payload.cwd || 'unknown'}`);
109
+ debugLog(`Permission Mode: ${payload.permission_mode || 'unknown'}`);
110
+
111
+ const prompt = payload.prompt || "";
112
+ debugLogSection("ORIGINAL PROMPT", prompt);
113
+
114
+ // Skip enhancement for very short prompts or slash commands, but still inject reminder
115
+ if (prompt.length < 10) {
116
+ debugLog("SKIP enhancement: Prompt too short (< 10 chars), but injecting reminder");
117
+ outputResponse(null);
118
+ debugLog("====================================================\n");
119
+ process.exit(0);
120
+ }
121
+ if (prompt.startsWith("/")) {
122
+ debugLog("SKIP enhancement: Prompt is a slash command, but injecting reminder");
123
+ outputResponse(null);
124
+ debugLog("====================================================\n");
125
+ process.exit(0);
126
+ }
127
+
128
+ // Check if enhancement should proceed (auto-confirms on all platforms)
129
+ debugLog("Checking if enhancement should proceed...");
130
+ const shouldProceed = shouldEnhance(prompt);
131
+ debugLog(`Enhancement decision: ${shouldProceed ? 'proceeding' : 'skipped'}`);
132
+
133
+ if (!shouldProceed) {
134
+ debugLog("SKIP enhancement: Not proceeding, but injecting reminder");
135
+ outputResponse(null);
136
+ debugLog("====================================================\n");
137
+ process.exit(0);
138
+ }
139
+
140
+ let enhancedContext = null;
141
+
142
+ try {
143
+ // Call sgrep enhance with JSON output
144
+ debugLog("Calling: sgrep enhance --json \"<prompt>\"");
145
+
146
+ // Escape the prompt for shell
147
+ const escapedPrompt = prompt.replace(/"/g, '\\"').replace(/\n/g, ' ');
148
+
149
+ const result = execSync(`sgrep enhance --json "${escapedPrompt}"`, {
150
+ encoding: "utf8",
151
+ timeout: 60000, // 60 second timeout
152
+ stdio: ["pipe", "pipe", "pipe"],
153
+ });
154
+
155
+ debugLogSection("SGREP ENHANCE RAW RESULT", result);
156
+
157
+ // Parse the JSON result
158
+ const parsed = JSON.parse(result);
159
+ const enhanced = parsed.enhanced || null;
160
+
161
+ if (enhanced && enhanced !== prompt) {
162
+ debugLogSection("ENHANCED PROMPT", enhanced);
163
+ enhancedContext = enhanced;
164
+ debugLog("SUCCESS: Enhancement complete");
165
+ } else {
166
+ debugLog("SKIP: No enhanced prompt or same as original");
167
+ }
168
+ } catch (e) {
169
+ debugLog(`ERROR: Enhancement failed - ${e.message}`);
170
+ if (e.stderr) {
171
+ debugLog(`STDERR: ${e.stderr}`);
172
+ }
173
+ // Continue to output reminder even on error
174
+ }
175
+
176
+ // Always output response with reminder (and enhanced context if available)
177
+ outputResponse(enhancedContext);
178
+
179
+ debugLog("====================================================\n");
180
+ process.exit(0);
181
+ }
182
+
183
+ main();