@the-magic-tower/fixhive-opencode-plugin 0.1.21 → 0.1.23

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/dist/index.js CHANGED
@@ -1,10 +1,14 @@
1
1
  // src/plugin/index.ts
2
2
  import { tool as tool2 } from "@opencode-ai/plugin";
3
- import { existsSync as existsSync2, readFileSync } from "node:fs";
4
- import { join } from "node:path";
3
+ import { existsSync as existsSync2, readFileSync } from "fs";
4
+ import { join } from "path";
5
5
 
6
6
  // src/core/privacy-filter.ts
7
7
  var DEFAULT_FILTER_RULES = [
8
+ // =====================================
9
+ // SECRETS (Critical - Always Filter)
10
+ // =====================================
11
+ // AWS Keys
8
12
  {
9
13
  name: "aws_access_key",
10
14
  category: "secret",
@@ -12,6 +16,7 @@ var DEFAULT_FILTER_RULES = [
12
16
  replacement: "[AWS_KEY_REDACTED]",
13
17
  priority: 100
14
18
  },
19
+ // OpenAI API Keys
15
20
  {
16
21
  name: "openai_key",
17
22
  category: "secret",
@@ -19,6 +24,7 @@ var DEFAULT_FILTER_RULES = [
19
24
  replacement: "[OPENAI_KEY_REDACTED]",
20
25
  priority: 100
21
26
  },
27
+ // GitHub Tokens
22
28
  {
23
29
  name: "github_token",
24
30
  category: "secret",
@@ -26,6 +32,7 @@ var DEFAULT_FILTER_RULES = [
26
32
  replacement: "[GITHUB_TOKEN_REDACTED]",
27
33
  priority: 100
28
34
  },
35
+ // Google API Keys
29
36
  {
30
37
  name: "google_api_key",
31
38
  category: "secret",
@@ -33,6 +40,7 @@ var DEFAULT_FILTER_RULES = [
33
40
  replacement: "[GOOGLE_API_KEY_REDACTED]",
34
41
  priority: 100
35
42
  },
43
+ // Stripe Keys
36
44
  {
37
45
  name: "stripe_key",
38
46
  category: "secret",
@@ -40,6 +48,7 @@ var DEFAULT_FILTER_RULES = [
40
48
  replacement: "[STRIPE_KEY_REDACTED]",
41
49
  priority: 100
42
50
  },
51
+ // JWT Tokens (limited length to prevent ReDoS)
43
52
  {
44
53
  name: "jwt_token",
45
54
  category: "secret",
@@ -47,6 +56,7 @@ var DEFAULT_FILTER_RULES = [
47
56
  replacement: "[JWT_REDACTED]",
48
57
  priority: 100
49
58
  },
59
+ // Bearer Tokens
50
60
  {
51
61
  name: "bearer_token",
52
62
  category: "secret",
@@ -54,6 +64,7 @@ var DEFAULT_FILTER_RULES = [
54
64
  replacement: "$1 [TOKEN_REDACTED]",
55
65
  priority: 100
56
66
  },
67
+ // Private Keys
57
68
  {
58
69
  name: "private_key",
59
70
  category: "secret",
@@ -61,6 +72,7 @@ var DEFAULT_FILTER_RULES = [
61
72
  replacement: "[PRIVATE_KEY_REDACTED]",
62
73
  priority: 100
63
74
  },
75
+ // Generic API Keys (context-based, limited length to prevent ReDoS)
64
76
  {
65
77
  name: "generic_api_key",
66
78
  category: "secret",
@@ -68,6 +80,7 @@ var DEFAULT_FILTER_RULES = [
68
80
  replacement: "$1=[KEY_REDACTED]",
69
81
  priority: 95
70
82
  },
83
+ // Secret/Password assignments (limited length to prevent ReDoS)
71
84
  {
72
85
  name: "secret_assignment",
73
86
  category: "secret",
@@ -75,6 +88,10 @@ var DEFAULT_FILTER_RULES = [
75
88
  replacement: "$1=[REDACTED]",
76
89
  priority: 90
77
90
  },
91
+ // =====================================
92
+ // IDENTITY (High Risk)
93
+ // =====================================
94
+ // Email Addresses
78
95
  {
79
96
  name: "email",
80
97
  category: "identity",
@@ -82,6 +99,10 @@ var DEFAULT_FILTER_RULES = [
82
99
  replacement: "[EMAIL_REDACTED]",
83
100
  priority: 80
84
101
  },
102
+ // =====================================
103
+ // INFRASTRUCTURE (Medium Risk)
104
+ // =====================================
105
+ // Database Connection Strings
85
106
  {
86
107
  name: "db_connection",
87
108
  category: "infrastructure",
@@ -89,6 +110,7 @@ var DEFAULT_FILTER_RULES = [
89
110
  replacement: "$1://[CONNECTION_REDACTED]",
90
111
  priority: 85
91
112
  },
113
+ // Internal URLs
92
114
  {
93
115
  name: "internal_url",
94
116
  category: "infrastructure",
@@ -96,6 +118,7 @@ var DEFAULT_FILTER_RULES = [
96
118
  replacement: "[INTERNAL_URL_REDACTED]",
97
119
  priority: 75
98
120
  },
121
+ // IP Addresses (except localhost and common dev IPs)
99
122
  {
100
123
  name: "ipv4",
101
124
  category: "infrastructure",
@@ -108,6 +131,10 @@ var DEFAULT_FILTER_RULES = [
108
131
  },
109
132
  priority: 70
110
133
  },
134
+ // =====================================
135
+ // FILE PATHS (Context-dependent)
136
+ // =====================================
137
+ // Home Directory Paths (macOS)
111
138
  {
112
139
  name: "macos_home_path",
113
140
  category: "path",
@@ -115,6 +142,7 @@ var DEFAULT_FILTER_RULES = [
115
142
  replacement: "~",
116
143
  priority: 60
117
144
  },
145
+ // Home Directory Paths (Linux)
118
146
  {
119
147
  name: "linux_home_path",
120
148
  category: "path",
@@ -122,6 +150,7 @@ var DEFAULT_FILTER_RULES = [
122
150
  replacement: "~",
123
151
  priority: 60
124
152
  },
153
+ // Home Directory Paths (Windows)
125
154
  {
126
155
  name: "windows_home_path",
127
156
  category: "path",
@@ -129,6 +158,10 @@ var DEFAULT_FILTER_RULES = [
129
158
  replacement: "~",
130
159
  priority: 60
131
160
  },
161
+ // =====================================
162
+ // ENVIRONMENT (Medium Risk)
163
+ // =====================================
164
+ // Sensitive Environment Variables
132
165
  {
133
166
  name: "env_var_value",
134
167
  category: "environment",
@@ -157,7 +190,9 @@ var DEFAULT_FILTER_RULES = [
157
190
  }
158
191
  ];
159
192
  function createPrivacyFilter(customRules) {
160
- const rules = [...DEFAULT_FILTER_RULES, ...customRules || []].sort((a, b) => b.priority - a.priority);
193
+ const rules = [...DEFAULT_FILTER_RULES, ...customRules || []].sort(
194
+ (a, b) => b.priority - a.priority
195
+ );
161
196
  function generalizePaths(content, context) {
162
197
  let result = content;
163
198
  if (context.projectRoot) {
@@ -173,6 +208,9 @@ function createPrivacyFilter(customRules) {
173
208
  return result;
174
209
  }
175
210
  return {
211
+ /**
212
+ * Sanitize content by applying all filter rules
213
+ */
176
214
  sanitize(content, context) {
177
215
  let result = content;
178
216
  const appliedFilters = [];
@@ -202,10 +240,16 @@ function createPrivacyFilter(customRules) {
202
240
  appliedFilters: [...new Set(appliedFilters)]
203
241
  };
204
242
  },
243
+ /**
244
+ * Add a custom filter rule
245
+ */
205
246
  addRule(rule) {
206
247
  rules.push(rule);
207
248
  rules.sort((a, b) => b.priority - a.priority);
208
249
  },
250
+ /**
251
+ * Remove a filter rule by name
252
+ */
209
253
  removeRule(name) {
210
254
  const index = rules.findIndex((r) => r.name === name);
211
255
  if (index !== -1) {
@@ -214,9 +258,16 @@ function createPrivacyFilter(customRules) {
214
258
  }
215
259
  return false;
216
260
  },
261
+ /**
262
+ * Get all current rules
263
+ */
217
264
  getRules() {
218
265
  return rules;
219
266
  },
267
+ /**
268
+ * Check if content contains sensitive data
269
+ * Note: Always reset regex lastIndex BEFORE testing to prevent state pollution
270
+ */
220
271
  containsSensitiveData(content) {
221
272
  for (const rule of rules) {
222
273
  if (rule.category === "secret") {
@@ -240,7 +291,7 @@ function createFilterContext(projectDirectory) {
240
291
  return {
241
292
  projectRoot: projectDirectory,
242
293
  homeDir,
243
- commonPaths: new Map([
294
+ commonPaths: /* @__PURE__ */ new Map([
244
295
  ["/usr/local/lib/", "<LIB>/"],
245
296
  ["/usr/lib/", "<LIB>/"],
246
297
  ["/var/log/", "<LOG>/"],
@@ -253,6 +304,7 @@ var defaultPrivacyFilter = createPrivacyFilter();
253
304
 
254
305
  // src/core/error-detector.ts
255
306
  var ERROR_PATTERNS = {
307
+ // Universal error indicators
256
308
  universal: [
257
309
  /\b(error|failed|failure|fatal|exception|panic)\b/i,
258
310
  /\b(cannot|could not|unable to|couldn't)\b/i,
@@ -263,26 +315,36 @@ var ERROR_PATTERNS = {
263
315
  /\b(segmentation fault|segfault|core dumped)\b/i,
264
316
  /\b(out of memory|oom|memory allocation failed)\b/i
265
317
  ],
318
+ // Error prefixes
266
319
  prefixed: [
267
320
  /^Error:/m,
268
321
  /^ERROR\s/m,
269
322
  /^E\s+\d+:/m,
323
+ // Rust errors
270
324
  /^\[ERROR\]/m,
271
325
  /^fatal:/m,
272
326
  /^FATAL:/m,
273
327
  /^panic:/m,
274
328
  /^Traceback \(most recent call last\):/m,
329
+ // Python
275
330
  /^Exception in thread/m,
331
+ // Java
276
332
  /^Uncaught \w+Error:/m
333
+ // JavaScript
277
334
  ],
335
+ // Build/compilation errors
278
336
  build: [
279
337
  /^.+:\d+:\d+:\s*error:/m,
338
+ // GCC/Clang format
280
339
  /error\[E\d+\]:/m,
340
+ // Rust compiler
281
341
  /error TS\d+:/m,
342
+ // TypeScript
282
343
  /SyntaxError:/m,
283
344
  /ParseError:/m,
284
345
  /CompileError:/m
285
346
  ],
347
+ // Package manager errors
286
348
  package: [
287
349
  /npm ERR!/m,
288
350
  /npm error/m,
@@ -295,7 +357,9 @@ var ERROR_PATTERNS = {
295
357
  /Cannot find module/m,
296
358
  /Module not found/m
297
359
  ],
360
+ // Permission errors
298
361
  permission: [/EACCES:/m, /EPERM:/m, /Permission denied/m, /Access denied/m, /Insufficient permissions/m],
362
+ // Network errors
299
363
  network: [
300
364
  /ECONNREFUSED/m,
301
365
  /ETIMEDOUT/m,
@@ -304,6 +368,7 @@ var ERROR_PATTERNS = {
304
368
  /Connection refused/m,
305
369
  /Network is unreachable/m
306
370
  ],
371
+ // Test failures
307
372
  test: [/FAIL /m, /AssertionError/m, /Expected .+ but got/m, /Test failed/i, /\d+ failing/m]
308
373
  };
309
374
  var STACK_TRACE_PATTERNS = {
@@ -318,14 +383,23 @@ var STACK_TRACE_PATTERNS = {
318
383
  };
319
384
  var EXIT_CODE_SEVERITY = {
320
385
  1: "error",
386
+ // General errors
321
387
  2: "error",
388
+ // Misuse of shell builtins
322
389
  126: "error",
390
+ // Command cannot execute
323
391
  127: "error",
392
+ // Command not found
324
393
  128: "critical",
394
+ // Invalid exit argument
325
395
  130: "warning",
396
+ // Script terminated by Ctrl+C
326
397
  137: "critical",
398
+ // SIGKILL (OOM, etc.)
327
399
  139: "critical",
400
+ // Segmentation fault
328
401
  143: "warning"
402
+ // SIGTERM
329
403
  };
330
404
  function createErrorDetector(privacyFilter) {
331
405
  const filter = privacyFilter || createPrivacyFilter();
@@ -343,8 +417,7 @@ function createErrorDetector(privacyFilter) {
343
417
  test: 0.7
344
418
  };
345
419
  for (const [category, patterns] of Object.entries(ERROR_PATTERNS)) {
346
- if (category === "universal")
347
- continue;
420
+ if (category === "universal") continue;
348
421
  for (const pattern of patterns) {
349
422
  const match = content.match(pattern);
350
423
  if (match) {
@@ -379,44 +452,32 @@ function createErrorDetector(privacyFilter) {
379
452
  };
380
453
  }
381
454
  function calculateConfidence(signals) {
382
- if (signals.length === 0)
383
- return 0;
455
+ if (signals.length === 0) return 0;
384
456
  const totalWeight = signals.reduce((sum, s) => sum + s.weight, 0);
385
457
  const avgWeight = totalWeight / signals.length;
386
458
  const multiplier = Math.min(1.2, 1 + signals.length * 0.05);
387
459
  return Math.min(1, avgWeight * multiplier);
388
460
  }
389
461
  function classifyErrorType(signals, content) {
390
- if (ERROR_PATTERNS.build.some((p) => p.test(content)))
391
- return "build";
392
- if (ERROR_PATTERNS.package.some((p) => p.test(content)))
393
- return "dependency";
394
- if (ERROR_PATTERNS.permission.some((p) => p.test(content)))
395
- return "permission";
396
- if (ERROR_PATTERNS.network.some((p) => p.test(content)))
397
- return "network";
398
- if (ERROR_PATTERNS.test.some((p) => p.test(content)))
399
- return "test";
400
- if (/TypeError:|type error|Type '[^']+' is not assignable/i.test(content))
401
- return "type_error";
402
- if (/SyntaxError:|syntax error|unexpected token/i.test(content))
403
- return "syntax";
404
- if (/ReferenceError:|RangeError:|runtime error/i.test(content))
405
- return "runtime";
462
+ if (ERROR_PATTERNS.build.some((p) => p.test(content))) return "build";
463
+ if (ERROR_PATTERNS.package.some((p) => p.test(content))) return "dependency";
464
+ if (ERROR_PATTERNS.permission.some((p) => p.test(content))) return "permission";
465
+ if (ERROR_PATTERNS.network.some((p) => p.test(content))) return "network";
466
+ if (ERROR_PATTERNS.test.some((p) => p.test(content))) return "test";
467
+ if (/TypeError:|type error|Type '[^']+' is not assignable/i.test(content)) return "type_error";
468
+ if (/SyntaxError:|syntax error|unexpected token/i.test(content)) return "syntax";
469
+ if (/ReferenceError:|RangeError:|runtime error/i.test(content)) return "runtime";
406
470
  const hasStackTrace = signals.some((s) => s.type === "stack_trace");
407
- if (hasStackTrace)
408
- return "runtime";
471
+ if (hasStackTrace) return "runtime";
409
472
  return "unknown";
410
473
  }
411
474
  function determineSeverity(signals, exitCode) {
412
- if (exitCode !== undefined && EXIT_CODE_SEVERITY[exitCode]) {
475
+ if (exitCode !== void 0 && EXIT_CODE_SEVERITY[exitCode]) {
413
476
  return EXIT_CODE_SEVERITY[exitCode];
414
477
  }
415
478
  const maxWeight = Math.max(...signals.map((s) => s.weight));
416
- if (maxWeight >= 0.9)
417
- return "error";
418
- if (maxWeight >= 0.7)
419
- return "error";
479
+ if (maxWeight >= 0.9) return "error";
480
+ if (maxWeight >= 0.7) return "error";
420
481
  return "warning";
421
482
  }
422
483
  function isErrorLine(line) {
@@ -424,8 +485,7 @@ function createErrorDetector(privacyFilter) {
424
485
  return /^(Error|TypeError|ReferenceError|SyntaxError|RangeError):/i.test(trimmed) || /^(error|FAIL|fatal|panic)\b/i.test(trimmed) || /^error\[E\d+\]:/.test(trimmed) || /^error TS\d+:/.test(trimmed);
425
486
  }
426
487
  function extractErrorDetails(output) {
427
- const lines = output.split(`
428
- `);
488
+ const lines = output.split("\n");
429
489
  let message = "";
430
490
  let stack = "";
431
491
  let inStack = false;
@@ -433,9 +493,11 @@ function createErrorDetector(privacyFilter) {
433
493
  if (isErrorLine(line) && !message) {
434
494
  message = line.trim();
435
495
  inStack = true;
436
- } else if (inStack && (line.match(/^\s+at\s/) || line.match(/^\s+File\s/) || line.match(/^\s+\d+:\s/) || line.match(/^\s+from\s/))) {
437
- stack += line + `
438
- `;
496
+ } else if (inStack && (line.match(/^\s+at\s/) || // JS stack
497
+ line.match(/^\s+File\s/) || // Python stack
498
+ line.match(/^\s+\d+:\s/) || // Rust stack
499
+ line.match(/^\s+from\s/))) {
500
+ stack += line + "\n";
439
501
  }
440
502
  }
441
503
  if (!message) {
@@ -448,15 +510,18 @@ function createErrorDetector(privacyFilter) {
448
510
  }
449
511
  return {
450
512
  message: message || output.substring(0, 500),
451
- stack: stack || undefined
513
+ stack: stack || void 0
452
514
  };
453
515
  }
454
516
  return {
517
+ /**
518
+ * Detect if output contains an error
519
+ */
455
520
  detect(toolOutput) {
456
521
  const signals = [];
457
522
  const combinedOutput = `${toolOutput.output || ""}
458
523
  ${toolOutput.stderr || ""}`;
459
- if (toolOutput.exitCode !== undefined && toolOutput.exitCode !== 0) {
524
+ if (toolOutput.exitCode !== void 0 && toolOutput.exitCode !== 0) {
460
525
  const severity2 = EXIT_CODE_SEVERITY[toolOutput.exitCode] || "error";
461
526
  signals.push({
462
527
  type: "exit_code",
@@ -482,8 +547,7 @@ ${toolOutput.stderr || ""}`;
482
547
  signals.push({
483
548
  type: "stack_trace",
484
549
  weight: 0.95,
485
- value: stackTrace.frames.slice(0, 5).join(`
486
- `),
550
+ value: stackTrace.frames.slice(0, 5).join("\n"),
487
551
  description: `${stackTrace.language} stack trace detected`
488
552
  });
489
553
  }
@@ -493,8 +557,8 @@ ${toolOutput.stderr || ""}`;
493
557
  const severity = determineSeverity(signals, toolOutput.exitCode);
494
558
  const { message, stack } = extractErrorDetails(combinedOutput);
495
559
  const sanitizedMessage = filter.sanitize(message);
496
- const sanitizedStack = stack ? filter.sanitize(stack) : undefined;
497
- const sanitizedOutput = filter.sanitize(combinedOutput.substring(0, 5000));
560
+ const sanitizedStack = stack ? filter.sanitize(stack) : void 0;
561
+ const sanitizedOutput = filter.sanitize(combinedOutput.substring(0, 5e3));
498
562
  return {
499
563
  detected,
500
564
  confidence,
@@ -555,9 +619,8 @@ function calculateStringSimilarity(str1, str2) {
555
619
  const words1 = new Set(str1.toLowerCase().split(/\s+/));
556
620
  const words2 = new Set(str2.toLowerCase().split(/\s+/));
557
621
  const intersection = new Set([...words1].filter((x) => words2.has(x)));
558
- const union = new Set([...words1, ...words2]);
559
- if (union.size === 0)
560
- return 0;
622
+ const union = /* @__PURE__ */ new Set([...words1, ...words2]);
623
+ if (union.size === 0) return 0;
561
624
  return intersection.size / union.size;
562
625
  }
563
626
 
@@ -570,7 +633,9 @@ function runMigrations(db) {
570
633
  applied_at TEXT DEFAULT CURRENT_TIMESTAMP
571
634
  )
572
635
  `);
573
- const appliedMigrations = new Set(db.prepare("SELECT name FROM migrations").all().map((r) => r.name));
636
+ const appliedMigrations = new Set(
637
+ db.prepare("SELECT name FROM migrations").all().map((r) => r.name)
638
+ );
574
639
  for (const migration of MIGRATIONS) {
575
640
  if (!appliedMigrations.has(migration.name)) {
576
641
  db.exec(migration.sql);
@@ -664,19 +729,19 @@ function rowToRecord(row) {
664
729
  errorHash: row.error_hash,
665
730
  errorType: row.error_type,
666
731
  errorMessage: row.error_message,
667
- errorStack: row.error_stack || undefined,
668
- language: row.language || undefined,
669
- framework: row.framework || undefined,
732
+ errorStack: row.error_stack || void 0,
733
+ language: row.language || void 0,
734
+ framework: row.framework || void 0,
670
735
  toolName: row.tool_name,
671
736
  toolInput: JSON.parse(row.tool_input || "{}"),
672
737
  sessionId: row.session_id,
673
738
  status: row.status,
674
- resolution: row.resolution || undefined,
675
- resolutionCode: row.resolution_code || undefined,
739
+ resolution: row.resolution || void 0,
740
+ resolutionCode: row.resolution_code || void 0,
676
741
  createdAt: row.created_at,
677
- resolvedAt: row.resolved_at || undefined,
678
- uploadedAt: row.uploaded_at || undefined,
679
- cloudKnowledgeId: row.cloud_knowledge_id || undefined
742
+ resolvedAt: row.resolved_at || void 0,
743
+ uploadedAt: row.uploaded_at || void 0,
744
+ cloudKnowledgeId: row.cloud_knowledge_id || void 0
680
745
  };
681
746
  }
682
747
  function createLocalStore(projectDirectory) {
@@ -697,6 +762,10 @@ function createLocalStore(projectDirectory) {
697
762
  stmt.run();
698
763
  }
699
764
  return {
765
+ // ============ Error Records ============
766
+ /**
767
+ * Create a new error record
768
+ */
700
769
  createErrorRecord(data) {
701
770
  const id = uuidv4();
702
771
  const errorHash = generateErrorFingerprint(data.errorMessage, data.errorStack);
@@ -724,11 +793,17 @@ function createLocalStore(projectDirectory) {
724
793
  incrementStat("total_errors");
725
794
  return this.getErrorById(id);
726
795
  },
796
+ /**
797
+ * Get error record by ID
798
+ */
727
799
  getErrorById(id) {
728
800
  const stmt = db.prepare("SELECT * FROM error_records WHERE id = ?");
729
801
  const row = stmt.get(id);
730
802
  return row ? rowToRecord(row) : null;
731
803
  },
804
+ /**
805
+ * Get errors by session
806
+ */
732
807
  getSessionErrors(sessionId, options) {
733
808
  let query = "SELECT * FROM error_records WHERE session_id = ?";
734
809
  const params = [sessionId];
@@ -744,13 +819,24 @@ function createLocalStore(projectDirectory) {
744
819
  const stmt = db.prepare(query);
745
820
  return stmt.all(...params).map((row) => rowToRecord(row));
746
821
  },
822
+ /**
823
+ * Get unresolved errors for a session
824
+ */
747
825
  getUnresolvedErrors(sessionId) {
748
826
  return this.getSessionErrors(sessionId, { status: "unresolved" });
749
827
  },
828
+ /**
829
+ * Get recent errors across all sessions
830
+ */
750
831
  getRecentErrors(limit = 10) {
751
- const stmt = db.prepare("SELECT * FROM error_records ORDER BY created_at DESC LIMIT ?");
832
+ const stmt = db.prepare(
833
+ "SELECT * FROM error_records ORDER BY created_at DESC LIMIT ?"
834
+ );
752
835
  return stmt.all(limit).map((row) => rowToRecord(row));
753
836
  },
837
+ /**
838
+ * Mark error as resolved
839
+ */
754
840
  markResolved(id, data) {
755
841
  const stmt = db.prepare(`
756
842
  UPDATE error_records
@@ -767,6 +853,9 @@ function createLocalStore(projectDirectory) {
767
853
  }
768
854
  return null;
769
855
  },
856
+ /**
857
+ * Mark error as uploaded to cloud
858
+ */
770
859
  markUploaded(id, cloudKnowledgeId) {
771
860
  const stmt = db.prepare(`
772
861
  UPDATE error_records
@@ -780,10 +869,19 @@ function createLocalStore(projectDirectory) {
780
869
  incrementStat("uploaded_errors");
781
870
  }
782
871
  },
872
+ /**
873
+ * Find similar errors by hash
874
+ */
783
875
  findSimilarErrors(errorHash) {
784
- const stmt = db.prepare("SELECT * FROM error_records WHERE error_hash = ? ORDER BY created_at DESC");
876
+ const stmt = db.prepare(
877
+ "SELECT * FROM error_records WHERE error_hash = ? ORDER BY created_at DESC"
878
+ );
785
879
  return stmt.all(errorHash).map((row) => rowToRecord(row));
786
880
  },
881
+ // ============ Query Cache ============
882
+ /**
883
+ * Get cached query results
884
+ */
787
885
  getCachedResults(errorHash) {
788
886
  const stmt = db.prepare(`
789
887
  SELECT results FROM query_cache
@@ -796,7 +894,10 @@ function createLocalStore(projectDirectory) {
796
894
  }
797
895
  return null;
798
896
  },
799
- cacheResults(errorHash, results, expirationMs = 3600000) {
897
+ /**
898
+ * Cache query results
899
+ */
900
+ cacheResults(errorHash, results, expirationMs = 36e5) {
800
901
  const id = uuidv4();
801
902
  const expiresAt = new Date(Date.now() + expirationMs).toISOString();
802
903
  const stmt = db.prepare(`
@@ -806,13 +907,22 @@ function createLocalStore(projectDirectory) {
806
907
  stmt.run(id, errorHash, JSON.stringify(results), expiresAt);
807
908
  incrementStat("queries_made");
808
909
  },
910
+ /**
911
+ * Clear expired cache entries
912
+ */
809
913
  clearExpiredCache() {
810
914
  const stmt = db.prepare("DELETE FROM query_cache WHERE expires_at <= datetime('now')");
811
915
  const result = stmt.run();
812
916
  return result.changes;
813
917
  },
918
+ // ============ Statistics ============
919
+ /**
920
+ * Get usage statistics
921
+ */
814
922
  getStats() {
815
- const stmt = db.prepare("SELECT total_errors, resolved_errors, uploaded_errors FROM usage_stats WHERE id = 1");
923
+ const stmt = db.prepare(
924
+ "SELECT total_errors, resolved_errors, uploaded_errors FROM usage_stats WHERE id = 1"
925
+ );
816
926
  const row = stmt.get();
817
927
  return {
818
928
  totalErrors: row.total_errors,
@@ -820,20 +930,34 @@ function createLocalStore(projectDirectory) {
820
930
  uploadedErrors: row.uploaded_errors
821
931
  };
822
932
  },
933
+ // ============ Preferences ============
934
+ /**
935
+ * Get preference value
936
+ */
823
937
  getPreference(key) {
824
938
  const stmt = db.prepare("SELECT value FROM user_preferences WHERE key = ?");
825
939
  const row = stmt.get(key);
826
940
  return row?.value || null;
827
941
  },
942
+ /**
943
+ * Set preference value
944
+ */
828
945
  setPreference(key, value) {
829
946
  const stmt = db.prepare(`
830
947
  INSERT OR REPLACE INTO user_preferences (key, value) VALUES (?, ?)
831
948
  `);
832
949
  stmt.run(key, value);
833
950
  },
951
+ // ============ Utilities ============
952
+ /**
953
+ * Close database connection
954
+ */
834
955
  close() {
835
956
  db.close();
836
957
  },
958
+ /**
959
+ * Get database for advanced queries
960
+ */
837
961
  getDatabase() {
838
962
  return db;
839
963
  }
@@ -844,13 +968,13 @@ var LocalStore = {
844
968
  };
845
969
 
846
970
  // src/cloud/client.ts
847
- import { createClient } from "@supabase/supabase-js";
971
+ import * as supabaseJs from "@supabase/supabase-js";
848
972
 
849
973
  // src/cloud/embedding.ts
850
- import { OpenAI } from "openai";
974
+ import * as openaiModule from "openai";
851
975
  var DEFAULT_MODEL = "text-embedding-3-small";
852
976
  var DEFAULT_DIMENSIONS = 1536;
853
- var MAX_INPUT_LENGTH = 30000;
977
+ var MAX_INPUT_LENGTH = 3e4;
854
978
  function cosineSimilarity(a, b) {
855
979
  if (a.length !== b.length) {
856
980
  throw new Error("Embeddings must have same dimensions");
@@ -858,18 +982,18 @@ function cosineSimilarity(a, b) {
858
982
  let dotProduct = 0;
859
983
  let normA = 0;
860
984
  let normB = 0;
861
- for (let i = 0;i < a.length; i++) {
985
+ for (let i = 0; i < a.length; i++) {
862
986
  dotProduct += a[i] * b[i];
863
987
  normA += a[i] * a[i];
864
988
  normB += b[i] * b[i];
865
989
  }
866
990
  const magnitude = Math.sqrt(normA) * Math.sqrt(normB);
867
- if (magnitude === 0)
868
- return 0;
991
+ if (magnitude === 0) return 0;
869
992
  return dotProduct / magnitude;
870
993
  }
871
994
  function createEmbeddingService(config) {
872
- const client = new OpenAI({ apiKey: config.apiKey });
995
+ const OpenAI2 = openaiModule.OpenAI || openaiModule.default;
996
+ const client = new OpenAI2({ apiKey: config.apiKey });
873
997
  const model = config.model || DEFAULT_MODEL;
874
998
  const dimensions = config.dimensions || DEFAULT_DIMENSIONS;
875
999
  function truncateText(text) {
@@ -877,14 +1001,16 @@ function createEmbeddingService(config) {
877
1001
  return text;
878
1002
  }
879
1003
  const truncated = text.substring(0, MAX_INPUT_LENGTH);
880
- const lastNewline = truncated.lastIndexOf(`
881
- `);
1004
+ const lastNewline = truncated.lastIndexOf("\n");
882
1005
  if (lastNewline > MAX_INPUT_LENGTH * 0.8) {
883
1006
  return truncated.substring(0, lastNewline);
884
1007
  }
885
1008
  return truncated;
886
1009
  }
887
1010
  return {
1011
+ /**
1012
+ * Generate embedding for a single text
1013
+ */
888
1014
  async generate(text) {
889
1015
  const truncated = truncateText(text);
890
1016
  const response = await client.embeddings.create({
@@ -894,6 +1020,9 @@ function createEmbeddingService(config) {
894
1020
  });
895
1021
  return response.data[0].embedding;
896
1022
  },
1023
+ /**
1024
+ * Generate embeddings for multiple texts
1025
+ */
897
1026
  async generateBatch(texts) {
898
1027
  const truncated = texts.map((t) => truncateText(t));
899
1028
  const response = await client.embeddings.create({
@@ -903,6 +1032,10 @@ function createEmbeddingService(config) {
903
1032
  });
904
1033
  return response.data.map((d) => d.embedding);
905
1034
  },
1035
+ /**
1036
+ * Generate embedding for error context
1037
+ * Combines error message, stack trace, and context
1038
+ */
906
1039
  async generateErrorEmbedding(errorMessage, errorStack, context) {
907
1040
  const parts = [];
908
1041
  if (context?.language) {
@@ -916,13 +1049,18 @@ function createEmbeddingService(config) {
916
1049
  parts.push(`Stack Trace:
917
1050
  ${errorStack}`);
918
1051
  }
919
- const text = parts.join(`
920
- `);
1052
+ const text = parts.join("\n");
921
1053
  return this.generate(text);
922
1054
  },
1055
+ /**
1056
+ * Get embedding dimensions
1057
+ */
923
1058
  getDimensions() {
924
1059
  return dimensions;
925
1060
  },
1061
+ /**
1062
+ * Get model name
1063
+ */
926
1064
  getModel() {
927
1065
  return model;
928
1066
  }
@@ -940,13 +1078,13 @@ function mapToKnowledgeEntry(row) {
940
1078
  errorHash: row.error_hash,
941
1079
  errorType: row.error_type,
942
1080
  errorMessage: row.error_message,
943
- errorStack: row.error_stack || undefined,
1081
+ errorStack: row.error_stack || void 0,
944
1082
  language: row.language,
945
- framework: row.framework || undefined,
946
- dependencies: row.dependencies || undefined,
1083
+ framework: row.framework || void 0,
1084
+ dependencies: row.dependencies || void 0,
947
1085
  resolutionDescription: row.resolution_description,
948
- resolutionCode: row.resolution_code || undefined,
949
- resolutionSteps: row.resolution_steps || undefined,
1086
+ resolutionCode: row.resolution_code || void 0,
1087
+ resolutionSteps: row.resolution_steps || void 0,
950
1088
  contributorId: row.contributor_id,
951
1089
  upvotes: row.upvotes || 0,
952
1090
  downvotes: row.downvotes || 0,
@@ -954,11 +1092,11 @@ function mapToKnowledgeEntry(row) {
954
1092
  createdAt: row.created_at,
955
1093
  updatedAt: row.updated_at,
956
1094
  isVerified: row.is_verified || false,
957
- similarity: row.similarity || undefined
1095
+ similarity: row.similarity || void 0
958
1096
  };
959
1097
  }
960
1098
  async function createCloudClient(config) {
961
- const supabase = createClient(config.supabaseUrl, config.supabaseAnonKey);
1099
+ const supabase = supabaseJs.createClient(config.supabaseUrl, config.supabaseAnonKey);
962
1100
  let embedding = null;
963
1101
  if (config.openaiApiKey) {
964
1102
  try {
@@ -1166,6 +1304,9 @@ var CloudClient = {
1166
1304
  import { tool } from "@opencode-ai/plugin";
1167
1305
  function createTools(localStore, cloudClient, privacyFilter, context) {
1168
1306
  return {
1307
+ /**
1308
+ * Search cloud knowledge base for error solutions
1309
+ */
1169
1310
  fixhive_search: tool({
1170
1311
  description: "Search FixHive knowledge base for error solutions. Use when encountering errors to find community solutions.",
1171
1312
  args: {
@@ -1194,6 +1335,9 @@ function createTools(localStore, cloudClient, privacyFilter, context) {
1194
1335
  return formatSearchResults(results.results, false);
1195
1336
  }
1196
1337
  }),
1338
+ /**
1339
+ * Mark error as resolved and optionally upload solution
1340
+ */
1197
1341
  fixhive_resolve: tool({
1198
1342
  description: "Mark an error as resolved and optionally share the solution with the community.",
1199
1343
  args: {
@@ -1229,6 +1373,9 @@ function createTools(localStore, cloudClient, privacyFilter, context) {
1229
1373
  return "Error marked as resolved locally.";
1230
1374
  }
1231
1375
  }),
1376
+ /**
1377
+ * List errors in current session
1378
+ */
1232
1379
  fixhive_list: tool({
1233
1380
  description: "List errors detected in the current session.",
1234
1381
  args: {
@@ -1247,6 +1394,9 @@ function createTools(localStore, cloudClient, privacyFilter, context) {
1247
1394
  return formatErrorList(errors);
1248
1395
  }
1249
1396
  }),
1397
+ /**
1398
+ * Vote on a solution
1399
+ */
1250
1400
  fixhive_vote: tool({
1251
1401
  description: "Upvote or downvote a FixHive solution based on whether it helped.",
1252
1402
  args: {
@@ -1264,6 +1414,9 @@ function createTools(localStore, cloudClient, privacyFilter, context) {
1264
1414
  return args.helpful ? "Thanks for the feedback! Solution upvoted." : "Thanks for the feedback! Solution downvoted.";
1265
1415
  }
1266
1416
  }),
1417
+ /**
1418
+ * Report inappropriate content
1419
+ */
1267
1420
  fixhive_report: tool({
1268
1421
  description: "Report a FixHive solution for inappropriate content, spam, or incorrect information.",
1269
1422
  args: {
@@ -1278,6 +1431,9 @@ function createTools(localStore, cloudClient, privacyFilter, context) {
1278
1431
  return "Report submitted. Thank you for helping keep FixHive clean!";
1279
1432
  }
1280
1433
  }),
1434
+ /**
1435
+ * Get usage statistics
1436
+ */
1281
1437
  fixhive_stats: tool({
1282
1438
  description: "Get FixHive usage statistics.",
1283
1439
  args: {},
@@ -1299,6 +1455,9 @@ function createTools(localStore, cloudClient, privacyFilter, context) {
1299
1455
  `;
1300
1456
  }
1301
1457
  }),
1458
+ /**
1459
+ * Report that a solution was helpful
1460
+ */
1302
1461
  fixhive_helpful: tool({
1303
1462
  description: "Report that a FixHive solution was helpful and resolved your issue.",
1304
1463
  args: {
@@ -1333,8 +1492,7 @@ ${r.resolutionCode}
1333
1492
  if (r.resolutionSteps?.length) {
1334
1493
  entry += `
1335
1494
  **Steps:**
1336
- ${r.resolutionSteps.map((s, j) => `${j + 1}. ${s}`).join(`
1337
- `)}
1495
+ ${r.resolutionSteps.map((s, j) => `${j + 1}. ${s}`).join("\n")}
1338
1496
  `;
1339
1497
  }
1340
1498
  entry += `
@@ -1342,8 +1500,7 @@ ${r.resolutionSteps.map((s, j) => `${j + 1}. ${s}`).join(`
1342
1500
 
1343
1501
  ---`;
1344
1502
  return entry;
1345
- }).join(`
1346
- `);
1503
+ }).join("\n");
1347
1504
  return `${header}
1348
1505
  ${entries}
1349
1506
 
@@ -1354,8 +1511,9 @@ function formatErrorList(errors) {
1354
1511
  const table = `
1355
1512
  | ID | Type | Status | Message |
1356
1513
  |----|------|--------|---------|
1357
- ${errors.map((e) => `| ${e.id.slice(0, 8)} | ${e.errorType} | ${e.status} | ${e.errorMessage.slice(0, 50)}... |`).join(`
1358
- `)}
1514
+ ${errors.map(
1515
+ (e) => `| ${e.id.slice(0, 8)} | ${e.errorType} | ${e.status} | ${e.errorMessage.slice(0, 50)}... |`
1516
+ ).join("\n")}
1359
1517
  `;
1360
1518
  return `${header}
1361
1519
  ${table}
@@ -1365,7 +1523,8 @@ Use \`fixhive_resolve <id>\` to mark as resolved and share solutions.`;
1365
1523
 
1366
1524
  // src/plugin/index.ts
1367
1525
  var DEFAULT_CONFIG = {
1368
- cacheExpirationMs: 3600000,
1526
+ cacheExpirationMs: 36e5,
1527
+ // 1 hour
1369
1528
  embeddingModel: "text-embedding-3-small",
1370
1529
  embeddingDimensions: 1536,
1371
1530
  similarityThreshold: 0.7,
@@ -1407,9 +1566,9 @@ var FixHivePlugin = async (ctx) => {
1407
1566
  console.log("[FixHive] Ready - use fixhive_stats to verify");
1408
1567
  const errorProducingTools = ["bash", "edit", "write", "read", "terminal"];
1409
1568
  return {
1569
+ // ============ Tool Execution Hook ============
1410
1570
  "tool.execute.after": async (input, output) => {
1411
- if (!errorProducingTools.includes(input.tool))
1412
- return;
1571
+ if (!errorProducingTools.includes(input.tool)) return;
1413
1572
  const detection = errorDetector.detect({
1414
1573
  tool: input.tool,
1415
1574
  output: output.output,
@@ -1419,7 +1578,7 @@ var FixHivePlugin = async (ctx) => {
1419
1578
  });
1420
1579
  if (detection.detected && detection.confidence >= 0.5) {
1421
1580
  const sanitizedErrorMessage = privacyFilter.sanitize(detection.errorMessage, filterContext).sanitized;
1422
- const sanitizedErrorStack = detection.errorStack ? privacyFilter.sanitize(detection.errorStack, filterContext).sanitized : undefined;
1581
+ const sanitizedErrorStack = detection.errorStack ? privacyFilter.sanitize(detection.errorStack, filterContext).sanitized : void 0;
1423
1582
  localStore.createErrorRecord({
1424
1583
  errorType: detection.errorType,
1425
1584
  errorMessage: sanitizedErrorMessage,
@@ -1428,6 +1587,7 @@ var FixHivePlugin = async (ctx) => {
1428
1587
  framework: pluginContext.framework,
1429
1588
  toolName: input.tool,
1430
1589
  toolInput: {},
1590
+ // Tool input is intentionally omitted to avoid storing sensitive data
1431
1591
  sessionId: pluginContext.sessionId || input.sessionID
1432
1592
  });
1433
1593
  if (cloudClient) {
@@ -1440,7 +1600,10 @@ var FixHivePlugin = async (ctx) => {
1440
1600
  limit: 3
1441
1601
  });
1442
1602
  if (solutions.results.length > 0) {
1443
- localStore.cacheResults(generateErrorFingerprint(sanitizedErrorMessage, sanitizedErrorStack), solutions.results);
1603
+ localStore.cacheResults(
1604
+ generateErrorFingerprint(sanitizedErrorMessage, sanitizedErrorStack),
1605
+ solutions.results
1606
+ );
1444
1607
  output.title = `${output.title} [FixHive: ${solutions.results.length} solution(s) found]`;
1445
1608
  }
1446
1609
  } catch (e) {
@@ -1450,22 +1613,24 @@ var FixHivePlugin = async (ctx) => {
1450
1613
  }
1451
1614
  }
1452
1615
  },
1616
+ // ============ Session Compaction Hook ============
1453
1617
  "experimental.session.compacting": async (_input, output) => {
1454
1618
  const unresolvedErrors = localStore.getUnresolvedErrors(pluginContext.sessionId);
1455
1619
  if (unresolvedErrors.length > 0) {
1456
1620
  output.context.push(`
1457
1621
  ## FixHive: Unresolved Errors in Session
1458
1622
 
1459
- ${unresolvedErrors.map((e) => `- [${e.id.slice(0, 8)}] ${e.errorType}: ${e.errorMessage.slice(0, 100)}...`).join(`
1460
- `)}
1623
+ ${unresolvedErrors.map((e) => `- [${e.id.slice(0, 8)}] ${e.errorType}: ${e.errorMessage.slice(0, 100)}...`).join("\n")}
1461
1624
 
1462
1625
  Use \`fixhive_mark_resolved\` when errors are fixed to contribute solutions.
1463
1626
  `);
1464
1627
  }
1465
1628
  },
1629
+ // ============ Chat Message Hook ============
1466
1630
  "chat.message": async (input, _output) => {
1467
1631
  pluginContext.sessionId = input.sessionID;
1468
1632
  },
1633
+ // ============ Custom Tools ============
1469
1634
  tool: cloudClient ? createTools(localStore, cloudClient, privacyFilter, pluginContext) : createOfflineTools(localStore, privacyFilter, pluginContext)
1470
1635
  };
1471
1636
  };
@@ -1488,8 +1653,7 @@ function createOfflineTools(localStore, _privacyFilter, context) {
1488
1653
  }
1489
1654
  return `## Session Errors (${errors.length})
1490
1655
 
1491
- ${errors.map((e) => `- [${e.id.slice(0, 8)}] ${e.errorType}: ${e.errorMessage.slice(0, 80)}...`).join(`
1492
- `)}
1656
+ ${errors.map((e) => `- [${e.id.slice(0, 8)}] ${e.errorType}: ${e.errorMessage.slice(0, 80)}...`).join("\n")}
1493
1657
 
1494
1658
  *Cloud features disabled. Set FIXHIVE_SUPABASE_URL and FIXHIVE_SUPABASE_KEY to enable.*`;
1495
1659
  }
@@ -1548,7 +1712,7 @@ function detectLanguage(directory) {
1548
1712
  return lang;
1549
1713
  }
1550
1714
  }
1551
- return;
1715
+ return void 0;
1552
1716
  }
1553
1717
  function detectFramework(directory) {
1554
1718
  const pkgPath = join(directory, "package.json");
@@ -1556,61 +1720,54 @@ function detectFramework(directory) {
1556
1720
  try {
1557
1721
  const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1558
1722
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
1559
- if (deps["next"])
1560
- return "nextjs";
1561
- if (deps["react"])
1562
- return "react";
1563
- if (deps["vue"])
1564
- return "vue";
1565
- if (deps["@angular/core"])
1566
- return "angular";
1567
- if (deps["express"])
1568
- return "express";
1569
- if (deps["fastify"])
1570
- return "fastify";
1571
- if (deps["hono"])
1572
- return "hono";
1573
- } catch {}
1723
+ if (deps["next"]) return "nextjs";
1724
+ if (deps["react"]) return "react";
1725
+ if (deps["vue"]) return "vue";
1726
+ if (deps["@angular/core"]) return "angular";
1727
+ if (deps["express"]) return "express";
1728
+ if (deps["fastify"]) return "fastify";
1729
+ if (deps["hono"]) return "hono";
1730
+ } catch {
1731
+ }
1574
1732
  }
1575
1733
  const reqPath = join(directory, "requirements.txt");
1576
1734
  if (existsSync2(reqPath)) {
1577
1735
  try {
1578
1736
  const content = readFileSync(reqPath, "utf-8");
1579
- if (content.includes("django"))
1580
- return "django";
1581
- if (content.includes("flask"))
1582
- return "flask";
1583
- if (content.includes("fastapi"))
1584
- return "fastapi";
1585
- } catch {}
1737
+ if (content.includes("django")) return "django";
1738
+ if (content.includes("flask")) return "flask";
1739
+ if (content.includes("fastapi")) return "fastapi";
1740
+ } catch {
1741
+ }
1586
1742
  }
1587
- return;
1743
+ return void 0;
1588
1744
  }
1589
1745
  var plugin_default = FixHivePlugin;
1590
1746
  export {
1591
- shortHash,
1592
- sha256,
1593
- runMigrations,
1594
- normalizeErrorContent,
1595
- generateSessionHash,
1596
- generateErrorFingerprint,
1597
- generateContributorId,
1598
- fingerprintsMatch,
1599
- defaultPrivacyFilter,
1600
- defaultErrorDetector,
1601
- plugin_default as default,
1602
- createPrivacyFilter,
1603
- createLocalStore,
1604
- createFilterContext,
1605
- createErrorDetector,
1606
- createEmbeddingService,
1607
- createCloudClient,
1608
- cosineSimilarity,
1609
- calculateStringSimilarity,
1610
- PrivacyFilter,
1611
- LocalStore,
1612
- FixHivePlugin,
1613
- ErrorDetector,
1747
+ CloudClient,
1614
1748
  EmbeddingService,
1615
- CloudClient
1749
+ ErrorDetector,
1750
+ FixHivePlugin,
1751
+ LocalStore,
1752
+ PrivacyFilter,
1753
+ calculateStringSimilarity,
1754
+ cosineSimilarity,
1755
+ createCloudClient,
1756
+ createEmbeddingService,
1757
+ createErrorDetector,
1758
+ createFilterContext,
1759
+ createLocalStore,
1760
+ createPrivacyFilter,
1761
+ plugin_default as default,
1762
+ defaultErrorDetector,
1763
+ defaultPrivacyFilter,
1764
+ fingerprintsMatch,
1765
+ generateContributorId,
1766
+ generateErrorFingerprint,
1767
+ generateSessionHash,
1768
+ normalizeErrorContent,
1769
+ runMigrations,
1770
+ sha256,
1771
+ shortHash
1616
1772
  };
1773
+ //# sourceMappingURL=index.js.map