hyntx 2.4.0 → 2.5.4

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/api/index.js CHANGED
@@ -1,3078 +1 @@
1
- import { createHash } from 'crypto';
2
- import { existsSync, readdirSync, readFileSync } from 'fs';
3
- import { readFile, writeFile, rename, rm, mkdir } from 'fs/promises';
4
- import { join, basename, dirname } from 'path';
5
- import { homedir } from 'os';
6
- import { glob } from 'glob';
7
- import { startOfDay, parseISO, isAfter, subDays, format, subMonths, isSameDay, isBefore } from 'date-fns';
8
- import { z } from 'zod';
9
-
10
- // src/utils/logger-base.ts
11
- var BaseLogger = class {
12
- warnings = [];
13
- verboseEnabled = false;
14
- /**
15
- * Enables or disables verbose (debug) mode.
16
- *
17
- * @param enabled - Whether to enable verbose mode
18
- */
19
- setVerbose(enabled) {
20
- this.verboseEnabled = enabled;
21
- }
22
- /**
23
- * Returns whether verbose mode is enabled.
24
- *
25
- * @returns true if verbose mode is enabled
26
- */
27
- isVerbose() {
28
- return this.verboseEnabled;
29
- }
30
- /**
31
- * Logs an error message to stderr.
32
- *
33
- * @param message - Error message
34
- * @param context - Optional context (e.g., file name, operation)
35
- */
36
- error(message, context) {
37
- const prefix = context ? `[${context}] ` : "";
38
- process.stderr.write(`ERROR: ${prefix}${message}
39
- `);
40
- }
41
- /**
42
- * Logs a warning message to stderr.
43
- *
44
- * @param message - Warning message
45
- * @param context - Optional context (e.g., file name, operation)
46
- */
47
- warn(message, context) {
48
- const prefix = context ? `[${context}] ` : "";
49
- process.stderr.write(`WARN: ${prefix}${message}
50
- `);
51
- }
52
- /**
53
- * Logs an info message to stderr.
54
- *
55
- * @param message - Info message
56
- */
57
- info(message) {
58
- process.stderr.write(`INFO: ${message}
59
- `);
60
- }
61
- /**
62
- * Logs a debug message to stderr (only when verbose mode is enabled).
63
- *
64
- * @param message - Debug message
65
- * @param context - Optional context
66
- */
67
- debug(message, context) {
68
- if (this.verboseEnabled) {
69
- const prefix = context ? `[${context}] ` : "";
70
- process.stderr.write(`[DEBUG] ${prefix}${message}
71
- `);
72
- }
73
- }
74
- /**
75
- * Collects a warning for later reporting.
76
- * Use this for non-fatal issues that should be displayed at the end of execution.
77
- *
78
- * @param message - Warning message
79
- * @param context - Optional context (e.g., file name, operation)
80
- */
81
- collectWarning(message, context) {
82
- this.warnings.push({ message, context });
83
- }
84
- /**
85
- * Returns all collected warnings.
86
- *
87
- * @returns Array of collected warnings
88
- */
89
- getWarnings() {
90
- return [...this.warnings];
91
- }
92
- /**
93
- * Returns the number of collected warnings.
94
- *
95
- * @returns Warning count
96
- */
97
- getWarningCount() {
98
- return this.warnings.length;
99
- }
100
- /**
101
- * Clears all collected warnings.
102
- */
103
- clearWarnings() {
104
- this.warnings = [];
105
- }
106
- /**
107
- * Reports all collected warnings to stderr and clears them.
108
- * Does nothing if there are no warnings.
109
- */
110
- reportWarnings() {
111
- if (this.warnings.length === 0) {
112
- return;
113
- }
114
- process.stderr.write(`
115
- \u26A0\uFE0F ${String(this.warnings.length)} warning(s):
116
- `);
117
- for (const warning of this.warnings) {
118
- const prefix = warning.context ? `[${warning.context}] ` : "";
119
- process.stderr.write(` - ${prefix}${warning.message}
120
- `);
121
- }
122
- this.clearWarnings();
123
- }
124
- /**
125
- * Formats collected warnings as plain text (without ANSI colors).
126
- * Useful for JSON output or testing.
127
- *
128
- * @returns Array of formatted warning strings
129
- */
130
- formatWarnings() {
131
- return this.warnings.map((w) => {
132
- const prefix = w.context ? `[${w.context}] ` : "";
133
- return `${prefix}${w.message}`;
134
- });
135
- }
136
- };
137
- var logger = new BaseLogger();
138
-
139
- // src/core/sanitizer.ts
140
- function redactOpenAIKeys(text) {
141
- return text.replace(/sk-[a-zA-Z0-9]{48,}/g, "[REDACTED_OPENAI_KEY]");
142
- }
143
- function redactAnthropicKeys(text) {
144
- return text.replace(/sk-ant-[a-zA-Z0-9-]+/g, "[REDACTED_ANTHROPIC_KEY]");
145
- }
146
- function redactAWSCredentials(text) {
147
- return text.replace(/AKIA[0-9A-Z]{16}/g, "[REDACTED_AWS_KEY]");
148
- }
149
- function redactBearerTokens(text) {
150
- return text.replace(
151
- /Bearer(?:\s+token)?:?\s+[a-zA-Z0-9._-]{20,}/gi,
152
- "Bearer [REDACTED_TOKEN]"
153
- );
154
- }
155
- function redactURLCredentials(text) {
156
- return text.replace(
157
- /(https?:\/\/)([^:\s@]+)(?::([^\s@]+))?@/g,
158
- (match, protocol, _user, _pass) => {
159
- return `${protocol}[REDACTED_URL_CREDENTIAL]@`;
160
- }
161
- );
162
- }
163
- function redactEmails(text) {
164
- return text.replace(
165
- /[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
166
- "[REDACTED_EMAIL]"
167
- );
168
- }
169
- function redactPEMKeys(text) {
170
- return text.replace(
171
- /-----BEGIN\s+[A-Z\s]+PRIVATE\s+KEY-----[\s\S]*?-----END\s+[A-Z\s]+PRIVATE\s+KEY-----/g,
172
- "[REDACTED_PEM_KEY]"
173
- );
174
- }
175
- function redactNames(text) {
176
- return text.replace(
177
- /\b(?:Hi|Hello|Hey|Dear|Greetings|Good\s+(?:morning|afternoon|evening))\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?(?:\s+[A-Z][a-z]+)?)\b/gi,
178
- (match, name) => {
179
- const commonWords = /\b(?:there|everyone|all|team|guys|folks|people)\b/i;
180
- if (name && name.length >= 2 && !commonWords.test(name)) {
181
- return match.replace(name, "[REDACTED_NAME]");
182
- }
183
- return match;
184
- }
185
- );
186
- }
187
- function redactPhoneNumbers(text) {
188
- return text.replace(
189
- /(?:\+?1[-.\s]?)?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})\b/g,
190
- "[REDACTED_PHONE]"
191
- );
192
- }
193
- function redactCreditCards(text) {
194
- return text.replace(
195
- /\b(?:(?:4\d{3}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{1,4})|(?:5[1-5]\d{2}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4})|(?:3[47]\d{2}[\s-]?\d{6}[\s-]?\d{5})|(?:3[068]\d[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}))\b/g,
196
- "[REDACTED_CREDIT_CARD]"
197
- );
198
- }
199
- function redactSSN(text) {
200
- return text.replace(
201
- /\b(?!000|666|9\d{2})([0-9]{3})[-.\s]?(?!00)([0-9]{2})[-.\s]?(?!0000)([0-9]{4})\b/g,
202
- "[REDACTED_SSN]"
203
- );
204
- }
205
- function redactSpanishDNI(text) {
206
- return text.replace(/\b\d{8}[A-Z]\b/gi, "[REDACTED_SPANISH_DNI]");
207
- }
208
- function redactSpanishNIE(text) {
209
- return text.replace(/\b[XYZ]\d{7}[A-Z]\b/gi, "[REDACTED_SPANISH_NIE]");
210
- }
211
- function redactMexicanCURP(text) {
212
- return text.replace(
213
- /\b[A-Z]{4}\d{6}[HM][A-Z]{5}[0-9A-Z]{2}\b/gi,
214
- "[REDACTED_MEXICAN_CURP]"
215
- );
216
- }
217
- function redactBrazilianCPF(text) {
218
- return text.replace(
219
- /\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,
220
- "[REDACTED_BRAZILIAN_CPF]"
221
- );
222
- }
223
- function redactUKNINO(text) {
224
- return text.replace(
225
- /\b[A-Z]{2}\s?\d{2}\s?\d{2}\s?\d{2}\s?[A-Z]\b/gi,
226
- "[REDACTED_UK_NINO]"
227
- );
228
- }
229
- function redactChileanRUN(text) {
230
- return text.replace(
231
- /\b(?:RUN|RUT)[\s:]*([0-9]{7,8}-[0-9K]|[0-9]{8}[0-9K])\b/gi,
232
- (match, run) => {
233
- return match.replace(run, "[REDACTED_CHILEAN_RUN]");
234
- }
235
- );
236
- }
237
- function redactArgentineDNI(text) {
238
- return text.replace(
239
- /\b(?:DNI|dni)[\s:]*(\d{8})\b/gi,
240
- (match, dni) => {
241
- return match.replace(dni, "[REDACTED_ARGENTINE_DNI]");
242
- }
243
- );
244
- }
245
- function redactIPv4(text) {
246
- return text.replace(
247
- /\b(?!(?:127\.0\.0\.1|0\.0\.0\.0|255\.255\.255\.255))(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,
248
- "[REDACTED_IPV4]"
249
- );
250
- }
251
- function redactIPv6(text) {
252
- return text.replace(
253
- /\b(?!(?:::1|::))(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,7}::\b|\b::(?:[0-9a-fA-F]{1,4}:){1,7}[0-9a-fA-F]{1,4}\b/g,
254
- "[REDACTED_IPV6]"
255
- );
256
- }
257
- function redactMACAddresses(text) {
258
- return text.replace(
259
- /\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\b/g,
260
- "[REDACTED_MAC_ADDRESS]"
261
- );
262
- }
263
- function redactPassportNumbers(text) {
264
- return text.replace(
265
- /\b(?:passport|pasaporte)[\s:]*([A-Z0-9]{6,9})\b/gi,
266
- (match, passport) => {
267
- return match.replace(passport, "[REDACTED_PASSPORT]");
268
- }
269
- );
270
- }
271
- function redactDriverLicenseNumbers(text) {
272
- return text.replace(
273
- /\b(?:driver\s*license|licencia\s*de\s*conducir|DL|D\.L\.)[\s:]*([A-Z0-9]{8,16})\b/gi,
274
- (match, license) => {
275
- return match.replace(license, "[REDACTED_DRIVER_LICENSE]");
276
- }
277
- );
278
- }
279
- function redactAddresses(text) {
280
- let sanitized = text;
281
- sanitized = sanitized.replace(/\b\d{5}(?:-\d{4})?\b/g, "[REDACTED_ZIP_CODE]");
282
- sanitized = sanitized.replace(
283
- /\b[A-Z]{1,2}\d{1,2}[A-Z]?\s?\d[A-Z]{2}\b/gi,
284
- "[REDACTED_POSTCODE]"
285
- );
286
- sanitized = sanitized.replace(
287
- /\b[A-Z]\d[A-Z]\s?\d[A-Z]\d\b/gi,
288
- "[REDACTED_POSTAL_CODE]"
289
- );
290
- sanitized = sanitized.replace(
291
- /\b(?:address|direcci[oó]n|street|calle|avenue|ave)[\s:]*(\d+\s+[A-Za-z\s]+(?:street|st|avenue|ave|road|rd|boulevard|blvd|drive|dr|lane|ln|way|circle|cir))?\b/gi,
292
- (match) => {
293
- return match.replace(
294
- /\d+\s+[A-Za-z\s]+(?:street|st|avenue|ave|road|rd|boulevard|blvd|drive|dr|lane|ln|way|circle|cir)/gi,
295
- "[REDACTED_ADDRESS]"
296
- );
297
- }
298
- );
299
- return sanitized;
300
- }
301
- function redactBirthDates(text) {
302
- return text.replace(
303
- /\b(?:DOB|date\s+of\s+birth|fecha\s+de\s+nacimiento|born)[\s:]*(\d{1,2}[-/.]\d{1,2}[-/.]\d{2,4})\b/gi,
304
- (match, date) => {
305
- return match.replace(date, "[REDACTED_BIRTH_DATE]");
306
- }
307
- );
308
- }
309
- function countRedactions(original, sanitized) {
310
- const redactionPattern = /\[REDACTED_[^\]]+\]/g;
311
- const matches = sanitized.match(redactionPattern);
312
- return matches ? matches.length : 0;
313
- }
314
- function sanitize(text) {
315
- if (!text || text.trim().length === 0) {
316
- return { text, redacted: 0 };
317
- }
318
- let sanitized = text;
319
- sanitized = redactOpenAIKeys(sanitized);
320
- sanitized = redactAnthropicKeys(sanitized);
321
- sanitized = redactAWSCredentials(sanitized);
322
- sanitized = redactBearerTokens(sanitized);
323
- sanitized = redactURLCredentials(sanitized);
324
- sanitized = redactPEMKeys(sanitized);
325
- sanitized = redactEmails(sanitized);
326
- sanitized = redactCreditCards(sanitized);
327
- sanitized = redactPassportNumbers(sanitized);
328
- sanitized = redactDriverLicenseNumbers(sanitized);
329
- sanitized = redactSpanishDNI(sanitized);
330
- sanitized = redactSpanishNIE(sanitized);
331
- sanitized = redactMexicanCURP(sanitized);
332
- sanitized = redactBrazilianCPF(sanitized);
333
- sanitized = redactUKNINO(sanitized);
334
- sanitized = redactChileanRUN(sanitized);
335
- sanitized = redactArgentineDNI(sanitized);
336
- sanitized = redactAddresses(sanitized);
337
- sanitized = redactBirthDates(sanitized);
338
- sanitized = redactNames(sanitized);
339
- sanitized = redactSSN(sanitized);
340
- sanitized = redactPhoneNumbers(sanitized);
341
- sanitized = redactIPv4(sanitized);
342
- sanitized = redactIPv6(sanitized);
343
- sanitized = redactMACAddresses(sanitized);
344
- const redacted = countRedactions(text, sanitized);
345
- return {
346
- text: sanitized,
347
- redacted
348
- };
349
- }
350
- function sanitizePrompts(prompts) {
351
- if (prompts.length === 0) {
352
- return { prompts: [], totalRedacted: 0 };
353
- }
354
- logger.debug(
355
- `Sanitizing ${String(prompts.length)} prompts for secrets`,
356
- "sanitizer"
357
- );
358
- const sanitizedPrompts = [];
359
- let totalRedacted = 0;
360
- for (const prompt of prompts) {
361
- const result = sanitize(prompt);
362
- sanitizedPrompts.push(result.text);
363
- totalRedacted += result.redacted;
364
- }
365
- if (totalRedacted > 0) {
366
- logger.debug(
367
- `Redacted ${String(totalRedacted)} secret(s) from prompts`,
368
- "sanitizer"
369
- );
370
- } else {
371
- logger.debug("No secrets found to redact", "sanitizer");
372
- }
373
- return {
374
- prompts: sanitizedPrompts,
375
- totalRedacted
376
- };
377
- }
378
- var HOME = homedir();
379
- var CLAUDE_PROJECTS_DIR = process.env["HYNTX_CLAUDE_PROJECTS_DIR"] ?? join(HOME, ".claude", "projects");
380
- var LAST_RUN_FILE = join(HOME, ".hyntx-last-run");
381
- var HYNTX_HISTORY_DIR = process.env["HYNTX_HISTORY_DIR"] ?? join(HOME, ".hyntx", "history");
382
- var HYNTX_CACHE_DIR = process.env["HYNTX_CACHE_DIR"] ?? join(HOME, ".hyntx-cache");
383
- var CACHE_ANALYSIS_DIR = join(HYNTX_CACHE_DIR, "analysis");
384
- var CACHE_META_FILE = join(CACHE_ANALYSIS_DIR, ".metadata.json");
385
- process.env["HYNTX_RESULTS_DIR"] ?? join(HOME, ".hyntx", "results");
386
-
387
- // src/providers/schemas.ts
388
- var ISSUE_TAXONOMY = {
389
- vague: {
390
- name: "Vague Request",
391
- severity: "high",
392
- suggestion: "Be more specific about what you need - include function names, file paths, error messages, or specific behaviors",
393
- exampleBefore: "Help me with my code",
394
- exampleAfter: "Help me debug the calculateTotal() function in utils.ts that returns undefined when called with an empty array"
395
- },
396
- "no-context": {
397
- name: "Missing Context",
398
- severity: "high",
399
- suggestion: "Provide relevant background information - include file paths, function names, error messages, or code snippets",
400
- exampleBefore: "Fix the bug",
401
- exampleAfter: "Fix the bug in src/auth/login.ts where users are logged out after 5 minutes due to token expiration logic"
402
- },
403
- "too-broad": {
404
- name: "Too Broad",
405
- severity: "medium",
406
- suggestion: "Break down into smaller, focused requests - focus on one task or clearly order multiple related tasks",
407
- exampleBefore: "Build me an app with authentication, database, and API",
408
- exampleAfter: "Create a React login component with email/password authentication using JWT tokens"
409
- },
410
- "no-goal": {
411
- name: "No Clear Goal",
412
- severity: "high",
413
- suggestion: "State what outcome you want to achieve - specify success criteria and desired behavior",
414
- exampleBefore: "Look at this file",
415
- exampleAfter: "Review src/auth/login.ts for security vulnerabilities, focusing on input validation and SQL injection risks"
416
- },
417
- imperative: {
418
- name: "Command Without Context",
419
- severity: "low",
420
- suggestion: "Explain why you need this - provide context about the use case and requirements",
421
- exampleBefore: "Add a button",
422
- exampleAfter: 'Add a "Submit" button to the login form that triggers validation and calls the authentication API'
423
- },
424
- "missing-technical-details": {
425
- name: "Missing Technical Details",
426
- severity: "medium",
427
- suggestion: "Include technical details - file paths, function signatures, error messages, stack traces, or code snippets",
428
- exampleBefore: "The function crashes sometimes",
429
- exampleAfter: `The validateUser() function in src/utils/auth.ts crashes with "Cannot read property 'email' of null" when called with undefined`
430
- },
431
- "unclear-priorities": {
432
- name: "Unclear Priorities",
433
- severity: "low",
434
- suggestion: "Order multiple requests by priority or split into separate prompts for clarity",
435
- exampleBefore: "Add error handling and logging and also optimize performance and add tests",
436
- exampleAfter: "First, add comprehensive error handling with try-catch blocks. Then, add logging for debugging. Finally, optimize database queries."
437
- },
438
- "insufficient-constraints": {
439
- name: "Insufficient Constraints",
440
- severity: "low",
441
- suggestion: "Specify requirements and constraints - edge cases, performance needs, compatibility requirements",
442
- exampleBefore: "Make it faster",
443
- exampleAfter: "Optimize the database query to reduce response time to under 100ms, maintaining backward compatibility with existing API clients"
444
- }
445
- };
446
- var SYSTEM_PROMPT_MINIMAL = `You analyze prompts for quality issues.
447
- Respond with JSON only: {"issues": ["issue-id", ...], "score": 0-100}
448
-
449
- Valid issue IDs: vague, no-context, too-broad, no-goal, imperative, missing-technical-details, unclear-priorities, insufficient-constraints
450
-
451
- Issue definitions:
452
- - vague: Generic requests without specifics ("help", "fix", "improve")
453
- - no-context: Missing background info (uses "this", "it", "the bug" without context)
454
- - too-broad: Requests covering multiple unrelated topics
455
- - no-goal: Ambiguous success criteria or desired outcome
456
- - imperative: Commands without explanation or reasoning
457
- - missing-technical-details: No file paths, function names, or error messages
458
- - unclear-priorities: Multiple requests without ordering
459
- - insufficient-constraints: No requirements or edge cases mentioned
460
-
461
- Scoring: 0-100 (100=perfect, 90+=excellent, 70-89=good, 50-69=fair, <50=poor)
462
-
463
- Examples:
464
- Input: "Help me with code"
465
- Output: {"issues": ["vague", "no-context"], "score": 35}
466
-
467
- Input: "Debug this TypeScript function that returns undefined"
468
- Output: {"issues": ["missing-technical-details"], "score": 70}
469
-
470
- Input: "Debug calculateTotal() in utils.ts that returns undefined when called with empty array"
471
- Output: {"issues": [], "score": 90}`;
472
- var SYSTEM_PROMPT_FULL = `You are an expert prompt quality analyst specializing in code-related prompts for AI assistants like Claude. Your task is to analyze prompts and identify patterns that reduce their effectiveness, providing actionable improvements.
473
-
474
- CRITICAL: Return ONLY valid JSON following the exact schema below. No markdown, no explanations, no code fences - just pure JSON.
475
-
476
- Schema:
477
- {
478
- "patterns": [
479
- {
480
- "id": "kebab-case-id",
481
- "name": "Human-Readable Issue Name",
482
- "frequency": 3,
483
- "severity": "high|medium|low",
484
- "examples": ["example prompt 1", "example prompt 2"],
485
- "suggestion": "Actionable advice to fix this pattern",
486
- "beforeAfter": {
487
- "before": "Original problematic prompt",
488
- "after": "Improved version addressing the issue"
489
- }
490
- }
491
- ],
492
- "stats": {
493
- "totalPrompts": 10,
494
- "promptsWithIssues": 7,
495
- "overallScore": 65
496
- },
497
- "topSuggestion": "Single most impactful recommendation"
498
- }
499
-
500
- QUALITY DIMENSIONS TO EVALUATE:
501
-
502
- 1. SPECIFICITY (High Priority)
503
- - Vague: "help me", "fix this", "improve code" without specifics
504
- - Good: Includes function names, file paths, error messages, specific behaviors
505
- - Look for: Generic verbs without objects, pronouns without referents
506
-
507
- 2. CONTEXT PROVISION (High Priority)
508
- - Missing: References to "this code", "the bug", "it" without background
509
- - Good: Provides file paths, function signatures, relevant code snippets, error stack traces
510
- - Look for: Unclear referents, assumptions of shared knowledge
511
-
512
- 3. GOAL CLARITY (High Priority)
513
- - Unclear: "Look at this", "Review my code", "What's wrong?"
514
- - Good: Explicitly states desired outcome: "Find security vulnerabilities", "Optimize for performance", "Fix the null pointer exception"
515
- - Look for: Ambiguous success criteria, open-ended questions
516
-
517
- 4. SCOPE APPROPRIATENESS (Medium Priority)
518
- - Too broad: "Build me an app", "Refactor everything", multiple unrelated tasks
519
- - Too narrow: Overly specific constraints that limit solution space unnecessarily
520
- - Good: Focused single task or clearly ordered multiple tasks
521
- - Look for: Multiple "and" clauses, unrelated requests, scope creep
522
-
523
- 5. ACTIONABILITY (Medium Priority)
524
- - Low: "What do you think?", "Is this good?", purely exploratory
525
- - Good: Clear action requested: "Fix", "Implement", "Refactor", "Add"
526
- - Look for: Vague intentions, exploration without purpose
527
-
528
- 6. TECHNICAL RICHNESS (Medium Priority)
529
- - Missing: No code examples, file paths, function names, error messages
530
- - Good: Includes relevant code, stack traces, configuration, environment details
531
- - Look for: Purely conceptual descriptions without technical details
532
-
533
- 7. CONSTRAINT DEFINITION (Low Priority)
534
- - Missing: No requirements, edge cases, or constraints mentioned
535
- - Good: Specifies requirements, edge cases, performance needs, compatibility needs
536
- - Look for: Requests that could have many valid interpretations
537
-
538
- SEVERITY GUIDELINES:
539
- - high: Significantly impairs prompt effectiveness (vague, missing context, no goal)
540
- - medium: Moderate impact on effectiveness (too broad, lacks technical details)
541
- - low: Minor improvement opportunity (missing constraints, could be more specific)
542
-
543
- SCORING GUIDELINES (0-100):
544
- - 90-100: Excellent prompts - specific, contextual, actionable, well-scoped
545
- - 75-89: Good prompts - minor improvements possible
546
- - 60-74: Fair prompts - needs more context, clarity, or specificity
547
- - 40-59: Poor prompts - multiple significant issues, partially actionable
548
- - 20-39: Very poor - barely actionable, missing critical information
549
- - 0-19: Extremely poor - cannot be meaningfully acted upon
550
-
551
- PATTERN IDENTIFICATION:
552
- - Group similar issues together (same root cause)
553
- - Count frequency: how many prompts exhibit this pattern
554
- - Provide 1-3 real examples from the actual prompts analyzed
555
- - Create meaningful before/after pairs that clearly show improvement
556
- - Ensure beforeAfter.before matches one of the examples
557
-
558
- IMPROVEMENT PRIORITIES:
559
- 1. High severity patterns (vague, missing context, no goal) should appear first
560
- 2. More frequent patterns should rank higher
561
- 3. topSuggestion should address the most common high-severity issue
562
-
563
- Remember: The goal is actionable feedback. Focus on patterns that, when fixed, would meaningfully improve prompt effectiveness for AI code assistants.`;
564
- var VALID_PATTERN_IDS = Object.keys(ISSUE_TAXONOMY);
565
- function applyRulesConfig(rules, baseTaxonomy = ISSUE_TAXONOMY) {
566
- if (!rules || Object.keys(rules).length === 0) {
567
- return baseTaxonomy;
568
- }
569
- for (const ruleId of Object.keys(rules)) {
570
- if (!VALID_PATTERN_IDS.includes(ruleId)) {
571
- logger.warn(
572
- `Unknown rule ID "${ruleId}" in configuration. Valid IDs are: ${VALID_PATTERN_IDS.join(", ")}`,
573
- "config"
574
- );
575
- }
576
- }
577
- const newTaxonomy = {};
578
- for (const [patternId, metadata] of Object.entries(baseTaxonomy)) {
579
- const ruleConfig = rules[patternId];
580
- if (ruleConfig?.enabled === false) {
581
- continue;
582
- }
583
- if (ruleConfig?.severity) {
584
- newTaxonomy[patternId] = {
585
- ...metadata,
586
- severity: ruleConfig.severity
587
- };
588
- } else {
589
- newTaxonomy[patternId] = metadata;
590
- }
591
- }
592
- if (Object.keys(newTaxonomy).length === 0) {
593
- logger.collectWarning(
594
- "All analysis rules are disabled in configuration. No patterns will be detected.",
595
- "config"
596
- );
597
- }
598
- return newTaxonomy;
599
- }
600
-
601
- // src/types/index.ts
602
- var BATCH_STRATEGIES = {
603
- // For models < 4GB
604
- micro: {
605
- maxTokensPerBatch: 500,
606
- maxPromptsPerBatch: 3,
607
- description: "For models < 4GB"
608
- },
609
- // For models 4-7GB
610
- small: {
611
- maxTokensPerBatch: 1500,
612
- maxPromptsPerBatch: 10,
613
- description: "For models 4-7GB"
614
- },
615
- // For models > 7GB
616
- standard: {
617
- maxTokensPerBatch: 3e3,
618
- maxPromptsPerBatch: 50,
619
- description: "For models > 7GB"
620
- }
621
- };
622
- var PROVIDER_LIMITS = {
623
- // Small local models struggle with large inputs - limit to ~10 short prompts
624
- ollama: { maxTokensPerBatch: 3e3, prioritization: "longest-first" },
625
- anthropic: { maxTokensPerBatch: 1e5, prioritization: "chronological" },
626
- google: { maxTokensPerBatch: 5e5, prioritization: "chronological" }
627
- };
628
- var ENV_DEFAULTS = {
629
- reminder: "7d",
630
- ollama: {
631
- model: "llama3.2",
632
- host: "http://localhost:11434"
633
- },
634
- anthropic: {
635
- model: "claude-3-5-haiku-latest"
636
- },
637
- google: {
638
- model: "gemini-2.0-flash-exp"
639
- }
640
- };
641
- var EXIT_CODES = {
642
- SUCCESS: 0,
643
- ERROR: 1,
644
- NO_DATA: 2,
645
- PROVIDER_UNAVAILABLE: 3
646
- };
647
- var CACHE_DEFAULTS = {
648
- ttlMs: 7 * 24 * 60 * 60 * 1e3
649
- // 7 days in milliseconds
650
- };
651
-
652
- // src/cache/analysis-cache.ts
653
- async function ensureCacheDir() {
654
- try {
655
- await mkdir(CACHE_ANALYSIS_DIR, { recursive: true, mode: 448 });
656
- } catch (error) {
657
- const errorMessage = error instanceof Error ? error.message : String(error);
658
- throw new Error(
659
- `Failed to create cache directory ${CACHE_ANALYSIS_DIR}: ${errorMessage}`
660
- );
661
- }
662
- }
663
- function getCacheFilePath(cacheKey) {
664
- return join(CACHE_ANALYSIS_DIR, `${cacheKey}.json`);
665
- }
666
- function hashString(input) {
667
- return createHash("sha256").update(input, "utf-8").digest("hex");
668
- }
669
- function generateCacheKey(prompts, model, schemaType = "full") {
670
- const joined = prompts.join("\n---\n");
671
- const input = `${model}:${schemaType}:${joined}`;
672
- return hashString(input);
673
- }
674
- function hashSystemPrompt() {
675
- return hashString(SYSTEM_PROMPT_FULL);
676
- }
677
- async function loadCacheMetadata() {
678
- if (!existsSync(CACHE_META_FILE)) {
679
- return null;
680
- }
681
- try {
682
- const content = await readFile(CACHE_META_FILE, "utf-8");
683
- const metadata = JSON.parse(content);
684
- return metadata;
685
- } catch (error) {
686
- const errorMessage = error instanceof Error ? error.message : String(error);
687
- logger.warn(`Failed to load cache metadata: ${errorMessage}`, "cache");
688
- return null;
689
- }
690
- }
691
- async function saveCacheMetadata(metadata) {
692
- try {
693
- await ensureCacheDir();
694
- const content = JSON.stringify(metadata, null, 2);
695
- const tmpFile = `${CACHE_META_FILE}.tmp`;
696
- await writeFile(tmpFile, content, "utf-8");
697
- await rename(tmpFile, CACHE_META_FILE);
698
- logger.debug("Saved cache metadata", "cache");
699
- } catch (error) {
700
- const errorMessage = error instanceof Error ? error.message : String(error);
701
- logger.warn(`Failed to save cache metadata: ${errorMessage}`, "cache");
702
- }
703
- }
704
- async function validateSystemPrompt() {
705
- const currentHash = hashSystemPrompt();
706
- const metadata = await loadCacheMetadata();
707
- if (!metadata) {
708
- await saveCacheMetadata({
709
- systemPromptHash: currentHash,
710
- lastUpdated: Date.now()
711
- });
712
- return true;
713
- }
714
- if (metadata.systemPromptHash !== currentHash) {
715
- logger.debug("System prompt changed - invalidating cache", "cache");
716
- await clearCache();
717
- await saveCacheMetadata({
718
- systemPromptHash: currentHash,
719
- lastUpdated: Date.now()
720
- });
721
- return false;
722
- }
723
- return true;
724
- }
725
- async function getCachedResult(prompts, model, options = CACHE_DEFAULTS) {
726
- await validateSystemPrompt();
727
- const cacheKey = generateCacheKey(prompts, model);
728
- const filePath = getCacheFilePath(cacheKey);
729
- if (!existsSync(filePath)) {
730
- logger.debug(`Cache miss for key ${cacheKey}`, "cache");
731
- return null;
732
- }
733
- try {
734
- const content = await readFile(filePath, "utf-8");
735
- const data = JSON.parse(content);
736
- if (!data.metadata || !data.result) {
737
- logger.debug(`Invalid cache entry for key ${cacheKey}`, "cache");
738
- return null;
739
- }
740
- const cached = data;
741
- const now = Date.now();
742
- const age = now - cached.metadata.cachedAt;
743
- if (age > options.ttlMs) {
744
- logger.debug(
745
- `Cache entry expired for key ${cacheKey} (age: ${String(age)}ms)`,
746
- "cache"
747
- );
748
- return null;
749
- }
750
- if (cached.metadata.model !== model) {
751
- logger.debug(
752
- `Model mismatch for key ${cacheKey} (cached: ${cached.metadata.model}, requested: ${model})`,
753
- "cache"
754
- );
755
- return null;
756
- }
757
- if (cached.metadata.promptCount !== prompts.length) {
758
- logger.debug(`Prompt count mismatch for key ${cacheKey}`, "cache");
759
- return null;
760
- }
761
- logger.debug(`Cache hit for key ${cacheKey}`, "cache");
762
- return cached.result;
763
- } catch (error) {
764
- const errorMessage = error instanceof Error ? error.message : String(error);
765
- logger.warn(
766
- `Failed to read cache entry ${cacheKey}: ${errorMessage}`,
767
- "cache"
768
- );
769
- return null;
770
- }
771
- }
772
- async function setCachedResult(prompts, model, result) {
773
- try {
774
- await ensureCacheDir();
775
- await validateSystemPrompt();
776
- const cacheKey = generateCacheKey(prompts, model);
777
- const filePath = getCacheFilePath(cacheKey);
778
- const metadata = {
779
- cachedAt: Date.now(),
780
- promptCount: prompts.length,
781
- model,
782
- systemPromptHash: hashSystemPrompt()
783
- };
784
- const cached = {
785
- result,
786
- metadata
787
- };
788
- const content = JSON.stringify(cached, null, 2);
789
- const tmpFile = `${filePath}.tmp`;
790
- await writeFile(tmpFile, content, "utf-8");
791
- await rename(tmpFile, filePath);
792
- logger.debug(`Cached result for key ${cacheKey}`, "cache");
793
- } catch (error) {
794
- const errorMessage = error instanceof Error ? error.message : String(error);
795
- logger.warn(`Failed to cache result: ${errorMessage}`, "cache");
796
- }
797
- }
798
- async function clearCache() {
799
- if (!existsSync(CACHE_ANALYSIS_DIR)) {
800
- logger.debug("Cache directory does not exist - nothing to clear", "cache");
801
- return;
802
- }
803
- try {
804
- await rm(CACHE_ANALYSIS_DIR, { recursive: true, force: true });
805
- logger.debug("Cache cleared", "cache");
806
- } catch (error) {
807
- const errorMessage = error instanceof Error ? error.message : String(error);
808
- logger.warn(`Failed to clear cache: ${errorMessage}`, "cache");
809
- }
810
- }
811
- async function cleanupExpiredEntries(options = CACHE_DEFAULTS) {
812
- if (!existsSync(CACHE_ANALYSIS_DIR)) {
813
- return 0;
814
- }
815
- try {
816
- const files = readdirSync(CACHE_ANALYSIS_DIR);
817
- const now = Date.now();
818
- let removedCount = 0;
819
- for (const file of files) {
820
- if (!file.endsWith(".json") || file === ".metadata.json") {
821
- continue;
822
- }
823
- const filePath = join(CACHE_ANALYSIS_DIR, file);
824
- try {
825
- const content = await readFile(filePath, "utf-8");
826
- const cached = JSON.parse(content);
827
- const age = now - cached.metadata.cachedAt;
828
- if (age > options.ttlMs) {
829
- await rm(filePath, { force: true });
830
- removedCount++;
831
- logger.debug(`Removed expired cache entry: ${file}`, "cache");
832
- }
833
- } catch {
834
- await rm(filePath, { force: true });
835
- removedCount++;
836
- logger.debug(`Removed invalid cache entry: ${file}`, "cache");
837
- }
838
- }
839
- if (removedCount > 0) {
840
- logger.debug(
841
- `Cleanup removed ${String(removedCount)} expired entries`,
842
- "cache"
843
- );
844
- }
845
- return removedCount;
846
- } catch (error) {
847
- const errorMessage = error instanceof Error ? error.message : String(error);
848
- logger.warn(`Failed to cleanup expired entries: ${errorMessage}`, "cache");
849
- return 0;
850
- }
851
- }
852
-
853
- // src/core/analyzer.ts
854
- var SYSTEM_OVERHEAD_TOKENS = 2e3;
855
- var SEVERITY_RANK = {
856
- high: 3,
857
- medium: 2,
858
- low: 1
859
- };
860
- var MAX_PATTERNS = 5;
861
- var MAX_EXAMPLES_PER_PATTERN = 3;
862
- var CHARS_PER_TOKEN = 4;
863
- function hasDynamicLimits(provider) {
864
- return typeof provider.getBatchLimits === "function";
865
- }
866
- function shouldFallback(error) {
867
- const message = error.message.toLowerCase();
868
- return message.includes("parse") || message.includes("schema") || message.includes("json") || message.includes("timeout") || message.includes("network") || message.includes("failed");
869
- }
870
- function average(numbers) {
871
- if (numbers.length === 0) return 0;
872
- return sum(numbers) / numbers.length;
873
- }
874
- function sum(numbers) {
875
- return numbers.reduce((acc, n) => acc + n, 0);
876
- }
877
- function flattenAll(arrays) {
878
- const result = [];
879
- for (const arr of arrays) {
880
- for (const item of arr) {
881
- result.push(item);
882
- }
883
- }
884
- return result;
885
- }
886
- function limitExamples(examples, max) {
887
- return examples.slice(0, max);
888
- }
889
- function inferProviderType(providerName) {
890
- const nameLower = providerName.toLowerCase();
891
- if (nameLower.includes("ollama")) return "ollama";
892
- if (nameLower.includes("anthropic") || nameLower.includes("claude"))
893
- return "anthropic";
894
- if (nameLower.includes("google") || nameLower.includes("gemini"))
895
- return "google";
896
- return "ollama";
897
- }
898
- function extractModelFromProvider(providerName) {
899
- const match = /\((.*?)\)/.exec(providerName);
900
- return match?.[1] ?? providerName;
901
- }
902
- function maxSeverity(severities) {
903
- if (severities.length === 0) return "low";
904
- let max = "low";
905
- let maxRank = SEVERITY_RANK.low;
906
- for (const severity of severities) {
907
- const rank = SEVERITY_RANK[severity];
908
- if (rank > maxRank) {
909
- max = severity;
910
- maxRank = rank;
911
- }
912
- }
913
- return max;
914
- }
915
- async function analyzeWithFallback(provider, prompts, date, context, model, noCache) {
916
- if (prompts.length === 0) {
917
- return [];
918
- }
919
- try {
920
- if (!noCache) {
921
- const cachedResult = await getCachedResult(
922
- prompts,
923
- model,
924
- CACHE_DEFAULTS
925
- );
926
- if (cachedResult) {
927
- logger.debug(
928
- `Using cached result for batch of ${String(prompts.length)} prompt(s)`,
929
- "analyzer"
930
- );
931
- return [{ ...cachedResult, date }];
932
- }
933
- }
934
- const result = await provider.analyze(prompts, date, context);
935
- if (!noCache) {
936
- await setCachedResult(prompts, model, result);
937
- }
938
- return [result];
939
- } catch (error) {
940
- const err = error instanceof Error ? error : new Error(String(error));
941
- if (shouldFallback(err)) {
942
- if (prompts.length > 1) {
943
- const mid = Math.ceil(prompts.length / 2);
944
- const leftPrompts = prompts.slice(0, mid);
945
- const rightPrompts = prompts.slice(mid);
946
- logger.debug(
947
- `Batch of ${String(prompts.length)} failed, splitting into ${String(leftPrompts.length)} + ${String(rightPrompts.length)}`,
948
- "analyzer"
949
- );
950
- const [leftResults, rightResults] = await Promise.all([
951
- analyzeWithFallback(
952
- provider,
953
- leftPrompts,
954
- date,
955
- context,
956
- model,
957
- noCache
958
- ),
959
- analyzeWithFallback(
960
- provider,
961
- rightPrompts,
962
- date,
963
- context,
964
- model,
965
- noCache
966
- )
967
- ]);
968
- return [...leftResults, ...rightResults];
969
- }
970
- const promptPreview = prompts[0]?.slice(0, 50) ?? "unknown";
971
- logger.warn(
972
- `Skipped single prompt due to error: ${promptPreview}... (${err.message})`,
973
- "analyzer"
974
- );
975
- return [];
976
- }
977
- throw err;
978
- }
979
- }
980
- function estimateTokens(text) {
981
- if (!text || text.length === 0) return 0;
982
- return Math.ceil(text.length / CHARS_PER_TOKEN);
983
- }
984
- function batchPrompts(options) {
985
- const { prompts, maxTokensPerBatch, maxPromptsPerBatch, prioritization } = options;
986
- if (prompts.length === 0) {
987
- return [];
988
- }
989
- const effectiveLimit = maxTokensPerBatch - SYSTEM_OVERHEAD_TOKENS;
990
- const promptsWithTokens = prompts.map((prompt) => ({
991
- prompt,
992
- tokens: estimateTokens(prompt)
993
- }));
994
- const sorted = prioritization === "longest-first" ? [...promptsWithTokens].sort((a, b) => b.tokens - a.tokens) : promptsWithTokens;
995
- const batches = [];
996
- let currentBatch = [];
997
- let currentTokens = 0;
998
- for (const { prompt, tokens } of sorted) {
999
- if (tokens > effectiveLimit) {
1000
- if (currentBatch.length > 0) {
1001
- batches.push({ prompts: currentBatch, tokens: currentTokens });
1002
- currentBatch = [];
1003
- currentTokens = 0;
1004
- }
1005
- batches.push({ prompts: [prompt], tokens });
1006
- continue;
1007
- }
1008
- const wouldExceedTokens = currentTokens + tokens > effectiveLimit && currentBatch.length > 0;
1009
- const wouldExceedPrompts = maxPromptsPerBatch !== void 0 && currentBatch.length >= maxPromptsPerBatch;
1010
- if (wouldExceedTokens || wouldExceedPrompts) {
1011
- batches.push({ prompts: currentBatch, tokens: currentTokens });
1012
- currentBatch = [prompt];
1013
- currentTokens = tokens;
1014
- } else {
1015
- currentBatch.push(prompt);
1016
- currentTokens += tokens;
1017
- }
1018
- }
1019
- if (currentBatch.length > 0) {
1020
- batches.push({ prompts: currentBatch, tokens: currentTokens });
1021
- }
1022
- return batches;
1023
- }
1024
- function mergeBatchResults(options) {
1025
- const { results, date } = options;
1026
- if (results.length === 0) {
1027
- throw new Error("Cannot merge empty results array");
1028
- }
1029
- if (results.length === 1) {
1030
- const result = results[0];
1031
- if (!result) {
1032
- throw new Error("Results array is empty");
1033
- }
1034
- const limitedPatterns = result.patterns.map((p) => ({
1035
- ...p,
1036
- examples: limitExamples(p.examples, MAX_EXAMPLES_PER_PATTERN)
1037
- })).sort((a, b) => {
1038
- const severityDiff = SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity];
1039
- if (severityDiff !== 0) return severityDiff;
1040
- return b.frequency - a.frequency;
1041
- }).slice(0, MAX_PATTERNS);
1042
- const topSuggestion2 = limitedPatterns.length > 0 && limitedPatterns[0] ? limitedPatterns[0].suggestion : result.topSuggestion;
1043
- return {
1044
- ...result,
1045
- date,
1046
- patterns: limitedPatterns,
1047
- topSuggestion: topSuggestion2
1048
- };
1049
- }
1050
- const allPatterns = flattenAll(results.map((r) => r.patterns));
1051
- const patternGroups = /* @__PURE__ */ new Map();
1052
- for (const pattern of allPatterns) {
1053
- const group = patternGroups.get(pattern.id) ?? [];
1054
- group.push(pattern);
1055
- patternGroups.set(pattern.id, group);
1056
- }
1057
- const mergedPatterns = [];
1058
- for (const group of patternGroups.values()) {
1059
- if (group.length === 0) continue;
1060
- const firstPattern = group[0];
1061
- if (!firstPattern) continue;
1062
- if (group.length === 1) {
1063
- mergedPatterns.push({
1064
- ...firstPattern,
1065
- examples: limitExamples(
1066
- firstPattern.examples,
1067
- MAX_EXAMPLES_PER_PATTERN
1068
- )
1069
- });
1070
- } else {
1071
- const frequencies = group.map((p) => p.frequency);
1072
- const severities = group.map((p) => p.severity);
1073
- const allExamples = group.flatMap((p) => Array.from(p.examples));
1074
- const mergedFrequency = Math.round(average(frequencies));
1075
- const mergedSeverity = maxSeverity(severities);
1076
- const mergedExamples = limitExamples(
1077
- allExamples,
1078
- MAX_EXAMPLES_PER_PATTERN
1079
- );
1080
- mergedPatterns.push({
1081
- ...firstPattern,
1082
- frequency: mergedFrequency,
1083
- severity: mergedSeverity,
1084
- examples: mergedExamples
1085
- });
1086
- }
1087
- }
1088
- const sortedPatterns = mergedPatterns.sort((a, b) => {
1089
- const severityDiff = SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity];
1090
- if (severityDiff !== 0) return severityDiff;
1091
- return b.frequency - a.frequency;
1092
- });
1093
- const topPatterns = sortedPatterns.slice(0, MAX_PATTERNS);
1094
- const totalPrompts = sum(results.map((r) => r.stats.totalPrompts));
1095
- const promptsWithIssues = sum(results.map((r) => r.stats.promptsWithIssues));
1096
- const avgScore = Math.round(
1097
- average(results.map((r) => r.stats.overallScore))
1098
- );
1099
- const topSuggestion = topPatterns.length > 0 && topPatterns[0] ? topPatterns[0].suggestion : results[0]?.topSuggestion ?? "No suggestions available";
1100
- return {
1101
- date,
1102
- patterns: topPatterns,
1103
- stats: {
1104
- totalPrompts,
1105
- promptsWithIssues,
1106
- overallScore: avgScore
1107
- },
1108
- topSuggestion
1109
- };
1110
- }
1111
- function applyRulesToResult(result, rules) {
1112
- if (!rules || Object.keys(rules).length === 0) {
1113
- return result;
1114
- }
1115
- const customTaxonomy = applyRulesConfig(rules, ISSUE_TAXONOMY);
1116
- const enabledPatternIds = Object.keys(customTaxonomy);
1117
- const filteredPatterns = result.patterns.filter(
1118
- (pattern) => enabledPatternIds.includes(pattern.id)
1119
- );
1120
- const updatedPatterns = filteredPatterns.map((pattern) => {
1121
- const ruleConfig = rules[pattern.id];
1122
- if (ruleConfig?.severity) {
1123
- return {
1124
- ...pattern,
1125
- severity: ruleConfig.severity
1126
- };
1127
- }
1128
- return pattern;
1129
- });
1130
- const topSuggestion = updatedPatterns.length > 0 && updatedPatterns[0] ? updatedPatterns[0].suggestion : result.topSuggestion;
1131
- return {
1132
- ...result,
1133
- patterns: updatedPatterns,
1134
- topSuggestion
1135
- };
1136
- }
1137
- function mergeWithCachedResults(newResults, cachedResults, date, rules) {
1138
- if (!cachedResults || cachedResults.size === 0) {
1139
- if (newResults.length === 1) {
1140
- const result = newResults[0];
1141
- if (result) {
1142
- return applyRulesToResult(result, rules);
1143
- }
1144
- }
1145
- const mergedResult2 = mergeBatchResults({ results: newResults, date });
1146
- return applyRulesToResult(mergedResult2, rules);
1147
- }
1148
- const cachedArray = Array.from(cachedResults.values());
1149
- const allResults = [...cachedArray, ...newResults];
1150
- logger.debug(
1151
- `Merging ${String(cachedArray.length)} cached + ${String(newResults.length)} new results`,
1152
- "analyzer"
1153
- );
1154
- const mergedResult = mergeBatchResults({ results: allResults, date });
1155
- return applyRulesToResult(mergedResult, rules);
1156
- }
1157
- async function analyzePrompts(options) {
1158
- const {
1159
- provider,
1160
- prompts,
1161
- date,
1162
- context,
1163
- rules,
1164
- onProgress,
1165
- noCache,
1166
- cachedResults
1167
- } = options;
1168
- logger.debug(
1169
- `Starting analysis of ${String(prompts.length)} prompts for ${date}`,
1170
- "analyzer"
1171
- );
1172
- if (prompts.length === 0 && cachedResults && cachedResults.size > 0) {
1173
- logger.debug(
1174
- `Using ${String(cachedResults.size)} cached result(s), no new prompts to analyze`,
1175
- "analyzer"
1176
- );
1177
- const cachedArray = Array.from(cachedResults.values());
1178
- const mergedResult = mergeBatchResults({ results: cachedArray, date });
1179
- return applyRulesToResult(mergedResult, rules);
1180
- }
1181
- if (prompts.length === 0) {
1182
- throw new Error("Cannot analyze empty prompts array");
1183
- }
1184
- if (cachedResults && cachedResults.size > 0) {
1185
- const totalPrompts = prompts.length + cachedResults.size;
1186
- const cacheHitRate = (cachedResults.size / totalPrompts * 100).toFixed(1);
1187
- logger.debug(
1188
- `Results cache: ${String(cachedResults.size)} cached, ${String(prompts.length)} to analyze (${cacheHitRate}% hit rate)`,
1189
- "analyzer"
1190
- );
1191
- }
1192
- const { prompts: sanitizedPrompts, totalRedacted } = sanitizePrompts(prompts);
1193
- if (totalRedacted > 0) {
1194
- logger.debug(
1195
- `Sanitizer redacted ${String(totalRedacted)} secrets`,
1196
- "analyzer"
1197
- );
1198
- }
1199
- const limits = hasDynamicLimits(provider) ? provider.getBatchLimits() : PROVIDER_LIMITS[inferProviderType(provider.name)];
1200
- const limitsInfo = limits.maxPromptsPerBatch ? `${String(limits.maxTokensPerBatch)} tokens/batch, max ${String(limits.maxPromptsPerBatch)} prompts/batch` : `${String(limits.maxTokensPerBatch)} tokens/batch`;
1201
- logger.debug(`Using batch limits: ${limitsInfo}`, "analyzer");
1202
- const batches = batchPrompts({
1203
- prompts: sanitizedPrompts,
1204
- maxTokensPerBatch: limits.maxTokensPerBatch,
1205
- maxPromptsPerBatch: limits.maxPromptsPerBatch,
1206
- prioritization: limits.prioritization
1207
- });
1208
- logger.debug(
1209
- `Created ${String(batches.length)} batch(es) for analysis`,
1210
- "analyzer"
1211
- );
1212
- if (batches.length === 1) {
1213
- const batch = batches[0];
1214
- if (!batch) {
1215
- throw new Error("Failed to create batches");
1216
- }
1217
- if (onProgress) {
1218
- onProgress(0, 1);
1219
- }
1220
- const model2 = extractModelFromProvider(provider.name);
1221
- logger.debug(
1222
- `Processing single batch (${String(batch.tokens)} tokens, ${String(batch.prompts.length)} prompts)`,
1223
- "analyzer"
1224
- );
1225
- const startTime = Date.now();
1226
- const results2 = await analyzeWithFallback(
1227
- provider,
1228
- batch.prompts,
1229
- date,
1230
- context,
1231
- model2,
1232
- noCache ?? false
1233
- );
1234
- const elapsed = Date.now() - startTime;
1235
- logger.debug(`Batch completed in ${String(elapsed)}ms`, "analyzer");
1236
- if (onProgress) {
1237
- onProgress(1, 1);
1238
- }
1239
- if (results2.length === 0) {
1240
- throw new Error("All prompts failed analysis");
1241
- }
1242
- logger.debug(`Analysis complete, merging with cached results`, "analyzer");
1243
- return mergeWithCachedResults(results2, cachedResults, date, rules);
1244
- }
1245
- const results = [];
1246
- const totalBatches = batches.length;
1247
- const model = extractModelFromProvider(provider.name);
1248
- for (let i = 0; i < batches.length; i++) {
1249
- const batch = batches[i];
1250
- if (!batch) continue;
1251
- if (onProgress) {
1252
- onProgress(i, totalBatches);
1253
- }
1254
- logger.debug(
1255
- `Processing batch ${String(i + 1)}/${String(totalBatches)} (${String(batch.tokens)} tokens, ${String(batch.prompts.length)} prompts)`,
1256
- "analyzer"
1257
- );
1258
- const startTime = Date.now();
1259
- const batchResults = await analyzeWithFallback(
1260
- provider,
1261
- batch.prompts,
1262
- date,
1263
- context,
1264
- model,
1265
- noCache ?? false
1266
- );
1267
- results.push(...batchResults);
1268
- const elapsed = Date.now() - startTime;
1269
- logger.debug(
1270
- `Batch ${String(i + 1)}/${String(totalBatches)} completed in ${String(elapsed)}ms (${String(batchResults.length)} result(s))`,
1271
- "analyzer"
1272
- );
1273
- }
1274
- if (onProgress) {
1275
- onProgress(totalBatches, totalBatches);
1276
- }
1277
- if (results.length === 0) {
1278
- throw new Error("All batches failed analysis");
1279
- }
1280
- logger.debug(
1281
- `Analysis complete, merging ${String(results.length)} batch results with cached results`,
1282
- "analyzer"
1283
- );
1284
- return mergeWithCachedResults(results, cachedResults, date, rules);
1285
- }
1286
-
1287
- // src/core/schema-validator.ts
1288
- var SUPPORTED_VERSIONS = ["1.0"];
1289
- var CURRENT_VERSION = {
1290
- major: 1,
1291
- minor: 0,
1292
- detected: "1.0"
1293
- };
1294
- var V1_0_REQUIRED_FIELDS = [
1295
- "type",
1296
- "message",
1297
- "timestamp",
1298
- "sessionId",
1299
- "cwd"
1300
- ];
1301
- var V1_0_MESSAGE_FIELDS = ["role", "content"];
1302
- var V1_0_MESSAGE_TYPES = ["user", "assistant", "system"];
1303
- function isObject(value) {
1304
- return typeof value === "object" && value !== null && !Array.isArray(value);
1305
- }
1306
- function hasRequiredFields(obj, fields) {
1307
- return fields.every((field) => field in obj);
1308
- }
1309
- function isValidV1Message(message) {
1310
- if (!isObject(message)) {
1311
- return false;
1312
- }
1313
- if (!hasRequiredFields(message, V1_0_MESSAGE_FIELDS)) {
1314
- return false;
1315
- }
1316
- const role = message["role"];
1317
- if (typeof role !== "string" || !V1_0_MESSAGE_TYPES.includes(role)) {
1318
- return false;
1319
- }
1320
- const content = message["content"];
1321
- if (typeof content !== "string") {
1322
- return false;
1323
- }
1324
- return true;
1325
- }
1326
- function isValidV1Type(type) {
1327
- return typeof type === "string" && V1_0_MESSAGE_TYPES.includes(type);
1328
- }
1329
- function detectSchemaVersion(entry) {
1330
- if (!isObject(entry)) {
1331
- return null;
1332
- }
1333
- if (!hasRequiredFields(entry, V1_0_REQUIRED_FIELDS)) {
1334
- return null;
1335
- }
1336
- if (!isValidV1Type(entry["type"])) {
1337
- return null;
1338
- }
1339
- if (!isValidV1Message(entry["message"])) {
1340
- return null;
1341
- }
1342
- if (typeof entry["timestamp"] !== "string") {
1343
- return null;
1344
- }
1345
- if (typeof entry["sessionId"] !== "string") {
1346
- return null;
1347
- }
1348
- if (typeof entry["cwd"] !== "string") {
1349
- return null;
1350
- }
1351
- return CURRENT_VERSION;
1352
- }
1353
- function isSchemaSupported(version) {
1354
- return SUPPORTED_VERSIONS.includes(version.detected);
1355
- }
1356
- function getSchemaWarning(version, context) {
1357
- const contextSuffix = "";
1358
- if (version === null) {
1359
- return `Unknown log format detected${contextSuffix}. The log entry structure does not match any known Claude Code schema. This entry will be skipped.`;
1360
- }
1361
- if (!isSchemaSupported(version)) {
1362
- return `Unsupported schema version ${version.detected}${contextSuffix}. Supported versions: ${SUPPORTED_VERSIONS.join(", ")}. This entry may not be processed correctly.`;
1363
- }
1364
- return "";
1365
- }
1366
- function validateLogEntry(entry) {
1367
- const version = detectSchemaVersion(entry);
1368
- if (version === null) {
1369
- return {
1370
- isValid: false,
1371
- version: null,
1372
- warning: getSchemaWarning(null)
1373
- };
1374
- }
1375
- if (!isSchemaSupported(version)) {
1376
- return {
1377
- isValid: false,
1378
- version,
1379
- warning: getSchemaWarning(version)
1380
- };
1381
- }
1382
- return {
1383
- isValid: true,
1384
- version,
1385
- warning: null
1386
- };
1387
- }
1388
-
1389
- // src/core/log-reader.ts
1390
- function claudeProjectsExist() {
1391
- return existsSync(CLAUDE_PROJECTS_DIR);
1392
- }
1393
- function extractProjectName(filePath) {
1394
- const parts = filePath.split("/");
1395
- const projectIndex = parts.findIndex((p) => p === "projects");
1396
- const projectHash = parts[projectIndex + 1];
1397
- if (projectIndex !== -1 && projectHash !== void 0) {
1398
- return projectHash;
1399
- }
1400
- return basename(filePath, ".jsonl");
1401
- }
1402
- function parseDate(dateStr) {
1403
- const normalized = dateStr.trim().toLowerCase();
1404
- if (normalized === "today") {
1405
- return startOfDay(/* @__PURE__ */ new Date());
1406
- }
1407
- if (normalized === "yesterday") {
1408
- const yesterday = /* @__PURE__ */ new Date();
1409
- yesterday.setDate(yesterday.getDate() - 1);
1410
- return startOfDay(yesterday);
1411
- }
1412
- try {
1413
- const parsed = parseISO(dateStr);
1414
- if (isNaN(parsed.getTime())) {
1415
- throw new Error(`Invalid date format: ${dateStr}`);
1416
- }
1417
- return startOfDay(parsed);
1418
- } catch {
1419
- throw new Error(
1420
- `Invalid date format: ${dateStr}. Expected 'today', 'yesterday', or YYYY-MM-DD`
1421
- );
1422
- }
1423
- }
1424
- function extractDate(timestamp) {
1425
- try {
1426
- const date = parseISO(timestamp);
1427
- const dateStr = date.toISOString().split("T")[0];
1428
- return dateStr ?? "unknown";
1429
- } catch {
1430
- return "unknown";
1431
- }
1432
- }
1433
- function isClaudeMessage(value) {
1434
- if (typeof value !== "object" || value === null) {
1435
- return false;
1436
- }
1437
- const obj = value;
1438
- return typeof obj["timestamp"] === "string" && typeof obj["type"] === "string" && typeof obj["message"] === "object" && obj["message"] !== null && typeof obj["message"]["content"] === "string";
1439
- }
1440
- function parseLine(line, lineNumber, filePath) {
1441
- if (!line.trim()) {
1442
- return null;
1443
- }
1444
- const context = lineNumber !== void 0 && filePath ? `${filePath}:${String(lineNumber)}` : void 0;
1445
- try {
1446
- const parsed = JSON.parse(line);
1447
- const validation = validateLogEntry(parsed);
1448
- if (!validation.isValid) {
1449
- logger.debug(
1450
- `Schema validation failed: ${validation.warning ?? "Unknown format"}`,
1451
- context
1452
- );
1453
- return null;
1454
- }
1455
- if (!isClaudeMessage(parsed)) {
1456
- logger.debug("Type guard validation failed", context);
1457
- return null;
1458
- }
1459
- return parsed;
1460
- } catch (error) {
1461
- const errorMessage = error instanceof Error ? error.message : "Parse error";
1462
- logger.debug(`JSON parse failed: ${errorMessage}`, context);
1463
- return null;
1464
- }
1465
- }
1466
- function isUserMessage(message) {
1467
- return message.type === "user" && message.message.role === "user";
1468
- }
1469
- function extractContent(message) {
1470
- return message.message.content;
1471
- }
1472
- async function readJsonlFile(filePath) {
1473
- const prompts = [];
1474
- const warnings = [];
1475
- const projectName = extractProjectName(filePath);
1476
- try {
1477
- const content = await readFile(filePath, "utf-8");
1478
- const lines = content.split("\n");
1479
- let skippedLines = 0;
1480
- for (let i = 0; i < lines.length; i++) {
1481
- const line = lines[i] ?? "";
1482
- const lineNumber = i + 1;
1483
- const message = parseLine(line, lineNumber, filePath);
1484
- if (message === null) {
1485
- if (line.trim()) {
1486
- skippedLines++;
1487
- }
1488
- continue;
1489
- }
1490
- if (!isUserMessage(message)) {
1491
- continue;
1492
- }
1493
- const extractedContent = extractContent(message);
1494
- if (!extractedContent.trim()) {
1495
- continue;
1496
- }
1497
- prompts.push({
1498
- content: extractedContent,
1499
- timestamp: message.timestamp,
1500
- sessionId: message.sessionId,
1501
- project: projectName,
1502
- date: extractDate(message.timestamp)
1503
- });
1504
- }
1505
- if (skippedLines > 0) {
1506
- const warning = `Skipped ${String(skippedLines)} invalid line(s) in ${filePath}`;
1507
- warnings.push(warning);
1508
- logger.collectWarning(warning, "log-reader");
1509
- }
1510
- } catch (error) {
1511
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1512
- const warning = `Failed to read ${filePath}: ${errorMessage}`;
1513
- warnings.push(warning);
1514
- logger.error(warning, "log-reader");
1515
- }
1516
- return { prompts, warnings };
1517
- }
1518
- function filterByDateRange(prompts, fromDate, toDate) {
1519
- return prompts.filter((prompt) => {
1520
- try {
1521
- const promptDate = parseISO(prompt.timestamp);
1522
- const promptDay = startOfDay(promptDate);
1523
- return (isSameDay(promptDay, fromDate) || isAfter(promptDay, fromDate)) && (isSameDay(promptDay, toDate) || isBefore(promptDay, toDate));
1524
- } catch (error) {
1525
- const errorMessage = error instanceof Error ? error.message : "Parse error";
1526
- logger.debug(
1527
- `Invalid timestamp in filterByDateRange: ${prompt.timestamp} - ${errorMessage}`,
1528
- "log-reader"
1529
- );
1530
- return false;
1531
- }
1532
- });
1533
- }
1534
- function filterByDate(prompts, targetDate) {
1535
- return prompts.filter((prompt) => {
1536
- try {
1537
- const promptDate = parseISO(prompt.timestamp);
1538
- return isSameDay(startOfDay(promptDate), targetDate);
1539
- } catch (error) {
1540
- const errorMessage = error instanceof Error ? error.message : "Parse error";
1541
- logger.debug(
1542
- `Invalid timestamp in filterByDate: ${prompt.timestamp} - ${errorMessage}`,
1543
- "log-reader"
1544
- );
1545
- return false;
1546
- }
1547
- });
1548
- }
1549
- function filterByProject(prompts, projectName) {
1550
- const normalizedProject = projectName.toLowerCase().trim();
1551
- return prompts.filter(
1552
- (prompt) => prompt.project.toLowerCase().includes(normalizedProject)
1553
- );
1554
- }
1555
- function groupByDay(prompts) {
1556
- const groups = /* @__PURE__ */ new Map();
1557
- for (const prompt of prompts) {
1558
- const date = prompt.date;
1559
- if (!groups.has(date)) {
1560
- groups.set(date, { prompts: [], projects: /* @__PURE__ */ new Set() });
1561
- }
1562
- const group = groups.get(date);
1563
- if (group) {
1564
- group.prompts.push(prompt);
1565
- group.projects.add(prompt.project);
1566
- }
1567
- }
1568
- const result = Array.from(groups.entries()).map(([date, { prompts: groupPrompts, projects }]) => {
1569
- const sortedPrompts = groupPrompts.sort((a, b) => {
1570
- try {
1571
- const dateA = parseISO(a.timestamp);
1572
- const dateB = parseISO(b.timestamp);
1573
- return dateA.getTime() - dateB.getTime();
1574
- } catch (error) {
1575
- const errorMessage = error instanceof Error ? error.message : "Parse error";
1576
- logger.debug(
1577
- `Invalid timestamp in groupByDay sort: ${a.timestamp} or ${b.timestamp} - ${errorMessage}`,
1578
- "log-reader"
1579
- );
1580
- return 0;
1581
- }
1582
- });
1583
- return {
1584
- date,
1585
- prompts: sortedPrompts,
1586
- projects: Array.from(projects).sort()
1587
- };
1588
- }).sort((a, b) => {
1589
- try {
1590
- const dateA = parseISO(a.date + "T00:00:00Z");
1591
- const dateB = parseISO(b.date + "T00:00:00Z");
1592
- return dateA.getTime() - dateB.getTime();
1593
- } catch (error) {
1594
- const errorMessage = error instanceof Error ? error.message : "Parse error";
1595
- logger.debug(
1596
- `Invalid date in groupByDay sort: ${a.date} or ${b.date} - ${errorMessage}`,
1597
- "log-reader"
1598
- );
1599
- return 0;
1600
- }
1601
- });
1602
- return result;
1603
- }
1604
- async function readLogs(options) {
1605
- logger.debug(`Scanning ${CLAUDE_PROJECTS_DIR}`, "log-reader");
1606
- if (!claudeProjectsExist()) {
1607
- logger.debug("Claude projects directory not found", "log-reader");
1608
- return {
1609
- prompts: [],
1610
- warnings: [
1611
- `Claude projects directory not found at ${CLAUDE_PROJECTS_DIR}`
1612
- ]
1613
- };
1614
- }
1615
- const pattern = `${CLAUDE_PROJECTS_DIR}/**/*.jsonl`;
1616
- let files;
1617
- try {
1618
- files = await glob(pattern);
1619
- } catch (error) {
1620
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1621
- const warning = `Failed to search for JSONL files: ${errorMessage}`;
1622
- logger.error(warning, "log-reader");
1623
- return {
1624
- prompts: [],
1625
- warnings: [warning]
1626
- };
1627
- }
1628
- logger.debug(`Found ${String(files.length)} JSONL files`, "log-reader");
1629
- if (files.length === 0) {
1630
- return {
1631
- prompts: [],
1632
- warnings: ["No JSONL files found in Claude projects directory"]
1633
- };
1634
- }
1635
- const allPrompts = [];
1636
- const allWarnings = [];
1637
- const CONCURRENCY_LIMIT = 10;
1638
- for (let i = 0; i < files.length; i += CONCURRENCY_LIMIT) {
1639
- const chunk = files.slice(i, i + CONCURRENCY_LIMIT);
1640
- const results = await Promise.all(chunk.map(readJsonlFile));
1641
- for (const { prompts, warnings } of results) {
1642
- allPrompts.push(...prompts);
1643
- allWarnings.push(...warnings);
1644
- }
1645
- }
1646
- logger.debug(
1647
- `Parsed ${String(allPrompts.length)} total prompts from all files`,
1648
- "log-reader"
1649
- );
1650
- let filteredPrompts = allPrompts;
1651
- if (options) {
1652
- if (options.from && options.to) {
1653
- try {
1654
- const fromDate = parseDate(options.from);
1655
- const toDate = parseDate(options.to);
1656
- if (isAfter(fromDate, toDate)) {
1657
- return {
1658
- prompts: [],
1659
- warnings: [
1660
- ...allWarnings,
1661
- `Invalid date range: --from (${options.from}) must be before or equal to --to (${options.to})`
1662
- ]
1663
- };
1664
- }
1665
- filteredPrompts = filterByDateRange(filteredPrompts, fromDate, toDate);
1666
- } catch (error) {
1667
- const errorMessage = error instanceof Error ? error.message : "Invalid date range";
1668
- return {
1669
- prompts: [],
1670
- warnings: [...allWarnings, errorMessage]
1671
- };
1672
- }
1673
- } else if (options.date) {
1674
- try {
1675
- const targetDate = parseDate(options.date);
1676
- filteredPrompts = filterByDate(filteredPrompts, targetDate);
1677
- } catch (error) {
1678
- const errorMessage = error instanceof Error ? error.message : "Invalid date";
1679
- return {
1680
- prompts: [],
1681
- warnings: [...allWarnings, errorMessage]
1682
- };
1683
- }
1684
- }
1685
- if (options.project) {
1686
- filteredPrompts = filterByProject(filteredPrompts, options.project);
1687
- }
1688
- }
1689
- if (options) {
1690
- const filtered = allPrompts.length - filteredPrompts.length;
1691
- if (filtered > 0) {
1692
- logger.debug(
1693
- `Filtered ${String(filtered)} prompts (${String(filteredPrompts.length)} remaining)`,
1694
- "log-reader"
1695
- );
1696
- }
1697
- }
1698
- const sortedPrompts = filteredPrompts.sort((a, b) => {
1699
- try {
1700
- const dateA = parseISO(a.timestamp);
1701
- const dateB = parseISO(b.timestamp);
1702
- return dateA.getTime() - dateB.getTime();
1703
- } catch (error) {
1704
- const errorMessage = error instanceof Error ? error.message : "Parse error";
1705
- logger.debug(
1706
- `Invalid timestamp in readLogs sort: ${a.timestamp} or ${b.timestamp} - ${errorMessage}`,
1707
- "log-reader"
1708
- );
1709
- return 0;
1710
- }
1711
- });
1712
- logger.debug(
1713
- `Returning ${String(sortedPrompts.length)} prompts for analysis`,
1714
- "log-reader"
1715
- );
1716
- return {
1717
- prompts: sortedPrompts,
1718
- warnings: allWarnings
1719
- };
1720
- }
1721
- function getHistoryDir() {
1722
- return HYNTX_HISTORY_DIR;
1723
- }
1724
- async function ensureHistoryDir() {
1725
- try {
1726
- await mkdir(HYNTX_HISTORY_DIR, { recursive: true, mode: 448 });
1727
- } catch (error) {
1728
- const errorMessage = error instanceof Error ? error.message : String(error);
1729
- throw new Error(
1730
- `Failed to create history directory ${HYNTX_HISTORY_DIR}: ${errorMessage}`
1731
- );
1732
- }
1733
- }
1734
- function getHistoryFilePath(date) {
1735
- return join(HYNTX_HISTORY_DIR, `${date}.json`);
1736
- }
1737
- async function saveAnalysisResult(result, metadata) {
1738
- try {
1739
- await ensureHistoryDir();
1740
- const sanitizedResult = {
1741
- ...result,
1742
- patterns: result.patterns.map((pattern) => ({
1743
- ...pattern,
1744
- examples: pattern.examples.map((example) => sanitize(example).text)
1745
- }))
1746
- };
1747
- const entry = {
1748
- result: sanitizedResult,
1749
- metadata
1750
- };
1751
- const filePath = getHistoryFilePath(result.date);
1752
- const content = JSON.stringify(entry, null, 2);
1753
- const tmpFile = `${filePath}.tmp`;
1754
- await writeFile(tmpFile, content, "utf-8");
1755
- await rename(tmpFile, filePath);
1756
- logger.debug(`Saved history to ${filePath}`, "history");
1757
- } catch (error) {
1758
- const errorMessage = error instanceof Error ? error.message : String(error);
1759
- logger.warn(
1760
- `Failed to save analysis to history: ${errorMessage}`,
1761
- "history"
1762
- );
1763
- }
1764
- }
1765
- async function loadAnalysisResult(date) {
1766
- const filePath = getHistoryFilePath(date);
1767
- if (!existsSync(filePath)) {
1768
- return null;
1769
- }
1770
- try {
1771
- const content = await readFile(filePath, "utf-8");
1772
- const entry = JSON.parse(content);
1773
- if (entry.result === void 0 || entry.metadata === void 0) {
1774
- logger.warn(`Invalid history entry in ${filePath}`, "history");
1775
- return null;
1776
- }
1777
- return entry;
1778
- } catch (error) {
1779
- const errorMessage = error instanceof Error ? error.message : String(error);
1780
- logger.warn(
1781
- `Failed to load history from ${filePath}: ${errorMessage}`,
1782
- "history"
1783
- );
1784
- return null;
1785
- }
1786
- }
1787
- async function listAvailableDates(options) {
1788
- if (!existsSync(HYNTX_HISTORY_DIR)) {
1789
- return [];
1790
- }
1791
- try {
1792
- const files = readdirSync(HYNTX_HISTORY_DIR);
1793
- const dates = [];
1794
- for (const file of files) {
1795
- if (!file.endsWith(".json")) {
1796
- continue;
1797
- }
1798
- const date = file.slice(0, -5);
1799
- if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
1800
- continue;
1801
- }
1802
- if (options) {
1803
- const entry = await loadAnalysisResult(date);
1804
- if (!entry) {
1805
- continue;
1806
- }
1807
- if (options.provider && entry.metadata.provider !== options.provider) {
1808
- continue;
1809
- }
1810
- const projectFilter = options.project;
1811
- if (projectFilter && !entry.metadata.projects.some(
1812
- (p) => p.toLowerCase().includes(projectFilter.toLowerCase())
1813
- )) {
1814
- continue;
1815
- }
1816
- const score = entry.result.stats.overallScore;
1817
- if (options.minScore !== void 0 && score < options.minScore) {
1818
- continue;
1819
- }
1820
- if (options.maxScore !== void 0 && score > options.maxScore) {
1821
- continue;
1822
- }
1823
- }
1824
- dates.push(date);
1825
- }
1826
- return dates.sort((a, b) => b.localeCompare(a));
1827
- } catch (error) {
1828
- const errorMessage = error instanceof Error ? error.message : String(error);
1829
- logger.warn(`Failed to list history dates: ${errorMessage}`, "history");
1830
- return [];
1831
- }
1832
- }
1833
- function compareResults(before, after) {
1834
- const scoreDelta = after.stats.overallScore - before.stats.overallScore;
1835
- const beforePatterns = new Map(before.patterns.map((p) => [p.id, p]));
1836
- const afterPatterns = new Map(after.patterns.map((p) => [p.id, p]));
1837
- const newPatterns = [];
1838
- for (const pattern of after.patterns) {
1839
- if (!beforePatterns.has(pattern.id)) {
1840
- newPatterns.push(pattern);
1841
- }
1842
- }
1843
- const resolvedPatterns = [];
1844
- for (const pattern of before.patterns) {
1845
- if (!afterPatterns.has(pattern.id)) {
1846
- resolvedPatterns.push(pattern);
1847
- }
1848
- }
1849
- const changedPatterns = [];
1850
- for (const [id, beforePattern] of beforePatterns) {
1851
- const afterPattern = afterPatterns.get(id);
1852
- if (!afterPattern) {
1853
- continue;
1854
- }
1855
- const frequencyChanged = beforePattern.frequency !== afterPattern.frequency;
1856
- const severityChanged = beforePattern.severity !== afterPattern.severity;
1857
- if (frequencyChanged || severityChanged) {
1858
- changedPatterns.push({
1859
- id,
1860
- name: beforePattern.name,
1861
- status: "changed",
1862
- frequencyBefore: beforePattern.frequency,
1863
- frequencyAfter: afterPattern.frequency,
1864
- severityBefore: beforePattern.severity,
1865
- severityAfter: afterPattern.severity
1866
- });
1867
- }
1868
- }
1869
- const changes = {
1870
- scoreDelta,
1871
- newPatterns,
1872
- resolvedPatterns,
1873
- changedPatterns
1874
- };
1875
- return {
1876
- before,
1877
- after,
1878
- changes
1879
- };
1880
- }
1881
- function getDateOneWeekAgo(fromDate) {
1882
- const date = typeof fromDate === "string" ? parseISO(fromDate) : fromDate;
1883
- const weekAgo = subDays(date, 7);
1884
- return format(weekAgo, "yyyy-MM-dd");
1885
- }
1886
- function getDateOneMonthAgo(fromDate) {
1887
- const date = typeof fromDate === "string" ? parseISO(fromDate) : fromDate;
1888
- const monthAgo = subMonths(date, 1);
1889
- return format(monthAgo, "yyyy-MM-dd");
1890
- }
1891
-
1892
- // src/core/aggregator.ts
1893
- function normalizeScore(score100) {
1894
- const normalized = score100 / 10;
1895
- return Math.max(0, Math.min(10, normalized));
1896
- }
1897
- function lookupIssueMetadata(issueId, taxonomy) {
1898
- if (taxonomy[issueId]) {
1899
- return taxonomy[issueId];
1900
- }
1901
- return {
1902
- name: titleCase(issueId),
1903
- severity: "medium",
1904
- suggestion: "Review this pattern"
1905
- };
1906
- }
1907
- function titleCase(str) {
1908
- return str.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
1909
- }
1910
- function extractRealExamples(issueId, prompts, limit = 3) {
1911
- const matches = [];
1912
- for (const prompt of prompts) {
1913
- if (matches.length >= limit) {
1914
- break;
1915
- }
1916
- const trimmed = prompt.trim();
1917
- const lowerPrompt = trimmed.toLowerCase();
1918
- const wordCount = trimmed.split(/\s+/).length;
1919
- let isMatch = false;
1920
- switch (issueId) {
1921
- case "vague":
1922
- isMatch = trimmed.length < 50 && wordCount <= 5 && (lowerPrompt.includes("help") || lowerPrompt.includes("fix") || lowerPrompt.includes("do") || lowerPrompt.includes("make") || lowerPrompt.includes("create")) && /\w+\.(ts|js|tsx|jsx|py|go|java|rb|php)\b/.exec(lowerPrompt) === null;
1923
- break;
1924
- case "no-context":
1925
- isMatch = (lowerPrompt.includes("this") || lowerPrompt.includes("it") || lowerPrompt.includes("the bug") || lowerPrompt.includes("that")) && /\w+\.(ts|js|tsx|jsx|py|go|java|rb|php)\b/.exec(lowerPrompt) === null && /function|component|method|class/.exec(lowerPrompt) === null;
1926
- break;
1927
- case "too-broad": {
1928
- const andMatches = lowerPrompt.match(/\band\b/g);
1929
- isMatch = trimmed.length > 100 && (andMatches?.length ?? 0) >= 2 && (lowerPrompt.includes("also") || lowerPrompt.includes("then") || lowerPrompt.includes("build") || lowerPrompt.includes("create"));
1930
- break;
1931
- }
1932
- case "no-goal":
1933
- isMatch = trimmed.length < 30 && wordCount <= 4 && /\b(how|what|why|when|where|create|build|fix|add)\b/.exec(
1934
- lowerPrompt
1935
- ) === null && !lowerPrompt.includes("?");
1936
- break;
1937
- case "imperative":
1938
- isMatch = trimmed.length < 20 && wordCount <= 3 && /^(add|delete|remove|update|change|modify)\b/.exec(lowerPrompt) !== null && !lowerPrompt.includes("?");
1939
- break;
1940
- case "missing-technical-details": {
1941
- const hasFileRef = /\w+\.(ts|js|tsx|jsx|py|go|java|rb|php|json|yaml|yml)\b/.exec(
1942
- lowerPrompt
1943
- ) !== null;
1944
- const hasFunctionRef = /function|def |class |const |let |var |(\.\w+\()/.exec(
1945
- lowerPrompt
1946
- ) !== null;
1947
- const hasErrorRef = /error|exception|failed|crash|undefined|null/.exec(lowerPrompt) !== null;
1948
- isMatch = !hasFileRef && !hasFunctionRef && !hasErrorRef && wordCount >= 3;
1949
- break;
1950
- }
1951
- case "unclear-priorities": {
1952
- const andMatches = lowerPrompt.match(/\band\b/g);
1953
- const orMatches = lowerPrompt.match(/\bor\b/g);
1954
- const alsoMatches = lowerPrompt.match(/\balso\b/g);
1955
- const conjunctionCount = (andMatches?.length ?? 0) + (orMatches?.length ?? 0) + (alsoMatches?.length ?? 0);
1956
- isMatch = conjunctionCount >= 2 && !/\b(first|second|third|then|next|finally|after|before)\b/.exec(
1957
- lowerPrompt
1958
- ) && wordCount >= 10;
1959
- break;
1960
- }
1961
- case "insufficient-constraints":
1962
- isMatch = !/\b(constraint|requirement|must|should|edge case|boundary|limit|performance|compatib)\b/.exec(
1963
- lowerPrompt
1964
- ) && !/\b(<|>|<=|>=|\d+ms|\d+mb|\d+kb)\b/.exec(lowerPrompt) && (lowerPrompt.includes("optimize") || lowerPrompt.includes("improve") || lowerPrompt.includes("make") || lowerPrompt.includes("add")) && wordCount >= 4;
1965
- break;
1966
- default:
1967
- isMatch = false;
1968
- }
1969
- if (isMatch) {
1970
- matches.push(sanitizeExample(trimmed));
1971
- }
1972
- }
1973
- return [...new Set(matches)];
1974
- }
1975
- function sanitizeExample(prompt) {
1976
- const trimmed = prompt.trim().replace(/\s+/g, " ");
1977
- if (trimmed.length <= 80) {
1978
- return trimmed;
1979
- }
1980
- return trimmed.slice(0, 77) + "...";
1981
- }
1982
- function convertMinimalToAnalysisResult(minimal, date, taxonomy, prompts) {
1983
- const issueCounts = /* @__PURE__ */ new Map();
1984
- for (const issue of minimal.issues) {
1985
- issueCounts.set(issue, (issueCounts.get(issue) ?? 0) + 1);
1986
- }
1987
- const patterns = [...issueCounts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([issueId, count]) => {
1988
- const metadata = lookupIssueMetadata(issueId, taxonomy);
1989
- const examples = prompts ? extractRealExamples(issueId, prompts, 3) : metadata.exampleBefore ? [metadata.exampleBefore] : [];
1990
- return {
1991
- id: issueId,
1992
- name: metadata.name,
1993
- frequency: count,
1994
- severity: metadata.severity,
1995
- examples: [...examples],
1996
- suggestion: metadata.suggestion,
1997
- beforeAfter: {
1998
- before: metadata.exampleBefore ?? "Example not available",
1999
- after: metadata.exampleAfter ?? metadata.suggestion
2000
- }
2001
- };
2002
- });
2003
- return {
2004
- date,
2005
- patterns,
2006
- stats: {
2007
- totalPrompts: 1,
2008
- promptsWithIssues: minimal.issues.length > 0 ? 1 : 0,
2009
- overallScore: normalizeScore(minimal.score)
2010
- },
2011
- topSuggestion: patterns.length > 0 && patterns[0] ? patterns[0].suggestion : "Your prompts look good!"
2012
- };
2013
- }
2014
-
2015
- // src/providers/base.ts
2016
- function buildUserPrompt(prompts, date, context) {
2017
- if (prompts.length === 0) {
2018
- throw new Error("Cannot build prompt from empty array");
2019
- }
2020
- const promptsList = prompts.map((prompt, index) => `${String(index + 1)}. ${prompt}`).join("\n\n");
2021
- const count = String(prompts.length);
2022
- const plural = prompts.length === 1 ? "" : "s";
2023
- let contextSection = "";
2024
- if (context) {
2025
- const contextParts = [];
2026
- if (context.role) {
2027
- contextParts.push(`Role: ${context.role}`);
2028
- }
2029
- if (context.projectType) {
2030
- contextParts.push(`Project Type: ${context.projectType}`);
2031
- }
2032
- if (context.domain) {
2033
- contextParts.push(`Domain: ${context.domain}`);
2034
- }
2035
- if (context.techStack && context.techStack.length > 0) {
2036
- contextParts.push(`Tech Stack: ${context.techStack.join(", ")}`);
2037
- }
2038
- if (context.guidelines && context.guidelines.length > 0) {
2039
- contextParts.push(
2040
- `Guidelines:
2041
- ${context.guidelines.map((g) => `- ${g}`).join("\n")}`
2042
- );
2043
- }
2044
- if (contextParts.length > 0) {
2045
- contextSection = `
2046
-
2047
- Project Context:
2048
- ${contextParts.join("\n")}
2049
- `;
2050
- }
2051
- }
2052
- return `Analyze the following ${count} prompt${plural} from ${date}:${contextSection}
2053
-
2054
- ${promptsList}
2055
-
2056
- Please provide your analysis as a JSON object following the specified schema.`;
2057
- }
2058
- function isValidMinimalResponse(value) {
2059
- if (typeof value !== "object" || value === null) {
2060
- return false;
2061
- }
2062
- const obj = value;
2063
- if (!Array.isArray(obj["issues"])) {
2064
- return false;
2065
- }
2066
- if (!obj["issues"].every((item) => typeof item === "string")) {
2067
- return false;
2068
- }
2069
- return true;
2070
- }
2071
- function extractMinimalResult(obj) {
2072
- const issues = obj["issues"];
2073
- const score = typeof obj["score"] === "number" ? obj["score"] : 50;
2074
- return { issues, score };
2075
- }
2076
- function issueToPattern(issue, index) {
2077
- const id = issue.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
2078
- return {
2079
- id: id || `issue-${String(index)}`,
2080
- name: issue.name,
2081
- frequency: 1,
2082
- severity: "medium",
2083
- examples: [issue.example],
2084
- suggestion: issue.fix,
2085
- beforeAfter: {
2086
- before: issue.example,
2087
- after: issue.fix
2088
- }
2089
- };
2090
- }
2091
- function tryFixTruncatedJson(json) {
2092
- let fixed = json.trim();
2093
- let openBraces = 0;
2094
- let openBrackets = 0;
2095
- let inString = false;
2096
- let escapeNext = false;
2097
- for (const char of fixed) {
2098
- if (escapeNext) {
2099
- escapeNext = false;
2100
- continue;
2101
- }
2102
- if (char === "\\") {
2103
- escapeNext = true;
2104
- continue;
2105
- }
2106
- if (char === '"') {
2107
- inString = !inString;
2108
- continue;
2109
- }
2110
- if (inString) continue;
2111
- if (char === "{") openBraces++;
2112
- if (char === "}") openBraces--;
2113
- if (char === "[") openBrackets++;
2114
- if (char === "]") openBrackets--;
2115
- }
2116
- if (inString) {
2117
- fixed += '"';
2118
- }
2119
- fixed = fixed.replace(/,\s*$/, "");
2120
- while (openBrackets > 0) {
2121
- fixed += "]";
2122
- openBrackets--;
2123
- }
2124
- while (openBraces > 0) {
2125
- fixed += "}";
2126
- openBraces--;
2127
- }
2128
- return fixed;
2129
- }
2130
- function parseResponse(response, date, taxonomy = ISSUE_TAXONOMY, prompts) {
2131
- const codeBlockRegex = /```(?:json)?\s*\n?([\s\S]*?)\n?```/;
2132
- const jsonMatch = codeBlockRegex.exec(response);
2133
- let jsonString = jsonMatch?.[1]?.trim() ?? response.trim();
2134
- let parsed;
2135
- try {
2136
- parsed = JSON.parse(jsonString);
2137
- } catch {
2138
- jsonString = tryFixTruncatedJson(jsonString);
2139
- try {
2140
- parsed = JSON.parse(jsonString);
2141
- } catch (error) {
2142
- throw new Error(
2143
- `Failed to parse response as JSON: ${error instanceof Error ? error.message : "Unknown error"}`
2144
- );
2145
- }
2146
- }
2147
- if (isValidMinimalResponse(parsed)) {
2148
- const minimal = extractMinimalResult(parsed);
2149
- return convertMinimalToAnalysisResult(minimal, date, taxonomy, prompts);
2150
- }
2151
- if (isValidSimpleResponse(parsed)) {
2152
- const simple = extractSimpleResponse(parsed);
2153
- const patterns = simple.issues.map((issue, i) => issueToPattern(issue, i));
2154
- return {
2155
- date,
2156
- patterns,
2157
- stats: {
2158
- totalPrompts: 0,
2159
- // Will be filled by caller
2160
- promptsWithIssues: simple.issues.length,
2161
- overallScore: normalizeScore(simple.score)
2162
- },
2163
- topSuggestion: simple.tip
2164
- };
2165
- }
2166
- if (isValidFullResponse(parsed)) {
2167
- return {
2168
- date,
2169
- patterns: parsed.patterns,
2170
- stats: {
2171
- ...parsed.stats,
2172
- overallScore: normalizeScore(parsed.stats.overallScore)
2173
- },
2174
- topSuggestion: parsed.topSuggestion
2175
- };
2176
- }
2177
- throw new Error("Response does not match expected schema");
2178
- }
2179
- function isValidSimpleResponse(value) {
2180
- if (typeof value !== "object" || value === null) {
2181
- return false;
2182
- }
2183
- const obj = value;
2184
- if (!Array.isArray(obj["issues"])) {
2185
- return false;
2186
- }
2187
- for (const issue of obj["issues"]) {
2188
- if (typeof issue !== "object" || issue === null) {
2189
- return false;
2190
- }
2191
- const i = issue;
2192
- if (typeof i["name"] !== "string" || typeof i["example"] !== "string" || typeof i["fix"] !== "string") {
2193
- return false;
2194
- }
2195
- }
2196
- return true;
2197
- }
2198
- function extractSimpleResponse(obj) {
2199
- const issues = obj["issues"];
2200
- const score = typeof obj["score"] === "number" ? obj["score"] : 50;
2201
- const tip = typeof obj["tip"] === "string" ? obj["tip"] : issues.length > 0 && issues[0] ? issues[0].fix : "No suggestions";
2202
- return { issues, score, tip };
2203
- }
2204
- function isValidFullResponse(value) {
2205
- if (typeof value !== "object" || value === null) {
2206
- return false;
2207
- }
2208
- const obj = value;
2209
- if (!Array.isArray(obj["patterns"])) {
2210
- return false;
2211
- }
2212
- for (const pattern of obj["patterns"]) {
2213
- if (!isValidPattern(pattern)) {
2214
- return false;
2215
- }
2216
- }
2217
- if (typeof obj["stats"] !== "object" || obj["stats"] === null) {
2218
- return false;
2219
- }
2220
- const stats = obj["stats"];
2221
- if (typeof stats["totalPrompts"] !== "number" || typeof stats["promptsWithIssues"] !== "number" || typeof stats["overallScore"] !== "number") {
2222
- return false;
2223
- }
2224
- if (typeof obj["topSuggestion"] !== "string") {
2225
- return false;
2226
- }
2227
- return true;
2228
- }
2229
- function isValidPattern(value) {
2230
- if (typeof value !== "object" || value === null) {
2231
- return false;
2232
- }
2233
- const obj = value;
2234
- if (typeof obj["id"] !== "string" || typeof obj["name"] !== "string" || typeof obj["frequency"] !== "number" || typeof obj["suggestion"] !== "string") {
2235
- return false;
2236
- }
2237
- if (obj["severity"] !== "low" && obj["severity"] !== "medium" && obj["severity"] !== "high") {
2238
- return false;
2239
- }
2240
- if (!Array.isArray(obj["examples"]) || !obj["examples"].every((e) => typeof e === "string")) {
2241
- return false;
2242
- }
2243
- if (typeof obj["beforeAfter"] !== "object" || obj["beforeAfter"] === null) {
2244
- return false;
2245
- }
2246
- const beforeAfter = obj["beforeAfter"];
2247
- if (typeof beforeAfter["before"] !== "string" || typeof beforeAfter["after"] !== "string") {
2248
- return false;
2249
- }
2250
- return true;
2251
- }
2252
-
2253
- // src/providers/ollama.ts
2254
- var MAX_RETRIES = 2;
2255
- var AVAILABILITY_TIMEOUT_MS = 3e3;
2256
- var ANALYSIS_TIMEOUT_MS = 6e4;
2257
- var BASE_RETRY_DELAY_MS = 1e3;
2258
- var MODEL_STRATEGY_MAP = {
2259
- // Micro (< 4GB)
2260
- "llama3.2": "micro",
2261
- "phi3:mini": "micro",
2262
- "gemma3:4b": "micro",
2263
- "gemma2:2b": "micro",
2264
- // Small (4-7GB)
2265
- "mistral:7b": "small",
2266
- "llama3:8b": "small",
2267
- "codellama:7b": "small",
2268
- // Standard (> 7GB)
2269
- "llama3:70b": "standard",
2270
- mixtral: "standard",
2271
- "qwen2.5:14b": "standard"
2272
- };
2273
- function detectBatchStrategy(modelName) {
2274
- if (MODEL_STRATEGY_MAP[modelName]) {
2275
- return MODEL_STRATEGY_MAP[modelName];
2276
- }
2277
- for (const [pattern, strategy] of Object.entries(MODEL_STRATEGY_MAP)) {
2278
- if (modelName.includes(pattern)) {
2279
- return strategy;
2280
- }
2281
- }
2282
- return "micro";
2283
- }
2284
- var OllamaProvider = class {
2285
- name = "Ollama";
2286
- config;
2287
- batchStrategy;
2288
- schemaType;
2289
- /**
2290
- * Creates a new OllamaProvider instance.
2291
- * Automatically detects the optimal batch strategy and schema type based on model name.
2292
- *
2293
- * @param config - Ollama configuration with model and host
2294
- */
2295
- constructor(config) {
2296
- this.config = config;
2297
- this.batchStrategy = detectBatchStrategy(config.model);
2298
- this.schemaType = this.selectSchemaType();
2299
- const strategy = BATCH_STRATEGIES[this.batchStrategy];
2300
- logger.debug(
2301
- `Detected batch strategy: ${this.batchStrategy} (${strategy.description}), schema type: ${this.schemaType}`,
2302
- "ollama"
2303
- );
2304
- }
2305
- /**
2306
- * Selects the appropriate schema type based on model size.
2307
- * Micro and small models use minimal schema for better reliability.
2308
- * Standard models use full schema for detailed analysis.
2309
- *
2310
- * @returns Schema type identifier
2311
- */
2312
- selectSchemaType() {
2313
- return ["micro", "small"].includes(this.batchStrategy) ? "minimal" : "full";
2314
- }
2315
- /**
2316
- * Returns dynamic batch limits based on detected model strategy.
2317
- *
2318
- * @returns Provider limits with model-specific constraints
2319
- */
2320
- getBatchLimits() {
2321
- const strategy = BATCH_STRATEGIES[this.batchStrategy];
2322
- return {
2323
- maxTokensPerBatch: strategy.maxTokensPerBatch,
2324
- maxPromptsPerBatch: strategy.maxPromptsPerBatch,
2325
- prioritization: "longest-first"
2326
- };
2327
- }
2328
- /**
2329
- * Checks if the Ollama service is available and has the required model.
2330
- * Uses a 3-second timeout to avoid hanging on unreachable services.
2331
- *
2332
- * @returns Promise that resolves to true if available, false otherwise
2333
- */
2334
- async isAvailable() {
2335
- logger.debug(`Connecting to Ollama at ${this.config.host}`, "ollama");
2336
- try {
2337
- const controller = new AbortController();
2338
- const timeoutId = setTimeout(() => {
2339
- controller.abort();
2340
- }, AVAILABILITY_TIMEOUT_MS);
2341
- const response = await fetch(`${this.config.host}/api/tags`, {
2342
- signal: controller.signal
2343
- });
2344
- clearTimeout(timeoutId);
2345
- if (!response.ok) {
2346
- logger.debug(
2347
- `Ollama API returned ${String(response.status)}`,
2348
- "ollama"
2349
- );
2350
- return false;
2351
- }
2352
- const data = await response.json();
2353
- if (!data.models || !Array.isArray(data.models)) {
2354
- logger.debug("Ollama returned invalid model list", "ollama");
2355
- return false;
2356
- }
2357
- const modelAvailable = data.models.some(
2358
- (model) => model.name.includes(this.config.model)
2359
- );
2360
- if (modelAvailable) {
2361
- logger.debug(
2362
- `Model ${this.config.model} available (${String(data.models.length)} models found)`,
2363
- "ollama"
2364
- );
2365
- } else {
2366
- logger.debug(
2367
- `Model ${this.config.model} not found in available models`,
2368
- "ollama"
2369
- );
2370
- }
2371
- return modelAvailable;
2372
- } catch {
2373
- logger.debug("Ollama connection failed", "ollama");
2374
- return false;
2375
- }
2376
- }
2377
- /**
2378
- * Analyzes prompts using the Ollama service.
2379
- * Implements retry logic with exponential backoff for network errors.
2380
- *
2381
- * @param prompts - Array of prompt strings to analyze
2382
- * @param date - Date context for the analysis
2383
- * @param context - Optional project context for analysis
2384
- * @returns Promise resolving to AnalysisResult
2385
- * @throws Error if analysis fails after retries or if response is invalid
2386
- */
2387
- async analyze(prompts, date, context) {
2388
- if (prompts.length === 0) {
2389
- throw new Error("Cannot analyze empty prompts array");
2390
- }
2391
- const userPrompt = buildUserPrompt(prompts, date, context);
2392
- const systemPrompt = this.schemaType === "minimal" ? SYSTEM_PROMPT_MINIMAL : SYSTEM_PROMPT_FULL;
2393
- let lastError;
2394
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
2395
- try {
2396
- const controller = new AbortController();
2397
- const timeoutId = setTimeout(() => {
2398
- controller.abort();
2399
- }, ANALYSIS_TIMEOUT_MS);
2400
- const response = await fetch(`${this.config.host}/api/generate`, {
2401
- method: "POST",
2402
- headers: {
2403
- "Content-Type": "application/json"
2404
- },
2405
- body: JSON.stringify({
2406
- model: this.config.model,
2407
- prompt: userPrompt,
2408
- system: systemPrompt,
2409
- stream: false,
2410
- format: "json",
2411
- options: {
2412
- temperature: 0.3
2413
- }
2414
- }),
2415
- signal: controller.signal
2416
- });
2417
- clearTimeout(timeoutId);
2418
- if (!response.ok) {
2419
- const status = String(response.status);
2420
- throw new Error(
2421
- `Ollama API request failed: ${status} ${response.statusText}`
2422
- );
2423
- }
2424
- const data = await response.json();
2425
- if (typeof data.response !== "string") {
2426
- throw new Error("Invalid response format from Ollama API");
2427
- }
2428
- return parseResponse(data.response, date, void 0, prompts);
2429
- } catch (error) {
2430
- lastError = error instanceof Error ? error : new Error(String(error));
2431
- if (lastError.message.includes("parse") || lastError.message.includes("schema")) {
2432
- throw lastError;
2433
- }
2434
- if (attempt === MAX_RETRIES) {
2435
- break;
2436
- }
2437
- const delay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt);
2438
- logger.debug(
2439
- `Retry attempt ${String(attempt + 1)}/${String(MAX_RETRIES)}, waiting ${String(delay)}ms`,
2440
- "ollama"
2441
- );
2442
- await sleep(delay);
2443
- }
2444
- }
2445
- const attempts = String(MAX_RETRIES + 1);
2446
- throw new Error(
2447
- `Ollama analysis failed after ${attempts} attempts: ${lastError?.message ?? "Unknown error"}`
2448
- );
2449
- }
2450
- };
2451
- function sleep(ms) {
2452
- return new Promise((resolve) => setTimeout(resolve, ms));
2453
- }
2454
-
2455
- // src/utils/rate-limiter.ts
2456
- function createRateLimiter(options) {
2457
- const minIntervalMs = 6e4 / options.requestsPerMinute;
2458
- let lastRequestTime = 0;
2459
- async function throttle(fn) {
2460
- const now = Date.now();
2461
- const timeSinceLastRequest = now - lastRequestTime;
2462
- if (lastRequestTime > 0 && timeSinceLastRequest < minIntervalMs) {
2463
- const waitTime = minIntervalMs - timeSinceLastRequest;
2464
- await new Promise((resolve) => setTimeout(resolve, waitTime));
2465
- }
2466
- lastRequestTime = Date.now();
2467
- return fn();
2468
- }
2469
- function reset() {
2470
- lastRequestTime = 0;
2471
- }
2472
- return { throttle, reset };
2473
- }
2474
- var DEFAULT_RATE_LIMITS = {
2475
- anthropic: 50,
2476
- google: 50
2477
- };
2478
-
2479
- // src/utils/retry.ts
2480
- var DEFAULT_OPTIONS = {
2481
- maxRetries: 3,
2482
- baseDelayMs: 1e3,
2483
- maxDelayMs: 3e4,
2484
- isRetryable: isTransientError
2485
- };
2486
- function isTransientError(error) {
2487
- if (!(error instanceof Error)) {
2488
- return false;
2489
- }
2490
- const message = error.message.toLowerCase();
2491
- if (message.includes("network") || message.includes("timeout") || message.includes("econnreset") || message.includes("econnrefused") || message.includes("enotfound") || message.includes("abort")) {
2492
- return true;
2493
- }
2494
- if (message.includes("500") || message.includes("502") || message.includes("503") || message.includes("504")) {
2495
- return true;
2496
- }
2497
- if (message.includes("429")) {
2498
- return true;
2499
- }
2500
- if (message.includes("401") || message.includes("403")) {
2501
- return false;
2502
- }
2503
- if (message.includes("parse") || message.includes("schema")) {
2504
- return false;
2505
- }
2506
- return false;
2507
- }
2508
- function sleep2(ms) {
2509
- return new Promise((resolve) => setTimeout(resolve, ms));
2510
- }
2511
- async function withRetry(fn, options = {}) {
2512
- const opts = { ...DEFAULT_OPTIONS, ...options };
2513
- let lastError;
2514
- for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
2515
- try {
2516
- return await fn();
2517
- } catch (error) {
2518
- lastError = error;
2519
- const isLastAttempt = attempt === opts.maxRetries;
2520
- const shouldRetry = opts.isRetryable(error);
2521
- if (isLastAttempt || !shouldRetry) {
2522
- throw error;
2523
- }
2524
- const delay = Math.min(
2525
- opts.baseDelayMs * Math.pow(2, attempt),
2526
- opts.maxDelayMs
2527
- );
2528
- await sleep2(delay);
2529
- }
2530
- }
2531
- throw lastError;
2532
- }
2533
-
2534
- // src/providers/anthropic.ts
2535
- var MAX_RETRIES2 = 3;
2536
- var AVAILABILITY_TIMEOUT_MS2 = 5e3;
2537
- var ANALYSIS_TIMEOUT_MS2 = 6e4;
2538
- var BASE_DELAY_MS = 1e3;
2539
- var MAX_DELAY_MS = 3e4;
2540
- var API_BASE_URL = "https://api.anthropic.com";
2541
- var API_VERSION = "2023-06-01";
2542
- var MAX_TOKENS = 4096;
2543
- var AnthropicProvider = class {
2544
- name = "Anthropic";
2545
- config;
2546
- rateLimiter;
2547
- /**
2548
- * Creates a new AnthropicProvider instance.
2549
- *
2550
- * @param config - Anthropic configuration with model and API key
2551
- */
2552
- constructor(config) {
2553
- this.config = config;
2554
- this.rateLimiter = createRateLimiter({
2555
- requestsPerMinute: DEFAULT_RATE_LIMITS.anthropic
2556
- });
2557
- }
2558
- /**
2559
- * Checks if the Anthropic API is available by validating the API key.
2560
- * Makes a minimal request to verify the key is valid.
2561
- *
2562
- * @returns Promise that resolves to true if available, false otherwise
2563
- */
2564
- async isAvailable() {
2565
- if (!this.config.apiKey) {
2566
- logger.debug("No API key configured", "anthropic");
2567
- return false;
2568
- }
2569
- logger.debug(
2570
- `Validating API key with model ${this.config.model}`,
2571
- "anthropic"
2572
- );
2573
- try {
2574
- const controller = new AbortController();
2575
- const timeoutId = setTimeout(() => {
2576
- controller.abort();
2577
- }, AVAILABILITY_TIMEOUT_MS2);
2578
- const response = await fetch(`${API_BASE_URL}/v1/messages`, {
2579
- method: "POST",
2580
- headers: {
2581
- "Content-Type": "application/json",
2582
- "x-api-key": this.config.apiKey,
2583
- "anthropic-version": API_VERSION
2584
- },
2585
- body: JSON.stringify({
2586
- model: this.config.model,
2587
- max_tokens: 1,
2588
- messages: [{ role: "user", content: "Hi" }]
2589
- }),
2590
- signal: controller.signal
2591
- });
2592
- clearTimeout(timeoutId);
2593
- const isAvailable = response.ok || response.status === 429 || response.status === 400;
2594
- logger.debug(
2595
- `API responded with status ${String(response.status)} (available: ${String(isAvailable)})`,
2596
- "anthropic"
2597
- );
2598
- return isAvailable;
2599
- } catch {
2600
- logger.debug("Connection failed", "anthropic");
2601
- return false;
2602
- }
2603
- }
2604
- /**
2605
- * Analyzes prompts using the Anthropic Claude API.
2606
- * Implements retry logic with exponential backoff for network errors.
2607
- * Rate limited to prevent 429 errors during batch processing.
2608
- *
2609
- * @param prompts - Array of prompt strings to analyze
2610
- * @param date - Date context for the analysis
2611
- * @param context - Optional project context for analysis
2612
- * @returns Promise resolving to AnalysisResult
2613
- * @throws Error if analysis fails after retries or if response is invalid
2614
- */
2615
- async analyze(prompts, date, context) {
2616
- if (prompts.length === 0) {
2617
- throw new Error("Cannot analyze empty prompts array");
2618
- }
2619
- const userPrompt = buildUserPrompt(prompts, date, context);
2620
- return this.rateLimiter.throttle(
2621
- () => withRetry(
2622
- async () => {
2623
- const controller = new AbortController();
2624
- const timeoutId = setTimeout(() => {
2625
- controller.abort();
2626
- }, ANALYSIS_TIMEOUT_MS2);
2627
- try {
2628
- const response = await fetch(`${API_BASE_URL}/v1/messages`, {
2629
- method: "POST",
2630
- headers: {
2631
- "Content-Type": "application/json",
2632
- "x-api-key": this.config.apiKey,
2633
- "anthropic-version": API_VERSION
2634
- },
2635
- body: JSON.stringify({
2636
- model: this.config.model,
2637
- max_tokens: MAX_TOKENS,
2638
- system: SYSTEM_PROMPT_FULL,
2639
- messages: [{ role: "user", content: userPrompt }]
2640
- }),
2641
- signal: controller.signal
2642
- });
2643
- if (!response.ok) {
2644
- const status = String(response.status);
2645
- const errorBody = await response.text();
2646
- throw new Error(
2647
- `Anthropic API request failed: ${status} ${response.statusText} - ${errorBody}`
2648
- );
2649
- }
2650
- const data = await response.json();
2651
- const textContent = data.content?.find(
2652
- (block) => block.type === "text"
2653
- );
2654
- if (!textContent?.text) {
2655
- throw new Error("Invalid response format from Anthropic API");
2656
- }
2657
- return parseResponse(textContent.text, date, void 0, prompts);
2658
- } finally {
2659
- clearTimeout(timeoutId);
2660
- }
2661
- },
2662
- {
2663
- maxRetries: MAX_RETRIES2,
2664
- baseDelayMs: BASE_DELAY_MS,
2665
- maxDelayMs: MAX_DELAY_MS,
2666
- isRetryable: isTransientError
2667
- }
2668
- )
2669
- );
2670
- }
2671
- };
2672
-
2673
- // src/providers/google.ts
2674
- var MAX_RETRIES3 = 3;
2675
- var AVAILABILITY_TIMEOUT_MS3 = 5e3;
2676
- var ANALYSIS_TIMEOUT_MS3 = 6e4;
2677
- var BASE_DELAY_MS2 = 1e3;
2678
- var MAX_DELAY_MS2 = 3e4;
2679
- var API_BASE_URL2 = "https://generativelanguage.googleapis.com/v1beta";
2680
- var GoogleProvider = class {
2681
- name = "Google";
2682
- config;
2683
- rateLimiter;
2684
- /**
2685
- * Creates a new GoogleProvider instance.
2686
- *
2687
- * @param config - Google configuration with model and API key
2688
- */
2689
- constructor(config) {
2690
- this.config = config;
2691
- this.rateLimiter = createRateLimiter({
2692
- requestsPerMinute: DEFAULT_RATE_LIMITS.google
2693
- });
2694
- }
2695
- /**
2696
- * Checks if the Google Gemini API is available by validating the API key.
2697
- * Makes a minimal request to verify the key is valid.
2698
- *
2699
- * @returns Promise that resolves to true if available, false otherwise
2700
- */
2701
- async isAvailable() {
2702
- if (!this.config.apiKey) {
2703
- logger.debug("No API key configured", "google");
2704
- return false;
2705
- }
2706
- logger.debug(
2707
- `Validating API key with model ${this.config.model}`,
2708
- "google"
2709
- );
2710
- try {
2711
- const controller = new AbortController();
2712
- const timeoutId = setTimeout(() => {
2713
- controller.abort();
2714
- }, AVAILABILITY_TIMEOUT_MS3);
2715
- const url = `${API_BASE_URL2}/models/${this.config.model}:generateContent?key=${this.config.apiKey}`;
2716
- const response = await fetch(url, {
2717
- method: "POST",
2718
- headers: {
2719
- "Content-Type": "application/json"
2720
- },
2721
- body: JSON.stringify({
2722
- contents: [
2723
- {
2724
- role: "user",
2725
- parts: [{ text: "Hi" }]
2726
- }
2727
- ],
2728
- generationConfig: {
2729
- maxOutputTokens: 1
2730
- }
2731
- }),
2732
- signal: controller.signal
2733
- });
2734
- clearTimeout(timeoutId);
2735
- const isAvailable = response.ok || response.status === 429 || response.status === 400;
2736
- logger.debug(
2737
- `API responded with status ${String(response.status)} (available: ${String(isAvailable)})`,
2738
- "google"
2739
- );
2740
- return isAvailable;
2741
- } catch {
2742
- logger.debug("Connection failed", "google");
2743
- return false;
2744
- }
2745
- }
2746
- /**
2747
- * Analyzes prompts using the Google Gemini API.
2748
- * Implements retry logic with exponential backoff for network errors.
2749
- * Rate limited to prevent 429 errors during batch processing.
2750
- *
2751
- * @param prompts - Array of prompt strings to analyze
2752
- * @param date - Date context for the analysis
2753
- * @param context - Optional project context for analysis
2754
- * @returns Promise resolving to AnalysisResult
2755
- * @throws Error if analysis fails after retries or if response is invalid
2756
- */
2757
- async analyze(prompts, date, context) {
2758
- if (prompts.length === 0) {
2759
- throw new Error("Cannot analyze empty prompts array");
2760
- }
2761
- const userPrompt = buildUserPrompt(prompts, date, context);
2762
- return this.rateLimiter.throttle(
2763
- () => withRetry(
2764
- async () => {
2765
- const controller = new AbortController();
2766
- const timeoutId = setTimeout(() => {
2767
- controller.abort();
2768
- }, ANALYSIS_TIMEOUT_MS3);
2769
- try {
2770
- const url = `${API_BASE_URL2}/models/${this.config.model}:generateContent?key=${this.config.apiKey}`;
2771
- const response = await fetch(url, {
2772
- method: "POST",
2773
- headers: {
2774
- "Content-Type": "application/json"
2775
- },
2776
- body: JSON.stringify({
2777
- contents: [
2778
- {
2779
- role: "user",
2780
- parts: [{ text: userPrompt }]
2781
- }
2782
- ],
2783
- systemInstruction: {
2784
- parts: [{ text: SYSTEM_PROMPT_FULL }]
2785
- },
2786
- generationConfig: {
2787
- responseMimeType: "application/json"
2788
- }
2789
- }),
2790
- signal: controller.signal
2791
- });
2792
- if (!response.ok) {
2793
- const status = String(response.status);
2794
- const errorBody = await response.text();
2795
- throw new Error(
2796
- `Google API request failed: ${status} ${response.statusText} - ${errorBody}`
2797
- );
2798
- }
2799
- const data = await response.json();
2800
- const textContent = data.candidates?.[0]?.content?.parts?.[0]?.text;
2801
- if (!textContent) {
2802
- throw new Error("Invalid response format from Google API");
2803
- }
2804
- return parseResponse(textContent, date, void 0, prompts);
2805
- } finally {
2806
- clearTimeout(timeoutId);
2807
- }
2808
- },
2809
- {
2810
- maxRetries: MAX_RETRIES3,
2811
- baseDelayMs: BASE_DELAY_MS2,
2812
- maxDelayMs: MAX_DELAY_MS2,
2813
- isRetryable: isTransientError
2814
- }
2815
- )
2816
- );
2817
- }
2818
- };
2819
-
2820
- // src/providers/index.ts
2821
- function createProvider(type, config) {
2822
- switch (type) {
2823
- case "ollama":
2824
- return new OllamaProvider(config.ollama);
2825
- case "anthropic":
2826
- return new AnthropicProvider(config.anthropic);
2827
- case "google":
2828
- return new GoogleProvider(config.google);
2829
- }
2830
- }
2831
- async function getAvailableProvider(config, onFallback) {
2832
- if (config.services.length === 0) {
2833
- throw new Error(
2834
- "No providers configured. Please run hyntx setup to configure providers."
2835
- );
2836
- }
2837
- logger.debug(
2838
- `Checking ${String(config.services.length)} configured provider(s): ${config.services.join(", ")}`,
2839
- "provider"
2840
- );
2841
- let firstProvider;
2842
- for (const type of config.services) {
2843
- const provider = createProvider(type, config);
2844
- firstProvider ??= provider;
2845
- logger.debug(`Checking availability of ${provider.name}...`, "provider");
2846
- try {
2847
- const isAvailable = await provider.isAvailable();
2848
- if (isAvailable) {
2849
- logger.debug(`${provider.name} is available`, "provider");
2850
- if (onFallback && provider !== firstProvider) {
2851
- onFallback(firstProvider.name, provider.name);
2852
- }
2853
- return provider;
2854
- } else {
2855
- logger.debug(`${provider.name} is not available`, "provider");
2856
- }
2857
- } catch {
2858
- logger.debug(`${provider.name} availability check failed`, "provider");
2859
- continue;
2860
- }
2861
- }
2862
- throw new Error(
2863
- "No providers are currently available. Please check your provider configurations."
2864
- );
2865
- }
2866
- function getAllProviders(config) {
2867
- if (config.services.length === 0) {
2868
- throw new Error(
2869
- "No providers configured. Please run hyntx setup to configure providers."
2870
- );
2871
- }
2872
- return config.services.map((type) => createProvider(type, config));
2873
- }
2874
- var START_MARKER = "# >>> hyntx config >>>";
2875
- var END_MARKER = "# <<< hyntx config <<<";
2876
- function findMarkerPositions(content) {
2877
- const startIndex = content.indexOf(START_MARKER);
2878
- const endIndex = content.indexOf(END_MARKER);
2879
- if (startIndex === -1 && endIndex === -1) {
2880
- return { startIndex: -1, endIndex: -1, isValid: true };
2881
- }
2882
- if (startIndex !== -1 && endIndex === -1) {
2883
- return { startIndex, endIndex: -1, isValid: false, issue: "missing_end" };
2884
- }
2885
- if (startIndex === -1 && endIndex !== -1) {
2886
- return { startIndex: -1, endIndex, isValid: false, issue: "missing_start" };
2887
- }
2888
- if (startIndex > endIndex) {
2889
- return { startIndex, endIndex, isValid: false, issue: "wrong_order" };
2890
- }
2891
- return { startIndex, endIndex, isValid: true };
2892
- }
2893
- function detectShellConfigFile() {
2894
- const home = homedir();
2895
- const shell = process.env["SHELL"] ?? "";
2896
- if (shell.includes("zsh")) {
2897
- return {
2898
- shellType: "zsh",
2899
- configFile: join(home, ".zshrc")
2900
- };
2901
- }
2902
- if (shell.includes("bash")) {
2903
- return {
2904
- shellType: "bash",
2905
- configFile: join(home, ".bashrc")
2906
- };
2907
- }
2908
- if (shell.includes("fish")) {
2909
- return {
2910
- shellType: "fish",
2911
- configFile: join(home, ".config", "fish", "config.fish")
2912
- };
2913
- }
2914
- const defaultShell = process.platform === "darwin" ? "zsh" : "bash";
2915
- return {
2916
- shellType: defaultShell,
2917
- configFile: join(home, `.${defaultShell}rc`)
2918
- };
2919
- }
2920
-
2921
- // src/utils/env.ts
2922
- var VALID_PROVIDERS = [
2923
- "ollama",
2924
- "anthropic",
2925
- "google"
2926
- ];
2927
- function isFirstRun() {
2928
- if (process.env["HYNTX_SERVICES"]) {
2929
- return false;
2930
- }
2931
- try {
2932
- const { configFile } = detectShellConfigFile();
2933
- if (existsSync(configFile)) {
2934
- const content = readFileSync(configFile, "utf-8");
2935
- const positions = findMarkerPositions(content);
2936
- if (positions.startIndex !== -1 && positions.endIndex !== -1 && positions.isValid) {
2937
- return false;
2938
- }
2939
- }
2940
- } catch {
2941
- }
2942
- return true;
2943
- }
2944
- function parseServices(services) {
2945
- if (!services || services.trim() === "") {
2946
- return [];
2947
- }
2948
- return services.split(",").map((s) => s.trim().toLowerCase()).filter(
2949
- (s) => VALID_PROVIDERS.includes(s)
2950
- );
2951
- }
2952
- function getEnvConfig() {
2953
- return {
2954
- services: parseServices(process.env["HYNTX_SERVICES"]),
2955
- reminder: process.env["HYNTX_REMINDER"] ?? ENV_DEFAULTS.reminder,
2956
- ollama: {
2957
- model: process.env["HYNTX_OLLAMA_MODEL"] ?? ENV_DEFAULTS.ollama.model,
2958
- host: process.env["HYNTX_OLLAMA_HOST"] ?? ENV_DEFAULTS.ollama.host
2959
- },
2960
- anthropic: {
2961
- model: process.env["HYNTX_ANTHROPIC_MODEL"] ?? ENV_DEFAULTS.anthropic.model,
2962
- apiKey: process.env["HYNTX_ANTHROPIC_KEY"] ?? ""
2963
- },
2964
- google: {
2965
- model: process.env["HYNTX_GOOGLE_MODEL"] ?? ENV_DEFAULTS.google.model,
2966
- apiKey: process.env["HYNTX_GOOGLE_KEY"] ?? ""
2967
- }
2968
- };
2969
- }
2970
- var CONFIG_FILENAME = ".hyntxrc.json";
2971
- var MAX_TRAVERSAL_DEPTH = 50;
2972
- var PROJECT_CONTEXT_SCHEMA = z.object({
2973
- role: z.string().optional(),
2974
- techStack: z.array(z.string()).optional(),
2975
- domain: z.string().optional(),
2976
- guidelines: z.array(z.string()).optional(),
2977
- projectType: z.string().optional()
2978
- });
2979
- var RULE_CONFIG_SCHEMA = z.object({
2980
- enabled: z.boolean().optional(),
2981
- severity: z.enum(["low", "medium", "high"]).optional()
2982
- });
2983
- var RULES_CONFIG_SCHEMA = z.record(z.string(), RULE_CONFIG_SCHEMA);
2984
- var PROJECT_CONFIG_SCHEMA = z.object({
2985
- context: PROJECT_CONTEXT_SCHEMA.optional(),
2986
- rules: RULES_CONFIG_SCHEMA.optional()
2987
- });
2988
- var configCache = /* @__PURE__ */ new Map();
2989
- function findProjectConfig(cwd) {
2990
- let currentDir = cwd;
2991
- const homeDirectory = homedir();
2992
- let depth = 0;
2993
- while (depth < MAX_TRAVERSAL_DEPTH) {
2994
- const configPath = join(currentDir, CONFIG_FILENAME);
2995
- try {
2996
- readFileSync(configPath, "utf-8");
2997
- return configPath;
2998
- } catch {
2999
- }
3000
- if (currentDir === homeDirectory || currentDir === "/") {
3001
- break;
3002
- }
3003
- const parentDir = dirname(currentDir);
3004
- if (parentDir === currentDir) {
3005
- break;
3006
- }
3007
- currentDir = parentDir;
3008
- depth++;
3009
- }
3010
- return null;
3011
- }
3012
- function loadProjectConfig(configPath) {
3013
- try {
3014
- const fileContent = readFileSync(configPath, "utf-8");
3015
- let parsed;
3016
- try {
3017
- parsed = JSON.parse(fileContent);
3018
- } catch (error) {
3019
- logger.collectWarning(
3020
- `Invalid JSON in ${CONFIG_FILENAME}: ${error instanceof Error ? error.message : "Unknown error"}`,
3021
- "config"
3022
- );
3023
- return null;
3024
- }
3025
- const result = PROJECT_CONFIG_SCHEMA.safeParse(parsed);
3026
- if (!result.success) {
3027
- const errorMessages = result.error.issues.map((issue) => {
3028
- const pathStr = issue.path.map(String).join(".");
3029
- return `${pathStr}: ${issue.message}`;
3030
- }).join(", ");
3031
- logger.collectWarning(
3032
- `Invalid ${CONFIG_FILENAME} schema: ${errorMessages}`,
3033
- "config"
3034
- );
3035
- return null;
3036
- }
3037
- return result.data;
3038
- } catch (error) {
3039
- logger.collectWarning(
3040
- `Failed to read ${CONFIG_FILENAME}: ${error instanceof Error ? error.message : "Unknown error"}`,
3041
- "config"
3042
- );
3043
- return null;
3044
- }
3045
- }
3046
- function mergeConfigs(envConfig, projectConfig) {
3047
- if (!projectConfig) {
3048
- return envConfig;
3049
- }
3050
- const existingEnvConfig = envConfig;
3051
- const merged = {
3052
- ...envConfig
3053
- };
3054
- if (projectConfig.context && !existingEnvConfig.context) {
3055
- merged.context = projectConfig.context;
3056
- } else if (existingEnvConfig.context) {
3057
- merged.context = existingEnvConfig.context;
3058
- }
3059
- if (projectConfig.rules) {
3060
- merged.rules = projectConfig.rules;
3061
- }
3062
- return merged;
3063
- }
3064
- function loadProjectConfigForCwd(cwd) {
3065
- if (configCache.has(cwd)) {
3066
- return configCache.get(cwd) ?? null;
3067
- }
3068
- const configPath = findProjectConfig(cwd);
3069
- if (!configPath) {
3070
- configCache.set(cwd, null);
3071
- return null;
3072
- }
3073
- const config = loadProjectConfig(configPath);
3074
- configCache.set(cwd, config);
3075
- return config;
3076
- }
3077
-
3078
- export { BATCH_STRATEGIES, CACHE_ANALYSIS_DIR, CACHE_DEFAULTS, CACHE_META_FILE, CLAUDE_PROJECTS_DIR, ENV_DEFAULTS, EXIT_CODES, HYNTX_CACHE_DIR, HYNTX_HISTORY_DIR, LAST_RUN_FILE, PROVIDER_LIMITS, analyzePrompts, claudeProjectsExist, cleanupExpiredEntries, clearCache, compareResults, createProvider, ensureHistoryDir, extractProjectName, generateCacheKey, getAllProviders, getAvailableProvider, getCachedResult, getDateOneMonthAgo, getDateOneWeekAgo, getEnvConfig, getHistoryDir, groupByDay, hashSystemPrompt, isFirstRun, listAvailableDates, loadAnalysisResult, loadProjectConfig, loadProjectConfigForCwd, mergeConfigs, parseDate, parseServices, readLogs, sanitize, sanitizePrompts, saveAnalysisResult, setCachedResult, validateSystemPrompt };
1
+ export { BATCH_STRATEGIES, CACHE_ANALYSIS_DIR, CACHE_DEFAULTS, CACHE_META_FILE, CLAUDE_PROJECTS_DIR, ENV_DEFAULTS, EXIT_CODES, HYNTX_CACHE_DIR, HYNTX_HISTORY_DIR, LAST_RUN_FILE, PROVIDER_LIMITS, analyzePrompts, claudeProjectsExist, cleanupExpiredEntries, clearCache, compareResults, createProvider, ensureHistoryDir, extractProjectName, generateCacheKey, getAllProviders, getAvailableProvider, getCachedResult, getDateOneMonthAgo, getDateOneWeekAgo, getEnvConfig, getHistoryDir, groupByDay, hashSystemPrompt, isFirstRun, listAvailableDates, loadAnalysisResult, loadProjectConfig, loadProjectConfigForCwd, mergeConfigs, parseDate, parseServices, readLogs, sanitize, sanitizePrompts, saveAnalysisResult, setCachedResult, validateSystemPrompt } from '../chunk-TGFHVZHY.js';