hyntx 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,18 +1,19 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, existsSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
2
+ import chalk6 from 'chalk';
3
+ import { readFileSync, realpathSync, existsSync, readdirSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
3
4
  import { homedir } from 'os';
4
- import { join, dirname, basename } from 'path';
5
+ import { join, dirname, extname, resolve, basename } from 'path';
5
6
  import { parseArgs } from 'util';
7
+ import { readFile, mkdir, writeFile, rename } from 'fs/promises';
6
8
  import { fileURLToPath } from 'url';
7
- import chalk3 from 'chalk';
8
9
  import ora from 'ora';
9
- import { readFile } from 'fs/promises';
10
+ import { isAfter, parseISO, subDays, format, subMonths, startOfDay, differenceInDays, isSameDay, isBefore } from 'date-fns';
10
11
  import { glob } from 'glob';
11
- import { isAfter, parseISO, startOfDay, isSameDay, isBefore } from 'date-fns';
12
12
  import prompts from 'prompts';
13
13
  import boxen2 from 'boxen';
14
14
  import Table from 'cli-table3';
15
15
  import figlet from 'figlet';
16
+ import { z } from 'zod';
16
17
 
17
18
  var __defProp = Object.defineProperty;
18
19
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -23,16 +24,187 @@ var __export = (target, all) => {
23
24
  for (var name in all)
24
25
  __defProp(target, name, { get: all[name], enumerable: true });
25
26
  };
27
+ var Logger, logger;
28
+ var init_logger = __esm({
29
+ "src/utils/logger.ts"() {
30
+ Logger = class {
31
+ warnings = [];
32
+ verboseEnabled = false;
33
+ /**
34
+ * Enables or disables verbose (debug) mode.
35
+ *
36
+ * @param enabled - Whether to enable verbose mode
37
+ */
38
+ setVerbose(enabled) {
39
+ this.verboseEnabled = enabled;
40
+ }
41
+ /**
42
+ * Returns whether verbose mode is enabled.
43
+ *
44
+ * @returns true if verbose mode is enabled
45
+ */
46
+ isVerbose() {
47
+ return this.verboseEnabled;
48
+ }
49
+ /**
50
+ * Logs an error message to stderr.
51
+ *
52
+ * @param message - Error message
53
+ * @param context - Optional context (e.g., file name, operation)
54
+ */
55
+ error(message, context) {
56
+ const prefix = context ? `[${context}] ` : "";
57
+ process.stderr.write(chalk6.red(`ERROR: ${prefix}${message}
58
+ `));
59
+ }
60
+ /**
61
+ * Logs a warning message to stderr.
62
+ *
63
+ * @param message - Warning message
64
+ * @param context - Optional context (e.g., file name, operation)
65
+ */
66
+ warn(message, context) {
67
+ const prefix = context ? `[${context}] ` : "";
68
+ process.stderr.write(chalk6.yellow(`WARN: ${prefix}${message}
69
+ `));
70
+ }
71
+ /**
72
+ * Logs an info message to stderr.
73
+ *
74
+ * @param message - Info message
75
+ */
76
+ info(message) {
77
+ process.stderr.write(chalk6.blue(`INFO: ${message}
78
+ `));
79
+ }
80
+ /**
81
+ * Logs a debug message to stderr (only when verbose mode is enabled).
82
+ *
83
+ * @param message - Debug message
84
+ * @param context - Optional context
85
+ */
86
+ debug(message, context) {
87
+ if (this.verboseEnabled) {
88
+ const prefix = context ? `[${context}] ` : "";
89
+ process.stderr.write(chalk6.gray(`[DEBUG] ${prefix}${message}
90
+ `));
91
+ }
92
+ }
93
+ /**
94
+ * Collects a warning for later reporting.
95
+ * Use this for non-fatal issues that should be displayed at the end of execution.
96
+ *
97
+ * @param message - Warning message
98
+ * @param context - Optional context (e.g., file name, operation)
99
+ */
100
+ collectWarning(message, context) {
101
+ this.warnings.push({ message, context });
102
+ }
103
+ /**
104
+ * Returns all collected warnings.
105
+ *
106
+ * @returns Array of collected warnings
107
+ */
108
+ getWarnings() {
109
+ return [...this.warnings];
110
+ }
111
+ /**
112
+ * Returns the number of collected warnings.
113
+ *
114
+ * @returns Warning count
115
+ */
116
+ getWarningCount() {
117
+ return this.warnings.length;
118
+ }
119
+ /**
120
+ * Clears all collected warnings.
121
+ */
122
+ clearWarnings() {
123
+ this.warnings = [];
124
+ }
125
+ /**
126
+ * Reports all collected warnings to stderr and clears them.
127
+ * Does nothing if there are no warnings.
128
+ */
129
+ reportWarnings() {
130
+ if (this.warnings.length === 0) {
131
+ return;
132
+ }
133
+ process.stderr.write(
134
+ chalk6.yellow(`
135
+ \u26A0\uFE0F ${String(this.warnings.length)} warning(s):
136
+ `)
137
+ );
138
+ for (const warning of this.warnings) {
139
+ const prefix = warning.context ? `[${warning.context}] ` : "";
140
+ process.stderr.write(chalk6.yellow(` - ${prefix}${warning.message}
141
+ `));
142
+ }
143
+ this.clearWarnings();
144
+ }
145
+ /**
146
+ * Formats collected warnings as plain text (without ANSI colors).
147
+ * Useful for JSON output or testing.
148
+ *
149
+ * @returns Array of formatted warning strings
150
+ */
151
+ formatWarnings() {
152
+ return this.warnings.map((w) => {
153
+ const prefix = w.context ? `[${w.context}] ` : "";
154
+ return `${prefix}${w.message}`;
155
+ });
156
+ }
157
+ };
158
+ logger = new Logger();
159
+ }
160
+ });
26
161
 
27
162
  // src/utils/shell-config.ts
28
163
  var shell_config_exports = {};
29
164
  __export(shell_config_exports, {
30
165
  detectShellConfigFile: () => detectShellConfigFile,
166
+ findMarkerPositions: () => findMarkerPositions,
31
167
  generateEnvExports: () => generateEnvExports,
32
168
  getManualInstructions: () => getManualInstructions,
169
+ removeMalformedMarkers: () => removeMalformedMarkers,
33
170
  saveConfigToShell: () => saveConfigToShell,
34
171
  updateShellConfig: () => updateShellConfig
35
172
  });
173
+ function findMarkerPositions(content) {
174
+ const startIndex = content.indexOf(START_MARKER);
175
+ const endIndex = content.indexOf(END_MARKER);
176
+ if (startIndex === -1 && endIndex === -1) {
177
+ return { startIndex: -1, endIndex: -1, isValid: true };
178
+ }
179
+ if (startIndex !== -1 && endIndex === -1) {
180
+ return { startIndex, endIndex: -1, isValid: false, issue: "missing_end" };
181
+ }
182
+ if (startIndex === -1 && endIndex !== -1) {
183
+ return { startIndex: -1, endIndex, isValid: false, issue: "missing_start" };
184
+ }
185
+ if (startIndex > endIndex) {
186
+ return { startIndex, endIndex, isValid: false, issue: "wrong_order" };
187
+ }
188
+ return { startIndex, endIndex, isValid: true };
189
+ }
190
+ function removeMalformedMarkers(content, positions) {
191
+ let result = content;
192
+ if (positions.issue === "wrong_order") {
193
+ const startLineEnd = result.indexOf("\n", positions.startIndex);
194
+ const before = result.slice(0, positions.endIndex);
195
+ const after = result.slice(
196
+ startLineEnd !== -1 ? startLineEnd + 1 : result.length
197
+ );
198
+ result = before.trimEnd() + (after ? "\n" + after : "");
199
+ } else {
200
+ const markerIndex = positions.startIndex !== -1 ? positions.startIndex : positions.endIndex;
201
+ const marker = positions.startIndex !== -1 ? START_MARKER : END_MARKER;
202
+ const lineStart = result.lastIndexOf("\n", markerIndex - 1) + 1;
203
+ const lineEnd = result.indexOf("\n", markerIndex + marker.length);
204
+ result = result.slice(0, lineStart) + result.slice(lineEnd !== -1 ? lineEnd + 1 : result.length);
205
+ }
206
+ return result.trimEnd();
207
+ }
36
208
  function detectShellConfigFile() {
37
209
  const home = homedir();
38
210
  const shell = process.env["SHELL"] ?? "";
@@ -87,15 +259,13 @@ function generateEnvExports(config) {
87
259
  return lines;
88
260
  }
89
261
  function updateShellConfig(configFile, exports$1) {
90
- const startMarker = "# >>> hyntx config >>>";
91
- const endMarker = "# <<< hyntx config <<<";
92
262
  const exportLines = exports$1.map((line) => ` ${line}`).join("\n");
93
- const configBlock = `${startMarker}
263
+ const configBlock = `${START_MARKER}
94
264
  ${exportLines}
95
265
 
96
266
  # Uncomment to enable periodic reminders:
97
267
  # hyntx --check-reminder 2>/dev/null
98
- ${endMarker}
268
+ ${END_MARKER}
99
269
  `;
100
270
  try {
101
271
  let content = "";
@@ -104,36 +274,44 @@ ${endMarker}
104
274
  content = readFileSync(configFile, "utf-8");
105
275
  action = "updated";
106
276
  }
107
- const hasStartMarker = content.includes(startMarker);
108
- const hasEndMarker = content.includes(endMarker);
109
- if (hasStartMarker && hasEndMarker) {
110
- const startIndex = content.indexOf(startMarker);
111
- const endIndex = content.indexOf(endMarker) + endMarker.length;
112
- const before = content.slice(0, startIndex);
113
- const after = content.slice(endIndex);
114
- const beforeTrimmed = before.endsWith("\n") ? before.slice(0, -1) : before;
115
- content = `${beforeTrimmed}
116
- ${configBlock}${after}`.trim() + "\n";
117
- } else if (hasStartMarker || hasEndMarker) {
118
- const startIndex = hasStartMarker ? content.indexOf(startMarker) : content.indexOf(endMarker);
119
- const endIndex = hasEndMarker ? content.indexOf(endMarker) + endMarker.length : content.indexOf(startMarker) + startMarker.length;
120
- const before = content.slice(0, startIndex);
121
- const after = content.slice(endIndex);
277
+ const positions = findMarkerPositions(content);
278
+ if (positions.startIndex === -1 && positions.endIndex === -1) {
279
+ const separator = content && !content.endsWith("\n") ? "\n\n" : "\n";
280
+ content = `${content}${separator}${configBlock}`;
281
+ } else if (positions.isValid) {
282
+ const before = content.slice(0, positions.startIndex);
283
+ const after = content.slice(positions.endIndex + END_MARKER.length);
122
284
  const beforeTrimmed = before.endsWith("\n") ? before.slice(0, -1) : before;
123
285
  content = `${beforeTrimmed}
124
286
  ${configBlock}${after}`.trim() + "\n";
125
287
  } else {
126
- const separator = content && !content.endsWith("\n") ? "\n\n" : "\n";
127
- content = `${content}${separator}${configBlock}`;
288
+ logger.collectWarning(
289
+ `Found malformed Hyntx block in ${configFile} (${positions.issue ?? "unknown"}). Rebuilding configuration.`,
290
+ "shell-config"
291
+ );
292
+ const cleanedContent = removeMalformedMarkers(content, positions);
293
+ const separator = cleanedContent && !cleanedContent.endsWith("\n") ? "\n\n" : "\n";
294
+ content = `${cleanedContent}${separator}${configBlock}`;
128
295
  }
129
296
  try {
130
297
  mkdirSync(dirname(configFile), { recursive: true });
131
- } catch {
298
+ } catch (error) {
299
+ if (error instanceof Error && !error.message.includes("EEXIST") && !error.code?.includes("EEXIST")) {
300
+ logger.debug(
301
+ `Directory creation note: ${error.message}`,
302
+ "shell-config"
303
+ );
304
+ }
132
305
  }
133
306
  writeFileSync(configFile, content, "utf-8");
134
307
  try {
135
308
  chmodSync(configFile, 384);
136
- } catch {
309
+ } catch (error) {
310
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
311
+ logger.collectWarning(
312
+ `Could not set restrictive permissions on ${configFile}: ${errorMessage}`,
313
+ "shell-config"
314
+ );
137
315
  }
138
316
  return {
139
317
  success: true,
@@ -171,8 +349,12 @@ function getManualInstructions(config) {
171
349
  ];
172
350
  return instructions.join("\n");
173
351
  }
352
+ var START_MARKER, END_MARKER;
174
353
  var init_shell_config = __esm({
175
354
  "src/utils/shell-config.ts"() {
355
+ init_logger();
356
+ START_MARKER = "# >>> hyntx config >>>";
357
+ END_MARKER = "# <<< hyntx config <<<";
176
358
  }
177
359
  });
178
360
 
@@ -238,8 +420,9 @@ function getEnvConfig() {
238
420
  };
239
421
  }
240
422
  var HOME = homedir();
241
- var CLAUDE_PROJECTS_DIR = join(HOME, ".claude", "projects");
242
- join(HOME, ".hyntx-last-run");
423
+ var CLAUDE_PROJECTS_DIR = process.env["HYNTX_CLAUDE_PROJECTS_DIR"] ?? join(HOME, ".claude", "projects");
424
+ var LAST_RUN_FILE = join(HOME, ".hyntx-last-run");
425
+ var HYNTX_HISTORY_DIR = process.env["HYNTX_HISTORY_DIR"] ?? join(HOME, ".hyntx", "history");
243
426
 
244
427
  // src/core/schema-validator.ts
245
428
  var SUPPORTED_VERSIONS = ["1.0"];
@@ -344,6 +527,7 @@ function validateLogEntry(entry) {
344
527
  }
345
528
 
346
529
  // src/core/log-reader.ts
530
+ init_logger();
347
531
  function claudeProjectsExist() {
348
532
  return existsSync(CLAUDE_PROJECTS_DIR);
349
533
  }
@@ -387,18 +571,36 @@ function extractDate(timestamp) {
387
571
  return "unknown";
388
572
  }
389
573
  }
390
- function parseLine(line) {
574
+ function isClaudeMessage(value) {
575
+ if (typeof value !== "object" || value === null) {
576
+ return false;
577
+ }
578
+ const obj = value;
579
+ return typeof obj["timestamp"] === "string" && typeof obj["type"] === "string" && typeof obj["message"] === "object" && obj["message"] !== null && typeof obj["message"]["content"] === "string";
580
+ }
581
+ function parseLine(line, lineNumber, filePath) {
391
582
  if (!line.trim()) {
392
583
  return null;
393
584
  }
585
+ const context = lineNumber !== void 0 && filePath ? `${filePath}:${String(lineNumber)}` : void 0;
394
586
  try {
395
587
  const parsed = JSON.parse(line);
396
588
  const validation = validateLogEntry(parsed);
397
589
  if (!validation.isValid) {
590
+ logger.debug(
591
+ `Schema validation failed: ${validation.warning ?? "Unknown format"}`,
592
+ context
593
+ );
594
+ return null;
595
+ }
596
+ if (!isClaudeMessage(parsed)) {
597
+ logger.debug("Type guard validation failed", context);
398
598
  return null;
399
599
  }
400
600
  return parsed;
401
- } catch {
601
+ } catch (error) {
602
+ const errorMessage = error instanceof Error ? error.message : "Parse error";
603
+ logger.debug(`JSON parse failed: ${errorMessage}`, context);
402
604
  return null;
403
605
  }
404
606
  }
@@ -406,25 +608,23 @@ function isUserMessage(message) {
406
608
  return message.type === "user" && message.message.role === "user";
407
609
  }
408
610
  function extractContent(message) {
409
- const content = message.message.content;
410
- if (typeof content === "string") {
411
- return content;
412
- }
413
- return "";
611
+ return message.message.content;
414
612
  }
415
613
  async function readJsonlFile(filePath) {
416
- const prompts2 = [];
614
+ const prompts3 = [];
417
615
  const warnings = [];
418
616
  const projectName = extractProjectName(filePath);
419
617
  try {
420
618
  const content = await readFile(filePath, "utf-8");
421
619
  const lines = content.split("\n");
620
+ let skippedLines = 0;
422
621
  for (let i = 0; i < lines.length; i++) {
423
622
  const line = lines[i] ?? "";
424
- const message = parseLine(line);
623
+ const lineNumber = i + 1;
624
+ const message = parseLine(line, lineNumber, filePath);
425
625
  if (message === null) {
426
626
  if (line.trim()) {
427
- warnings.push(`Skipped invalid line ${String(i + 1)} in ${filePath}`);
627
+ skippedLines++;
428
628
  }
429
629
  continue;
430
630
  }
@@ -435,7 +635,7 @@ async function readJsonlFile(filePath) {
435
635
  if (!extractedContent.trim()) {
436
636
  continue;
437
637
  }
438
- prompts2.push({
638
+ prompts3.push({
439
639
  content: extractedContent,
440
640
  timestamp: message.timestamp,
441
641
  sessionId: message.sessionId,
@@ -443,41 +643,109 @@ async function readJsonlFile(filePath) {
443
643
  date: extractDate(message.timestamp)
444
644
  });
445
645
  }
646
+ if (skippedLines > 0) {
647
+ const warning = `Skipped ${String(skippedLines)} invalid line(s) in ${filePath}`;
648
+ warnings.push(warning);
649
+ logger.collectWarning(warning, "log-reader");
650
+ }
446
651
  } catch (error) {
447
652
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
448
- warnings.push(`Failed to read ${filePath}: ${errorMessage}`);
653
+ const warning = `Failed to read ${filePath}: ${errorMessage}`;
654
+ warnings.push(warning);
655
+ logger.error(warning, "log-reader");
449
656
  }
450
- return { prompts: prompts2, warnings };
657
+ return { prompts: prompts3, warnings };
451
658
  }
452
- function filterByDateRange(prompts2, fromDate, toDate) {
453
- return prompts2.filter((prompt) => {
659
+ function filterByDateRange(prompts3, fromDate, toDate) {
660
+ return prompts3.filter((prompt) => {
454
661
  try {
455
662
  const promptDate = parseISO(prompt.timestamp);
456
663
  const promptDay = startOfDay(promptDate);
457
664
  return (isSameDay(promptDay, fromDate) || isAfter(promptDay, fromDate)) && (isSameDay(promptDay, toDate) || isBefore(promptDay, toDate));
458
- } catch {
665
+ } catch (error) {
666
+ const errorMessage = error instanceof Error ? error.message : "Parse error";
667
+ logger.debug(
668
+ `Invalid timestamp in filterByDateRange: ${prompt.timestamp} - ${errorMessage}`,
669
+ "log-reader"
670
+ );
459
671
  return false;
460
672
  }
461
673
  });
462
674
  }
463
- function filterByDate(prompts2, targetDate) {
464
- return prompts2.filter((prompt) => {
675
+ function filterByDate(prompts3, targetDate) {
676
+ return prompts3.filter((prompt) => {
465
677
  try {
466
678
  const promptDate = parseISO(prompt.timestamp);
467
679
  return isSameDay(startOfDay(promptDate), targetDate);
468
- } catch {
680
+ } catch (error) {
681
+ const errorMessage = error instanceof Error ? error.message : "Parse error";
682
+ logger.debug(
683
+ `Invalid timestamp in filterByDate: ${prompt.timestamp} - ${errorMessage}`,
684
+ "log-reader"
685
+ );
469
686
  return false;
470
687
  }
471
688
  });
472
689
  }
473
- function filterByProject(prompts2, projectName) {
690
+ function filterByProject(prompts3, projectName) {
474
691
  const normalizedProject = projectName.toLowerCase().trim();
475
- return prompts2.filter(
692
+ return prompts3.filter(
476
693
  (prompt) => prompt.project.toLowerCase().includes(normalizedProject)
477
694
  );
478
695
  }
696
+ function groupByDay(prompts3) {
697
+ const groups = /* @__PURE__ */ new Map();
698
+ for (const prompt of prompts3) {
699
+ const date = prompt.date;
700
+ if (!groups.has(date)) {
701
+ groups.set(date, { prompts: [], projects: /* @__PURE__ */ new Set() });
702
+ }
703
+ const group = groups.get(date);
704
+ if (group) {
705
+ group.prompts.push(prompt);
706
+ group.projects.add(prompt.project);
707
+ }
708
+ }
709
+ const result = Array.from(groups.entries()).map(([date, { prompts: groupPrompts, projects }]) => {
710
+ const sortedPrompts = groupPrompts.sort((a, b) => {
711
+ try {
712
+ const dateA = parseISO(a.timestamp);
713
+ const dateB = parseISO(b.timestamp);
714
+ return dateA.getTime() - dateB.getTime();
715
+ } catch (error) {
716
+ const errorMessage = error instanceof Error ? error.message : "Parse error";
717
+ logger.debug(
718
+ `Invalid timestamp in groupByDay sort: ${a.timestamp} or ${b.timestamp} - ${errorMessage}`,
719
+ "log-reader"
720
+ );
721
+ return 0;
722
+ }
723
+ });
724
+ return {
725
+ date,
726
+ prompts: sortedPrompts,
727
+ projects: Array.from(projects).sort()
728
+ };
729
+ }).sort((a, b) => {
730
+ try {
731
+ const dateA = parseISO(a.date + "T00:00:00Z");
732
+ const dateB = parseISO(b.date + "T00:00:00Z");
733
+ return dateA.getTime() - dateB.getTime();
734
+ } catch (error) {
735
+ const errorMessage = error instanceof Error ? error.message : "Parse error";
736
+ logger.debug(
737
+ `Invalid date in groupByDay sort: ${a.date} or ${b.date} - ${errorMessage}`,
738
+ "log-reader"
739
+ );
740
+ return 0;
741
+ }
742
+ });
743
+ return result;
744
+ }
479
745
  async function readLogs(options) {
746
+ logger.debug(`Scanning ${CLAUDE_PROJECTS_DIR}`, "log-reader");
480
747
  if (!claudeProjectsExist()) {
748
+ logger.debug("Claude projects directory not found", "log-reader");
481
749
  return {
482
750
  prompts: [],
483
751
  warnings: [
@@ -486,7 +754,19 @@ async function readLogs(options) {
486
754
  };
487
755
  }
488
756
  const pattern = `${CLAUDE_PROJECTS_DIR}/**/*.jsonl`;
489
- const files = await glob(pattern);
757
+ let files;
758
+ try {
759
+ files = await glob(pattern);
760
+ } catch (error) {
761
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
762
+ const warning = `Failed to search for JSONL files: ${errorMessage}`;
763
+ logger.error(warning, "log-reader");
764
+ return {
765
+ prompts: [],
766
+ warnings: [warning]
767
+ };
768
+ }
769
+ logger.debug(`Found ${String(files.length)} JSONL files`, "log-reader");
490
770
  if (files.length === 0) {
491
771
  return {
492
772
  prompts: [],
@@ -495,11 +775,19 @@ async function readLogs(options) {
495
775
  }
496
776
  const allPrompts = [];
497
777
  const allWarnings = [];
498
- for (const file of files) {
499
- const { prompts: prompts2, warnings } = await readJsonlFile(file);
500
- allPrompts.push(...prompts2);
501
- allWarnings.push(...warnings);
778
+ const CONCURRENCY_LIMIT = 10;
779
+ for (let i = 0; i < files.length; i += CONCURRENCY_LIMIT) {
780
+ const chunk = files.slice(i, i + CONCURRENCY_LIMIT);
781
+ const results = await Promise.all(chunk.map(readJsonlFile));
782
+ for (const { prompts: prompts3, warnings } of results) {
783
+ allPrompts.push(...prompts3);
784
+ allWarnings.push(...warnings);
785
+ }
502
786
  }
787
+ logger.debug(
788
+ `Parsed ${String(allPrompts.length)} total prompts from all files`,
789
+ "log-reader"
790
+ );
503
791
  let filteredPrompts = allPrompts;
504
792
  if (options) {
505
793
  if (options.from && options.to) {
@@ -539,15 +827,33 @@ async function readLogs(options) {
539
827
  filteredPrompts = filterByProject(filteredPrompts, options.project);
540
828
  }
541
829
  }
830
+ if (options) {
831
+ const filtered = allPrompts.length - filteredPrompts.length;
832
+ if (filtered > 0) {
833
+ logger.debug(
834
+ `Filtered ${String(filtered)} prompts (${String(filteredPrompts.length)} remaining)`,
835
+ "log-reader"
836
+ );
837
+ }
838
+ }
542
839
  const sortedPrompts = filteredPrompts.sort((a, b) => {
543
840
  try {
544
841
  const dateA = parseISO(a.timestamp);
545
842
  const dateB = parseISO(b.timestamp);
546
843
  return dateA.getTime() - dateB.getTime();
547
- } catch {
844
+ } catch (error) {
845
+ const errorMessage = error instanceof Error ? error.message : "Parse error";
846
+ logger.debug(
847
+ `Invalid timestamp in readLogs sort: ${a.timestamp} or ${b.timestamp} - ${errorMessage}`,
848
+ "log-reader"
849
+ );
548
850
  return 0;
549
851
  }
550
852
  });
853
+ logger.debug(
854
+ `Returning ${String(sortedPrompts.length)} prompts for analysis`,
855
+ "log-reader"
856
+ );
551
857
  return {
552
858
  prompts: sortedPrompts,
553
859
  warnings: allWarnings
@@ -585,12 +891,20 @@ async function configureProvider(provider, config) {
585
891
  message: "Ollama model to use:",
586
892
  initial: ENV_DEFAULTS.ollama.model
587
893
  });
894
+ if (!("model" in response2)) {
895
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
896
+ process.exit(EXIT_CODES.ERROR);
897
+ }
588
898
  const hostResponse = await prompts({
589
899
  type: "text",
590
900
  name: "host",
591
901
  message: "Ollama host:",
592
902
  initial: ENV_DEFAULTS.ollama.host
593
903
  });
904
+ if (!("host" in hostResponse)) {
905
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
906
+ process.exit(EXIT_CODES.ERROR);
907
+ }
594
908
  return {
595
909
  ...config,
596
910
  ollama: {
@@ -606,12 +920,20 @@ async function configureProvider(provider, config) {
606
920
  message: "Anthropic model to use:",
607
921
  initial: ENV_DEFAULTS.anthropic.model
608
922
  });
923
+ if (!("model" in response2)) {
924
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
925
+ process.exit(EXIT_CODES.ERROR);
926
+ }
609
927
  const apiKeyResponse2 = await prompts({
610
928
  type: "password",
611
929
  name: "apiKey",
612
930
  message: "Anthropic API key:",
613
931
  validate: (value) => value.trim() !== "" || "API key is required"
614
932
  });
933
+ if (!("apiKey" in apiKeyResponse2)) {
934
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
935
+ process.exit(EXIT_CODES.ERROR);
936
+ }
615
937
  return {
616
938
  ...config,
617
939
  anthropic: {
@@ -626,12 +948,20 @@ async function configureProvider(provider, config) {
626
948
  message: "Google model to use:",
627
949
  initial: ENV_DEFAULTS.google.model
628
950
  });
951
+ if (!("model" in response)) {
952
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
953
+ process.exit(EXIT_CODES.ERROR);
954
+ }
629
955
  const apiKeyResponse = await prompts({
630
956
  type: "password",
631
957
  name: "apiKey",
632
958
  message: "Google API key:",
633
959
  validate: (value) => value.trim() !== "" || "API key is required"
634
960
  });
961
+ if (!("apiKey" in apiKeyResponse)) {
962
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
963
+ process.exit(EXIT_CODES.ERROR);
964
+ }
635
965
  return {
636
966
  ...config,
637
967
  google: {
@@ -642,12 +972,12 @@ async function configureProvider(provider, config) {
642
972
  }
643
973
  function showManualInstructions(config) {
644
974
  const instructions = getManualInstructions(config);
645
- console.log("\n" + chalk3.green("\u2705 Setup complete!"));
975
+ console.log("\n" + chalk6.green("\u2705 Setup complete!"));
646
976
  console.log("\n" + instructions + "\n");
647
977
  }
648
978
  async function runSetup() {
649
979
  console.log(
650
- boxen2(chalk3.bold("\u{1F44B} Welcome to Hyntx!"), {
980
+ boxen2(chalk6.bold("\u{1F44B} Welcome to Hyntx!"), {
651
981
  padding: 1,
652
982
  borderColor: "cyan"
653
983
  })
@@ -662,8 +992,8 @@ async function runSetup() {
662
992
  });
663
993
  const providers = providerResponse.providers;
664
994
  if (!providers || providers.length === 0) {
665
- console.log(chalk3.red("No providers selected. Setup cancelled."));
666
- process.exit(1);
995
+ console.log(chalk6.red("No providers selected. Setup cancelled."));
996
+ process.exit(EXIT_CODES.ERROR);
667
997
  }
668
998
  let config = {
669
999
  services: providers,
@@ -689,6 +1019,10 @@ async function runSetup() {
689
1019
  initial: 1
690
1020
  // Default to 7d
691
1021
  });
1022
+ if (!("reminder" in reminderResponse)) {
1023
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
1024
+ process.exit(EXIT_CODES.ERROR);
1025
+ }
692
1026
  const reminder = reminderResponse.reminder;
693
1027
  if (reminder && reminder !== "never") {
694
1028
  config = { ...config, reminder };
@@ -715,18 +1049,22 @@ async function runSetup() {
715
1049
  message: `Save configuration to ${configFile}?`,
716
1050
  initial: true
717
1051
  });
1052
+ if (!("saveToShell" in saveToShellResponse)) {
1053
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
1054
+ process.exit(EXIT_CODES.ERROR);
1055
+ }
718
1056
  const saveToShell = saveToShellResponse.saveToShell ?? false;
719
1057
  if (saveToShell) {
720
1058
  const result = saveConfigToShell(config);
721
1059
  if (result.success) {
722
- console.log("\n" + chalk3.green("\u2705 " + result.message));
1060
+ console.log("\n" + chalk6.green("\u2705 " + result.message));
723
1061
  console.log(
724
- chalk3.dim(
1062
+ chalk6.dim(
725
1063
  " Run 'source " + result.shellFile + "' or open a new terminal to apply."
726
1064
  )
727
1065
  );
728
1066
  } else {
729
- console.log("\n" + chalk3.yellow("\u26A0\uFE0F " + result.message));
1067
+ console.log("\n" + chalk6.yellow("\u26A0\uFE0F " + result.message));
730
1068
  showManualInstructions(config);
731
1069
  }
732
1070
  } else {
@@ -736,6 +1074,7 @@ async function runSetup() {
736
1074
  }
737
1075
 
738
1076
  // src/core/sanitizer.ts
1077
+ init_logger();
739
1078
  function redactOpenAIKeys(text) {
740
1079
  return text.replace(/sk-[a-zA-Z0-9]{48,}/g, "[REDACTED_OPENAI_KEY]");
741
1080
  }
@@ -946,17 +1285,29 @@ function sanitize(text) {
946
1285
  redacted
947
1286
  };
948
1287
  }
949
- function sanitizePrompts(prompts2) {
950
- if (prompts2.length === 0) {
1288
+ function sanitizePrompts(prompts3) {
1289
+ if (prompts3.length === 0) {
951
1290
  return { prompts: [], totalRedacted: 0 };
952
1291
  }
1292
+ logger.debug(
1293
+ `Sanitizing ${String(prompts3.length)} prompts for secrets`,
1294
+ "sanitizer"
1295
+ );
953
1296
  const sanitizedPrompts = [];
954
1297
  let totalRedacted = 0;
955
- for (const prompt of prompts2) {
1298
+ for (const prompt of prompts3) {
956
1299
  const result = sanitize(prompt);
957
1300
  sanitizedPrompts.push(result.text);
958
1301
  totalRedacted += result.redacted;
959
1302
  }
1303
+ if (totalRedacted > 0) {
1304
+ logger.debug(
1305
+ `Redacted ${String(totalRedacted)} secret(s) from prompts`,
1306
+ "sanitizer"
1307
+ );
1308
+ } else {
1309
+ logger.debug("No secrets found to redact", "sanitizer");
1310
+ }
960
1311
  return {
961
1312
  prompts: sanitizedPrompts,
962
1313
  totalRedacted
@@ -964,6 +1315,7 @@ function sanitizePrompts(prompts2) {
964
1315
  }
965
1316
 
966
1317
  // src/core/analyzer.ts
1318
+ init_logger();
967
1319
  var SYSTEM_OVERHEAD_TOKENS = 2e3;
968
1320
  var SEVERITY_RANK = {
969
1321
  high: 3,
@@ -1019,12 +1371,12 @@ function estimateTokens(text) {
1019
1371
  return Math.ceil(text.length / CHARS_PER_TOKEN);
1020
1372
  }
1021
1373
  function batchPrompts(options) {
1022
- const { prompts: prompts2, maxTokensPerBatch, prioritization } = options;
1023
- if (prompts2.length === 0) {
1374
+ const { prompts: prompts3, maxTokensPerBatch, prioritization } = options;
1375
+ if (prompts3.length === 0) {
1024
1376
  return [];
1025
1377
  }
1026
1378
  const effectiveLimit = maxTokensPerBatch - SYSTEM_OVERHEAD_TOKENS;
1027
- const promptsWithTokens = prompts2.map((prompt) => ({
1379
+ const promptsWithTokens = prompts3.map((prompt) => ({
1028
1380
  prompt,
1029
1381
  tokens: estimateTokens(prompt)
1030
1382
  }));
@@ -1144,18 +1496,36 @@ function mergeBatchResults(options) {
1144
1496
  };
1145
1497
  }
1146
1498
  async function analyzePrompts(options) {
1147
- const { provider, prompts: prompts2, date, onProgress } = options;
1148
- if (prompts2.length === 0) {
1499
+ const { provider, prompts: prompts3, date, context, onProgress } = options;
1500
+ logger.debug(
1501
+ `Starting analysis of ${String(prompts3.length)} prompts for ${date}`,
1502
+ "analyzer"
1503
+ );
1504
+ if (prompts3.length === 0) {
1149
1505
  throw new Error("Cannot analyze empty prompts array");
1150
1506
  }
1151
- const { prompts: sanitizedPrompts } = sanitizePrompts(prompts2);
1507
+ const { prompts: sanitizedPrompts, totalRedacted } = sanitizePrompts(prompts3);
1508
+ if (totalRedacted > 0) {
1509
+ logger.debug(
1510
+ `Sanitizer redacted ${String(totalRedacted)} secrets`,
1511
+ "analyzer"
1512
+ );
1513
+ }
1152
1514
  const providerType = inferProviderType(provider.name);
1153
1515
  const limits = PROVIDER_LIMITS[providerType];
1516
+ logger.debug(
1517
+ `Using provider type: ${providerType} (limit: ${String(limits.maxTokensPerBatch)} tokens/batch)`,
1518
+ "analyzer"
1519
+ );
1154
1520
  const batches = batchPrompts({
1155
1521
  prompts: sanitizedPrompts,
1156
1522
  maxTokensPerBatch: limits.maxTokensPerBatch,
1157
1523
  prioritization: limits.prioritization
1158
1524
  });
1525
+ logger.debug(
1526
+ `Created ${String(batches.length)} batch(es) for analysis`,
1527
+ "analyzer"
1528
+ );
1159
1529
  if (batches.length === 1) {
1160
1530
  const batch = batches[0];
1161
1531
  if (!batch) {
@@ -1164,10 +1534,21 @@ async function analyzePrompts(options) {
1164
1534
  if (onProgress) {
1165
1535
  onProgress(0, 1);
1166
1536
  }
1167
- const result = await provider.analyze(batch.prompts, date);
1537
+ logger.debug(
1538
+ `Processing single batch (${String(batch.tokens)} tokens)`,
1539
+ "analyzer"
1540
+ );
1541
+ const startTime = Date.now();
1542
+ const result = await provider.analyze(batch.prompts, date, context);
1543
+ const elapsed = Date.now() - startTime;
1544
+ logger.debug(`Batch completed in ${String(elapsed)}ms`, "analyzer");
1168
1545
  if (onProgress) {
1169
1546
  onProgress(1, 1);
1170
1547
  }
1548
+ logger.debug(
1549
+ `Analysis complete: ${String(result.patterns.length)} patterns found`,
1550
+ "analyzer"
1551
+ );
1171
1552
  return result;
1172
1553
  }
1173
1554
  const results = [];
@@ -1178,13 +1559,29 @@ async function analyzePrompts(options) {
1178
1559
  if (onProgress) {
1179
1560
  onProgress(i, totalBatches);
1180
1561
  }
1181
- const result = await provider.analyze(batch.prompts, date);
1562
+ logger.debug(
1563
+ `Processing batch ${String(i + 1)}/${String(totalBatches)} (${String(batch.tokens)} tokens)`,
1564
+ "analyzer"
1565
+ );
1566
+ const startTime = Date.now();
1567
+ const result = await provider.analyze(batch.prompts, date, context);
1182
1568
  results.push(result);
1569
+ const elapsed = Date.now() - startTime;
1570
+ logger.debug(
1571
+ `Batch ${String(i + 1)}/${String(totalBatches)} completed in ${String(elapsed)}ms`,
1572
+ "analyzer"
1573
+ );
1183
1574
  }
1184
1575
  if (onProgress) {
1185
1576
  onProgress(totalBatches, totalBatches);
1186
1577
  }
1187
- return mergeBatchResults({ results, date });
1578
+ logger.debug(`Merging ${String(results.length)} batch results`, "analyzer");
1579
+ const mergedResult = mergeBatchResults({ results, date });
1580
+ logger.debug(
1581
+ `Analysis complete: ${String(mergedResult.patterns.length)} patterns found`,
1582
+ "analyzer"
1583
+ );
1584
+ return mergedResult;
1188
1585
  }
1189
1586
  function severityIcon(severity) {
1190
1587
  const icons = {
@@ -1196,12 +1593,12 @@ function severityIcon(severity) {
1196
1593
  }
1197
1594
  function scoreColor(score, text) {
1198
1595
  if (score >= 8) {
1199
- return chalk3.green(text);
1596
+ return chalk6.green(text);
1200
1597
  }
1201
1598
  if (score >= 6) {
1202
- return chalk3.yellow(text);
1599
+ return chalk6.yellow(text);
1203
1600
  }
1204
- return chalk3.red(text);
1601
+ return chalk6.red(text);
1205
1602
  }
1206
1603
  function truncateText(text, maxLength) {
1207
1604
  if (text.length <= maxLength) {
@@ -1221,16 +1618,16 @@ function formatHeader(title) {
1221
1618
  font: "Standard",
1222
1619
  horizontalLayout: "default"
1223
1620
  });
1224
- return chalk3.cyan(ascii);
1621
+ return chalk6.cyan(ascii);
1225
1622
  } catch {
1226
- return chalk3.cyan.bold(`
1623
+ return chalk6.cyan.bold(`
1227
1624
  ${headerText}
1228
1625
  `);
1229
1626
  }
1230
1627
  }
1231
1628
  function formatStats(stats, projectCount) {
1232
1629
  const table = new Table({
1233
- head: [chalk3.bold("Metric"), chalk3.bold("Value")],
1630
+ head: [chalk6.bold("Metric"), chalk6.bold("Value")],
1234
1631
  colWidths: [30, 20]
1235
1632
  });
1236
1633
  table.push(
@@ -1246,25 +1643,25 @@ function formatStats(stats, projectCount) {
1246
1643
  function formatPattern(pattern, index) {
1247
1644
  const lines = [];
1248
1645
  lines.push(
1249
- chalk3.bold(
1646
+ chalk6.bold(
1250
1647
  `${String(index + 1)}. ${severityIcon(pattern.severity)} ${pattern.name}`
1251
1648
  )
1252
1649
  );
1253
1650
  lines.push(
1254
- chalk3.dim(
1651
+ chalk6.dim(
1255
1652
  ` Frequency: ${String(pattern.frequency)} | Severity: ${pattern.severity}`
1256
1653
  )
1257
1654
  );
1258
1655
  lines.push("");
1259
1656
  if (pattern.examples.length > 0) {
1260
- lines.push(chalk3.yellow(" Examples:"));
1657
+ lines.push(chalk6.yellow(" Examples:"));
1261
1658
  for (const example of pattern.examples) {
1262
- lines.push(chalk3.dim(` \u2022 ${example}`));
1659
+ lines.push(chalk6.dim(` \u2022 ${example}`));
1263
1660
  }
1264
1661
  lines.push("");
1265
1662
  }
1266
- lines.push(chalk3.green(" Suggestion:"));
1267
- lines.push(chalk3.dim(` ${pattern.suggestion}`));
1663
+ lines.push(chalk6.green(" Suggestion:"));
1664
+ lines.push(chalk6.dim(` ${pattern.suggestion}`));
1268
1665
  return boxen2(lines.join("\n"), {
1269
1666
  padding: 1,
1270
1667
  borderColor: pattern.severity === "high" ? "red" : "yellow",
@@ -1273,14 +1670,14 @@ function formatPattern(pattern, index) {
1273
1670
  }
1274
1671
  function formatBeforeAfter(beforeAfter) {
1275
1672
  const sections = [];
1276
- const beforeBox = boxen2(chalk3.red(beforeAfter.before), {
1673
+ const beforeBox = boxen2(chalk6.red(beforeAfter.before), {
1277
1674
  padding: 1,
1278
1675
  borderColor: "red",
1279
1676
  borderStyle: "round",
1280
1677
  title: "\u274C Before"
1281
1678
  });
1282
1679
  sections.push(beforeBox);
1283
- const afterBox = boxen2(chalk3.green(beforeAfter.after), {
1680
+ const afterBox = boxen2(chalk6.green(beforeAfter.after), {
1284
1681
  padding: 1,
1285
1682
  borderColor: "green",
1286
1683
  borderStyle: "round",
@@ -1290,7 +1687,7 @@ function formatBeforeAfter(beforeAfter) {
1290
1687
  return sections.join("\n\n");
1291
1688
  }
1292
1689
  function formatTopSuggestion(suggestion) {
1293
- return boxen2(chalk3.cyan.bold(suggestion), {
1690
+ return boxen2(chalk6.cyan.bold(suggestion), {
1294
1691
  padding: 1,
1295
1692
  borderColor: "cyan",
1296
1693
  borderStyle: "double",
@@ -1306,7 +1703,7 @@ function printReport(result, options) {
1306
1703
  output.push(formatHeader());
1307
1704
  output.push("");
1308
1705
  }
1309
- output.push(chalk3.bold("\u{1F4CA} Statistics"));
1706
+ output.push(chalk6.bold("\u{1F4CA} Statistics"));
1310
1707
  output.push("");
1311
1708
  output.push(formatStats(result.stats));
1312
1709
  output.push("");
@@ -1315,7 +1712,7 @@ function printReport(result, options) {
1315
1712
  output.push("");
1316
1713
  }
1317
1714
  if (result.patterns.length > 0) {
1318
- output.push(chalk3.bold("\u{1F50D} Detected Patterns"));
1715
+ output.push(chalk6.bold("\u{1F50D} Detected Patterns"));
1319
1716
  output.push("");
1320
1717
  for (const [index, pattern] of result.patterns.entries()) {
1321
1718
  const truncatedPattern = {
@@ -1337,13 +1734,256 @@ function printReport(result, options) {
1337
1734
  }
1338
1735
  }
1339
1736
  } else {
1340
- output.push(chalk3.green("\u2705 No issues detected!"));
1737
+ output.push(chalk6.green("\u2705 No issues detected!"));
1738
+ output.push("");
1739
+ }
1740
+ output.push(chalk6.dim(`Analysis Date: ${result.date}`));
1741
+ console.log(output.join("\n"));
1742
+ }
1743
+ function formatJson(result, compact = false) {
1744
+ return compact ? JSON.stringify(result) : JSON.stringify(result, null, 2);
1745
+ }
1746
+ function severityIconMarkdown(severity) {
1747
+ const icons = {
1748
+ high: "\u{1F534}",
1749
+ medium: "\u{1F7E1}",
1750
+ low: "\u{1F7E2}"
1751
+ };
1752
+ return icons[severity];
1753
+ }
1754
+ function formatMarkdown(result) {
1755
+ const lines = [];
1756
+ lines.push("# Hyntx Analysis Report");
1757
+ lines.push("");
1758
+ lines.push(`**Date:** ${result.date}`);
1759
+ lines.push("");
1760
+ lines.push("## Statistics");
1761
+ lines.push("");
1762
+ lines.push("| Metric | Value |");
1763
+ lines.push("|--------|-------|");
1764
+ lines.push(`| Total Prompts | ${String(result.stats.totalPrompts)} |`);
1765
+ lines.push(
1766
+ `| Prompts with Issues | ${String(result.stats.promptsWithIssues)} |`
1767
+ );
1768
+ lines.push(`| Overall Score | ${String(result.stats.overallScore)}/10 |`);
1769
+ lines.push("");
1770
+ if (result.topSuggestion) {
1771
+ lines.push("## Top Suggestion");
1772
+ lines.push("");
1773
+ lines.push(`> \u{1F4A1} ${result.topSuggestion}`);
1774
+ lines.push("");
1775
+ }
1776
+ if (result.patterns.length > 0) {
1777
+ lines.push("## Detected Patterns");
1778
+ lines.push("");
1779
+ for (const [index, pattern] of result.patterns.entries()) {
1780
+ lines.push(
1781
+ `### ${String(index + 1)}. ${severityIconMarkdown(pattern.severity)} ${pattern.name}`
1782
+ );
1783
+ lines.push("");
1784
+ lines.push(
1785
+ `**Frequency:** ${String(pattern.frequency)} | **Severity:** ${pattern.severity}`
1786
+ );
1787
+ lines.push("");
1788
+ if (pattern.examples.length > 0) {
1789
+ lines.push("**Examples:**");
1790
+ lines.push("");
1791
+ for (const example of pattern.examples) {
1792
+ lines.push(`- ${example}`);
1793
+ }
1794
+ lines.push("");
1795
+ }
1796
+ lines.push("**Suggestion:**");
1797
+ lines.push("");
1798
+ lines.push(pattern.suggestion);
1799
+ lines.push("");
1800
+ lines.push("**Before/After:**");
1801
+ lines.push("");
1802
+ lines.push("> \u274C **Before:**");
1803
+ lines.push(">");
1804
+ for (const line of pattern.beforeAfter.before.split("\n")) {
1805
+ lines.push(`> ${line}`);
1806
+ }
1807
+ lines.push("");
1808
+ lines.push("> \u2705 **After:**");
1809
+ lines.push(">");
1810
+ for (const line of pattern.beforeAfter.after.split("\n")) {
1811
+ lines.push(`> ${line}`);
1812
+ }
1813
+ lines.push("");
1814
+ lines.push("---");
1815
+ lines.push("");
1816
+ }
1817
+ } else {
1818
+ lines.push("## Results");
1819
+ lines.push("");
1820
+ lines.push("\u2705 No issues detected! Your prompts look great.");
1821
+ lines.push("");
1822
+ }
1823
+ lines.push("---");
1824
+ lines.push("");
1825
+ lines.push("*Generated by [Hyntx](https://github.com/hyntx/hyntx)*");
1826
+ return lines.join("\n");
1827
+ }
1828
+ function scoreDeltaIndicator(delta) {
1829
+ if (delta > 0) {
1830
+ return chalk6.green(`\u2191 +${delta.toFixed(1)}`);
1831
+ }
1832
+ if (delta < 0) {
1833
+ return chalk6.red(`\u2193 ${delta.toFixed(1)}`);
1834
+ }
1835
+ return chalk6.dim("\u2192 0.0");
1836
+ }
1837
+ function printComparison(comparison) {
1838
+ const output = [];
1839
+ output.push("");
1840
+ output.push(
1841
+ chalk6.bold.cyan(
1842
+ `Comparison: ${comparison.before.date} \u2192 ${comparison.after.date}`
1843
+ )
1844
+ );
1845
+ output.push("");
1846
+ const delta = comparison.changes.scoreDelta;
1847
+ output.push(chalk6.bold("\u{1F4CA} Score Change"));
1848
+ output.push("");
1849
+ output.push(
1850
+ ` Before: ${scoreColor(comparison.before.stats.overallScore, comparison.before.stats.overallScore.toFixed(1))}/10`
1851
+ );
1852
+ output.push(
1853
+ ` After: ${scoreColor(comparison.after.stats.overallScore, comparison.after.stats.overallScore.toFixed(1))}/10`
1854
+ );
1855
+ output.push(` Change: ${scoreDeltaIndicator(delta)}`);
1856
+ output.push("");
1857
+ if (comparison.changes.newPatterns.length > 0) {
1858
+ output.push(chalk6.bold("\u{1F195} New Patterns Detected"));
1859
+ output.push("");
1860
+ for (const pattern of comparison.changes.newPatterns) {
1861
+ output.push(
1862
+ ` ${severityIcon(pattern.severity)} ${pattern.name} (${String(pattern.frequency)}x)`
1863
+ );
1864
+ }
1865
+ output.push("");
1866
+ }
1867
+ if (comparison.changes.resolvedPatterns.length > 0) {
1868
+ output.push(chalk6.bold.green("\u2705 Resolved Patterns"));
1869
+ output.push("");
1870
+ for (const pattern of comparison.changes.resolvedPatterns) {
1871
+ output.push(
1872
+ ` ${severityIcon(pattern.severity)} ${pattern.name} (was ${String(pattern.frequency)}x)`
1873
+ );
1874
+ }
1341
1875
  output.push("");
1342
1876
  }
1343
- output.push(chalk3.dim(`Analysis Date: ${result.date}`));
1877
+ if (comparison.changes.changedPatterns.length > 0) {
1878
+ output.push(chalk6.bold("\u{1F4CA} Changed Patterns"));
1879
+ output.push("");
1880
+ for (const change of comparison.changes.changedPatterns) {
1881
+ const freqChange = change.frequencyAfter !== void 0 && change.frequencyBefore ? change.frequencyAfter - change.frequencyBefore : 0;
1882
+ const freqIndicator = freqChange > 0 ? chalk6.red(`+${String(freqChange)}`) : freqChange < 0 ? chalk6.green(String(freqChange)) : chalk6.dim("\xB10");
1883
+ output.push(` ${change.name}`);
1884
+ if (change.frequencyBefore !== void 0 && change.frequencyAfter !== void 0) {
1885
+ output.push(
1886
+ ` Frequency: ${String(change.frequencyBefore)} \u2192 ${String(change.frequencyAfter)} (${freqIndicator})`
1887
+ );
1888
+ }
1889
+ if (change.severityBefore !== void 0 && change.severityAfter !== void 0 && change.severityBefore !== change.severityAfter) {
1890
+ output.push(
1891
+ ` Severity: ${change.severityBefore} \u2192 ${change.severityAfter}`
1892
+ );
1893
+ }
1894
+ }
1895
+ output.push("");
1896
+ }
1897
+ if (comparison.changes.newPatterns.length === 0 && comparison.changes.resolvedPatterns.length === 0 && comparison.changes.changedPatterns.length === 0) {
1898
+ output.push(chalk6.green("\u2705 No pattern changes detected"));
1899
+ output.push("");
1900
+ }
1901
+ console.log(output.join("\n"));
1902
+ }
1903
+ function formatComparisonJson(comparison, compact = false) {
1904
+ return compact ? JSON.stringify(comparison) : JSON.stringify(comparison, null, 2);
1905
+ }
1906
+ function printHistoryList(entries) {
1907
+ if (entries.length === 0) {
1908
+ console.log("");
1909
+ console.log(chalk6.yellow("No history entries found"));
1910
+ console.log("");
1911
+ return;
1912
+ }
1913
+ const output = [];
1914
+ output.push("");
1915
+ output.push(chalk6.bold.cyan("Analysis History"));
1916
+ output.push("");
1917
+ const table = new Table({
1918
+ head: [
1919
+ chalk6.bold("Date"),
1920
+ chalk6.bold("Score"),
1921
+ chalk6.bold("Patterns"),
1922
+ chalk6.bold("Provider"),
1923
+ chalk6.bold("Prompts")
1924
+ ],
1925
+ colWidths: [15, 10, 12, 15, 12]
1926
+ });
1927
+ for (const [date, entry] of entries) {
1928
+ table.push([
1929
+ date,
1930
+ scoreColor(
1931
+ entry.result.stats.overallScore,
1932
+ `${entry.result.stats.overallScore.toFixed(1)}/10`
1933
+ ),
1934
+ String(entry.result.patterns.length),
1935
+ entry.metadata.provider,
1936
+ String(entry.metadata.promptCount)
1937
+ ]);
1938
+ }
1939
+ output.push(table.toString());
1940
+ output.push("");
1941
+ console.log(output.join("\n"));
1942
+ }
1943
+ function printHistorySummary(entries) {
1944
+ if (entries.length === 0) {
1945
+ console.log("");
1946
+ console.log(chalk6.yellow("No history entries found"));
1947
+ console.log("");
1948
+ return;
1949
+ }
1950
+ const output = [];
1951
+ output.push("");
1952
+ output.push(chalk6.bold.cyan("History Summary"));
1953
+ output.push("");
1954
+ const totalEntries = entries.length;
1955
+ const scores = entries.map((e) => e[1].result.stats.overallScore);
1956
+ const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length;
1957
+ const minScore = Math.min(...scores);
1958
+ const maxScore = Math.max(...scores);
1959
+ const providers = new Set(entries.map((e) => e[1].metadata.provider));
1960
+ const totalPrompts = entries.reduce(
1961
+ (sum2, e) => sum2 + e[1].metadata.promptCount,
1962
+ 0
1963
+ );
1964
+ const table = new Table({
1965
+ head: [chalk6.bold("Metric"), chalk6.bold("Value")],
1966
+ colWidths: [30, 20]
1967
+ });
1968
+ table.push(
1969
+ ["Total Entries", String(totalEntries)],
1970
+ ["Average Score", scoreColor(avgScore, `${avgScore.toFixed(1)}/10`)],
1971
+ ["Min Score", scoreColor(minScore, `${minScore.toFixed(1)}/10`)],
1972
+ ["Max Score", scoreColor(maxScore, `${maxScore.toFixed(1)}/10`)],
1973
+ ["Providers Used", Array.from(providers).join(", ")],
1974
+ ["Total Prompts Analyzed", String(totalPrompts)]
1975
+ );
1976
+ output.push(table.toString());
1977
+ output.push("");
1344
1978
  console.log(output.join("\n"));
1345
1979
  }
1346
1980
 
1981
+ // src/providers/index.ts
1982
+ init_logger();
1983
+
1984
+ // src/providers/ollama.ts
1985
+ init_logger();
1986
+
1347
1987
  // src/providers/base.ts
1348
1988
  var SYSTEM_PROMPT = `You are an AI prompt quality analyzer. Your task is to analyze user prompts to Claude Code and identify patterns that could be improved for clarity, specificity, and effectiveness.
1349
1989
 
@@ -1380,14 +2020,43 @@ Guidelines:
1380
2020
  - topSuggestion should be the most impactful single change
1381
2021
  - If no issues found, return empty patterns array with score 100
1382
2022
  - Be constructive and specific in suggestions`;
1383
- function buildUserPrompt(prompts2, date) {
1384
- if (prompts2.length === 0) {
2023
+ function buildUserPrompt(prompts3, date, context) {
2024
+ if (prompts3.length === 0) {
1385
2025
  throw new Error("Cannot build prompt from empty array");
1386
2026
  }
1387
- const promptsList = prompts2.map((prompt, index) => `${String(index + 1)}. ${prompt}`).join("\n\n");
1388
- const count = String(prompts2.length);
1389
- const plural = prompts2.length === 1 ? "" : "s";
1390
- return `Analyze the following ${count} prompt${plural} from ${date}:
2027
+ const promptsList = prompts3.map((prompt, index) => `${String(index + 1)}. ${prompt}`).join("\n\n");
2028
+ const count = String(prompts3.length);
2029
+ const plural = prompts3.length === 1 ? "" : "s";
2030
+ let contextSection = "";
2031
+ if (context) {
2032
+ const contextParts = [];
2033
+ if (context.role) {
2034
+ contextParts.push(`Role: ${context.role}`);
2035
+ }
2036
+ if (context.projectType) {
2037
+ contextParts.push(`Project Type: ${context.projectType}`);
2038
+ }
2039
+ if (context.domain) {
2040
+ contextParts.push(`Domain: ${context.domain}`);
2041
+ }
2042
+ if (context.techStack && context.techStack.length > 0) {
2043
+ contextParts.push(`Tech Stack: ${context.techStack.join(", ")}`);
2044
+ }
2045
+ if (context.guidelines && context.guidelines.length > 0) {
2046
+ contextParts.push(
2047
+ `Guidelines:
2048
+ ${context.guidelines.map((g) => `- ${g}`).join("\n")}`
2049
+ );
2050
+ }
2051
+ if (contextParts.length > 0) {
2052
+ contextSection = `
2053
+
2054
+ Project Context:
2055
+ ${contextParts.join("\n")}
2056
+ `;
2057
+ }
2058
+ }
2059
+ return `Analyze the following ${count} prompt${plural} from ${date}:${contextSection}
1391
2060
 
1392
2061
  ${promptsList}
1393
2062
 
@@ -1487,6 +2156,7 @@ var OllamaProvider = class {
1487
2156
  * @returns Promise that resolves to true if available, false otherwise
1488
2157
  */
1489
2158
  async isAvailable() {
2159
+ logger.debug(`Connecting to Ollama at ${this.config.host}`, "ollama");
1490
2160
  try {
1491
2161
  const controller = new AbortController();
1492
2162
  const timeoutId = setTimeout(() => {
@@ -1497,16 +2167,34 @@ var OllamaProvider = class {
1497
2167
  });
1498
2168
  clearTimeout(timeoutId);
1499
2169
  if (!response.ok) {
2170
+ logger.debug(
2171
+ `Ollama API returned ${String(response.status)}`,
2172
+ "ollama"
2173
+ );
1500
2174
  return false;
1501
2175
  }
1502
2176
  const data = await response.json();
1503
2177
  if (!data.models || !Array.isArray(data.models)) {
2178
+ logger.debug("Ollama returned invalid model list", "ollama");
1504
2179
  return false;
1505
2180
  }
1506
- return data.models.some(
2181
+ const modelAvailable = data.models.some(
1507
2182
  (model) => model.name.includes(this.config.model)
1508
2183
  );
2184
+ if (modelAvailable) {
2185
+ logger.debug(
2186
+ `Model ${this.config.model} available (${String(data.models.length)} models found)`,
2187
+ "ollama"
2188
+ );
2189
+ } else {
2190
+ logger.debug(
2191
+ `Model ${this.config.model} not found in available models`,
2192
+ "ollama"
2193
+ );
2194
+ }
2195
+ return modelAvailable;
1509
2196
  } catch {
2197
+ logger.debug("Ollama connection failed", "ollama");
1510
2198
  return false;
1511
2199
  }
1512
2200
  }
@@ -1516,14 +2204,15 @@ var OllamaProvider = class {
1516
2204
  *
1517
2205
  * @param prompts - Array of prompt strings to analyze
1518
2206
  * @param date - Date context for the analysis
2207
+ * @param context - Optional project context for analysis
1519
2208
  * @returns Promise resolving to AnalysisResult
1520
2209
  * @throws Error if analysis fails after retries or if response is invalid
1521
2210
  */
1522
- async analyze(prompts2, date) {
1523
- if (prompts2.length === 0) {
2211
+ async analyze(prompts3, date, context) {
2212
+ if (prompts3.length === 0) {
1524
2213
  throw new Error("Cannot analyze empty prompts array");
1525
2214
  }
1526
- const userPrompt = buildUserPrompt(prompts2, date);
2215
+ const userPrompt = buildUserPrompt(prompts3, date, context);
1527
2216
  let lastError;
1528
2217
  for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
1529
2218
  try {
@@ -1568,6 +2257,10 @@ var OllamaProvider = class {
1568
2257
  break;
1569
2258
  }
1570
2259
  const delay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt);
2260
+ logger.debug(
2261
+ `Retry attempt ${String(attempt + 1)}/${String(MAX_RETRIES)}, waiting ${String(delay)}ms`,
2262
+ "ollama"
2263
+ );
1571
2264
  await sleep(delay);
1572
2265
  }
1573
2266
  }
@@ -1578,39 +2271,131 @@ var OllamaProvider = class {
1578
2271
  }
1579
2272
  };
1580
2273
  function sleep(ms) {
1581
- return new Promise((resolve) => setTimeout(resolve, ms));
2274
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1582
2275
  }
1583
2276
 
1584
2277
  // src/providers/anthropic.ts
1585
- var MAX_RETRIES2 = 2;
1586
- var AVAILABILITY_TIMEOUT_MS2 = 5e3;
1587
- var ANALYSIS_TIMEOUT_MS2 = 6e4;
1588
- var BASE_RETRY_DELAY_MS2 = 1e3;
1589
- var API_BASE_URL = "https://api.anthropic.com";
1590
- var API_VERSION = "2023-06-01";
1591
- var MAX_TOKENS = 4096;
1592
- var AnthropicProvider = class {
1593
- name = "Anthropic";
1594
- config;
1595
- /**
1596
- * Creates a new AnthropicProvider instance.
1597
- *
1598
- * @param config - Anthropic configuration with model and API key
1599
- */
1600
- constructor(config) {
1601
- this.config = config;
1602
- }
1603
- /**
1604
- * Checks if the Anthropic API is available by validating the API key.
1605
- * Makes a minimal request to verify the key is valid.
1606
- *
1607
- * @returns Promise that resolves to true if available, false otherwise
1608
- */
1609
- async isAvailable() {
1610
- if (!this.config.apiKey) {
1611
- return false;
2278
+ init_logger();
2279
+
2280
+ // src/utils/rate-limiter.ts
2281
+ function createRateLimiter(options) {
2282
+ const minIntervalMs = 6e4 / options.requestsPerMinute;
2283
+ let lastRequestTime = 0;
2284
+ async function throttle(fn) {
2285
+ const now = Date.now();
2286
+ const timeSinceLastRequest = now - lastRequestTime;
2287
+ if (lastRequestTime > 0 && timeSinceLastRequest < minIntervalMs) {
2288
+ const waitTime = minIntervalMs - timeSinceLastRequest;
2289
+ await new Promise((resolve2) => setTimeout(resolve2, waitTime));
1612
2290
  }
1613
- try {
2291
+ lastRequestTime = Date.now();
2292
+ return fn();
2293
+ }
2294
+ function reset() {
2295
+ lastRequestTime = 0;
2296
+ }
2297
+ return { throttle, reset };
2298
+ }
2299
+ var DEFAULT_RATE_LIMITS = {
2300
+ anthropic: 50,
2301
+ google: 50
2302
+ };
2303
+
2304
+ // src/utils/retry.ts
2305
+ var DEFAULT_OPTIONS = {
2306
+ maxRetries: 3,
2307
+ baseDelayMs: 1e3,
2308
+ maxDelayMs: 3e4,
2309
+ isRetryable: isTransientError
2310
+ };
2311
+ function isTransientError(error) {
2312
+ if (!(error instanceof Error)) {
2313
+ return false;
2314
+ }
2315
+ const message = error.message.toLowerCase();
2316
+ if (message.includes("network") || message.includes("timeout") || message.includes("econnreset") || message.includes("econnrefused") || message.includes("enotfound") || message.includes("abort")) {
2317
+ return true;
2318
+ }
2319
+ if (message.includes("500") || message.includes("502") || message.includes("503") || message.includes("504")) {
2320
+ return true;
2321
+ }
2322
+ if (message.includes("429")) {
2323
+ return true;
2324
+ }
2325
+ if (message.includes("401") || message.includes("403")) {
2326
+ return false;
2327
+ }
2328
+ if (message.includes("parse") || message.includes("schema")) {
2329
+ return false;
2330
+ }
2331
+ return false;
2332
+ }
2333
+ function sleep2(ms) {
2334
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
2335
+ }
2336
+ async function withRetry(fn, options = {}) {
2337
+ const opts = { ...DEFAULT_OPTIONS, ...options };
2338
+ let lastError;
2339
+ for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
2340
+ try {
2341
+ return await fn();
2342
+ } catch (error) {
2343
+ lastError = error;
2344
+ const isLastAttempt = attempt === opts.maxRetries;
2345
+ const shouldRetry = opts.isRetryable(error);
2346
+ if (isLastAttempt || !shouldRetry) {
2347
+ throw error;
2348
+ }
2349
+ const delay = Math.min(
2350
+ opts.baseDelayMs * Math.pow(2, attempt),
2351
+ opts.maxDelayMs
2352
+ );
2353
+ await sleep2(delay);
2354
+ }
2355
+ }
2356
+ throw lastError;
2357
+ }
2358
+
2359
+ // src/providers/anthropic.ts
2360
+ var MAX_RETRIES2 = 3;
2361
+ var AVAILABILITY_TIMEOUT_MS2 = 5e3;
2362
+ var ANALYSIS_TIMEOUT_MS2 = 6e4;
2363
+ var BASE_DELAY_MS = 1e3;
2364
+ var MAX_DELAY_MS = 3e4;
2365
+ var API_BASE_URL = "https://api.anthropic.com";
2366
+ var API_VERSION = "2023-06-01";
2367
+ var MAX_TOKENS = 4096;
2368
+ var AnthropicProvider = class {
2369
+ name = "Anthropic";
2370
+ config;
2371
+ rateLimiter;
2372
+ /**
2373
+ * Creates a new AnthropicProvider instance.
2374
+ *
2375
+ * @param config - Anthropic configuration with model and API key
2376
+ */
2377
+ constructor(config) {
2378
+ this.config = config;
2379
+ this.rateLimiter = createRateLimiter({
2380
+ requestsPerMinute: DEFAULT_RATE_LIMITS.anthropic
2381
+ });
2382
+ }
2383
+ /**
2384
+ * Checks if the Anthropic API is available by validating the API key.
2385
+ * Makes a minimal request to verify the key is valid.
2386
+ *
2387
+ * @returns Promise that resolves to true if available, false otherwise
2388
+ */
2389
+ async isAvailable() {
2390
+ if (!this.config.apiKey) {
2391
+ logger.debug("No API key configured", "anthropic");
2392
+ return false;
2393
+ }
2394
+ logger.debug(
2395
+ `Validating API key with model ${this.config.model}`,
2396
+ "anthropic"
2397
+ );
2398
+ try {
1614
2399
  const controller = new AbortController();
1615
2400
  const timeoutId = setTimeout(() => {
1616
2401
  controller.abort();
@@ -1630,97 +2415,98 @@ var AnthropicProvider = class {
1630
2415
  signal: controller.signal
1631
2416
  });
1632
2417
  clearTimeout(timeoutId);
1633
- return response.ok || response.status === 429 || response.status === 400;
2418
+ const isAvailable = response.ok || response.status === 429 || response.status === 400;
2419
+ logger.debug(
2420
+ `API responded with status ${String(response.status)} (available: ${String(isAvailable)})`,
2421
+ "anthropic"
2422
+ );
2423
+ return isAvailable;
1634
2424
  } catch {
2425
+ logger.debug("Connection failed", "anthropic");
1635
2426
  return false;
1636
2427
  }
1637
2428
  }
1638
2429
  /**
1639
2430
  * Analyzes prompts using the Anthropic Claude API.
1640
2431
  * Implements retry logic with exponential backoff for network errors.
2432
+ * Rate limited to prevent 429 errors during batch processing.
1641
2433
  *
1642
2434
  * @param prompts - Array of prompt strings to analyze
1643
2435
  * @param date - Date context for the analysis
2436
+ * @param context - Optional project context for analysis
1644
2437
  * @returns Promise resolving to AnalysisResult
1645
2438
  * @throws Error if analysis fails after retries or if response is invalid
1646
2439
  */
1647
- async analyze(prompts2, date) {
1648
- if (prompts2.length === 0) {
2440
+ async analyze(prompts3, date, context) {
2441
+ if (prompts3.length === 0) {
1649
2442
  throw new Error("Cannot analyze empty prompts array");
1650
2443
  }
1651
- const userPrompt = buildUserPrompt(prompts2, date);
1652
- let lastError;
1653
- for (let attempt = 0; attempt <= MAX_RETRIES2; attempt++) {
1654
- try {
1655
- const controller = new AbortController();
1656
- const timeoutId = setTimeout(() => {
1657
- controller.abort();
1658
- }, ANALYSIS_TIMEOUT_MS2);
1659
- const response = await fetch(`${API_BASE_URL}/v1/messages`, {
1660
- method: "POST",
1661
- headers: {
1662
- "Content-Type": "application/json",
1663
- "x-api-key": this.config.apiKey,
1664
- "anthropic-version": API_VERSION
1665
- },
1666
- body: JSON.stringify({
1667
- model: this.config.model,
1668
- max_tokens: MAX_TOKENS,
1669
- system: SYSTEM_PROMPT,
1670
- messages: [{ role: "user", content: userPrompt }]
1671
- }),
1672
- signal: controller.signal
1673
- });
1674
- clearTimeout(timeoutId);
1675
- if (!response.ok) {
1676
- const status = String(response.status);
1677
- const errorBody = await response.text();
1678
- throw new Error(
1679
- `Anthropic API request failed: ${status} ${response.statusText} - ${errorBody}`
1680
- );
1681
- }
1682
- const data = await response.json();
1683
- const textContent = data.content?.find(
1684
- (block) => block.type === "text"
1685
- );
1686
- if (!textContent?.text) {
1687
- throw new Error("Invalid response format from Anthropic API");
1688
- }
1689
- return parseResponse(textContent.text, date);
1690
- } catch (error) {
1691
- lastError = error instanceof Error ? error : new Error(String(error));
1692
- if (lastError.message.includes("parse") || lastError.message.includes("schema")) {
1693
- throw lastError;
1694
- }
1695
- if (lastError.message.includes("401") || lastError.message.includes("403")) {
1696
- throw lastError;
1697
- }
1698
- if (attempt === MAX_RETRIES2) {
1699
- break;
2444
+ const userPrompt = buildUserPrompt(prompts3, date, context);
2445
+ return this.rateLimiter.throttle(
2446
+ () => withRetry(
2447
+ async () => {
2448
+ const controller = new AbortController();
2449
+ const timeoutId = setTimeout(() => {
2450
+ controller.abort();
2451
+ }, ANALYSIS_TIMEOUT_MS2);
2452
+ try {
2453
+ const response = await fetch(`${API_BASE_URL}/v1/messages`, {
2454
+ method: "POST",
2455
+ headers: {
2456
+ "Content-Type": "application/json",
2457
+ "x-api-key": this.config.apiKey,
2458
+ "anthropic-version": API_VERSION
2459
+ },
2460
+ body: JSON.stringify({
2461
+ model: this.config.model,
2462
+ max_tokens: MAX_TOKENS,
2463
+ system: SYSTEM_PROMPT,
2464
+ messages: [{ role: "user", content: userPrompt }]
2465
+ }),
2466
+ signal: controller.signal
2467
+ });
2468
+ if (!response.ok) {
2469
+ const status = String(response.status);
2470
+ const errorBody = await response.text();
2471
+ throw new Error(
2472
+ `Anthropic API request failed: ${status} ${response.statusText} - ${errorBody}`
2473
+ );
2474
+ }
2475
+ const data = await response.json();
2476
+ const textContent = data.content?.find(
2477
+ (block) => block.type === "text"
2478
+ );
2479
+ if (!textContent?.text) {
2480
+ throw new Error("Invalid response format from Anthropic API");
2481
+ }
2482
+ return parseResponse(textContent.text, date);
2483
+ } finally {
2484
+ clearTimeout(timeoutId);
2485
+ }
2486
+ },
2487
+ {
2488
+ maxRetries: MAX_RETRIES2,
2489
+ baseDelayMs: BASE_DELAY_MS,
2490
+ maxDelayMs: MAX_DELAY_MS,
2491
+ isRetryable: isTransientError
1700
2492
  }
1701
- const delay = BASE_RETRY_DELAY_MS2 * Math.pow(2, attempt);
1702
- await sleep2(delay);
1703
- }
1704
- }
1705
- const attempts = String(MAX_RETRIES2 + 1);
1706
- throw new Error(
1707
- `Anthropic analysis failed after ${attempts} attempts: ${lastError?.message ?? "Unknown error"}`
2493
+ )
1708
2494
  );
1709
2495
  }
1710
2496
  };
1711
- function sleep2(ms) {
1712
- return new Promise((resolve) => setTimeout(resolve, ms));
1713
- }
1714
2497
 
1715
2498
  // src/providers/google.ts
1716
- var MAX_RETRIES3 = 2;
2499
+ init_logger();
2500
+ var MAX_RETRIES3 = 3;
1717
2501
  var AVAILABILITY_TIMEOUT_MS3 = 5e3;
1718
2502
  var ANALYSIS_TIMEOUT_MS3 = 6e4;
1719
- var BASE_RETRY_DELAY_MS3 = 1e3;
2503
+ var BASE_DELAY_MS2 = 1e3;
2504
+ var MAX_DELAY_MS2 = 3e4;
1720
2505
  var API_BASE_URL2 = "https://generativelanguage.googleapis.com/v1beta";
1721
2506
  var GoogleProvider = class {
1722
2507
  name = "Google";
1723
2508
  config;
2509
+ rateLimiter;
1724
2510
  /**
1725
2511
  * Creates a new GoogleProvider instance.
1726
2512
  *
@@ -1728,6 +2514,9 @@ var GoogleProvider = class {
1728
2514
  */
1729
2515
  constructor(config) {
1730
2516
  this.config = config;
2517
+ this.rateLimiter = createRateLimiter({
2518
+ requestsPerMinute: DEFAULT_RATE_LIMITS.google
2519
+ });
1731
2520
  }
1732
2521
  /**
1733
2522
  * Checks if the Google Gemini API is available by validating the API key.
@@ -1737,8 +2526,13 @@ var GoogleProvider = class {
1737
2526
  */
1738
2527
  async isAvailable() {
1739
2528
  if (!this.config.apiKey) {
2529
+ logger.debug("No API key configured", "google");
1740
2530
  return false;
1741
2531
  }
2532
+ logger.debug(
2533
+ `Validating API key with model ${this.config.model}`,
2534
+ "google"
2535
+ );
1742
2536
  try {
1743
2537
  const controller = new AbortController();
1744
2538
  const timeoutId = setTimeout(() => {
@@ -1764,92 +2558,90 @@ var GoogleProvider = class {
1764
2558
  signal: controller.signal
1765
2559
  });
1766
2560
  clearTimeout(timeoutId);
1767
- return response.ok || response.status === 429 || response.status === 400;
2561
+ const isAvailable = response.ok || response.status === 429 || response.status === 400;
2562
+ logger.debug(
2563
+ `API responded with status ${String(response.status)} (available: ${String(isAvailable)})`,
2564
+ "google"
2565
+ );
2566
+ return isAvailable;
1768
2567
  } catch {
2568
+ logger.debug("Connection failed", "google");
1769
2569
  return false;
1770
2570
  }
1771
2571
  }
1772
2572
  /**
1773
2573
  * Analyzes prompts using the Google Gemini API.
1774
2574
  * Implements retry logic with exponential backoff for network errors.
2575
+ * Rate limited to prevent 429 errors during batch processing.
1775
2576
  *
1776
2577
  * @param prompts - Array of prompt strings to analyze
1777
2578
  * @param date - Date context for the analysis
2579
+ * @param context - Optional project context for analysis
1778
2580
  * @returns Promise resolving to AnalysisResult
1779
2581
  * @throws Error if analysis fails after retries or if response is invalid
1780
2582
  */
1781
- async analyze(prompts2, date) {
1782
- if (prompts2.length === 0) {
2583
+ async analyze(prompts3, date, context) {
2584
+ if (prompts3.length === 0) {
1783
2585
  throw new Error("Cannot analyze empty prompts array");
1784
2586
  }
1785
- const userPrompt = buildUserPrompt(prompts2, date);
1786
- let lastError;
1787
- for (let attempt = 0; attempt <= MAX_RETRIES3; attempt++) {
1788
- try {
1789
- const controller = new AbortController();
1790
- const timeoutId = setTimeout(() => {
1791
- controller.abort();
1792
- }, ANALYSIS_TIMEOUT_MS3);
1793
- const url = `${API_BASE_URL2}/models/${this.config.model}:generateContent?key=${this.config.apiKey}`;
1794
- const response = await fetch(url, {
1795
- method: "POST",
1796
- headers: {
1797
- "Content-Type": "application/json"
1798
- },
1799
- body: JSON.stringify({
1800
- contents: [
1801
- {
1802
- role: "user",
1803
- parts: [{ text: userPrompt }]
1804
- }
1805
- ],
1806
- systemInstruction: {
1807
- parts: [{ text: SYSTEM_PROMPT }]
1808
- },
1809
- generationConfig: {
1810
- responseMimeType: "application/json"
2587
+ const userPrompt = buildUserPrompt(prompts3, date, context);
2588
+ return this.rateLimiter.throttle(
2589
+ () => withRetry(
2590
+ async () => {
2591
+ const controller = new AbortController();
2592
+ const timeoutId = setTimeout(() => {
2593
+ controller.abort();
2594
+ }, ANALYSIS_TIMEOUT_MS3);
2595
+ try {
2596
+ const url = `${API_BASE_URL2}/models/${this.config.model}:generateContent?key=${this.config.apiKey}`;
2597
+ const response = await fetch(url, {
2598
+ method: "POST",
2599
+ headers: {
2600
+ "Content-Type": "application/json"
2601
+ },
2602
+ body: JSON.stringify({
2603
+ contents: [
2604
+ {
2605
+ role: "user",
2606
+ parts: [{ text: userPrompt }]
2607
+ }
2608
+ ],
2609
+ systemInstruction: {
2610
+ parts: [{ text: SYSTEM_PROMPT }]
2611
+ },
2612
+ generationConfig: {
2613
+ responseMimeType: "application/json"
2614
+ }
2615
+ }),
2616
+ signal: controller.signal
2617
+ });
2618
+ if (!response.ok) {
2619
+ const status = String(response.status);
2620
+ const errorBody = await response.text();
2621
+ throw new Error(
2622
+ `Google API request failed: ${status} ${response.statusText} - ${errorBody}`
2623
+ );
1811
2624
  }
1812
- }),
1813
- signal: controller.signal
1814
- });
1815
- clearTimeout(timeoutId);
1816
- if (!response.ok) {
1817
- const status = String(response.status);
1818
- const errorBody = await response.text();
1819
- throw new Error(
1820
- `Google API request failed: ${status} ${response.statusText} - ${errorBody}`
1821
- );
1822
- }
1823
- const data = await response.json();
1824
- const textContent = data.candidates?.[0]?.content?.parts?.[0]?.text;
1825
- if (!textContent) {
1826
- throw new Error("Invalid response format from Google API");
1827
- }
1828
- return parseResponse(textContent, date);
1829
- } catch (error) {
1830
- lastError = error instanceof Error ? error : new Error(String(error));
1831
- if (lastError.message.includes("parse") || lastError.message.includes("schema")) {
1832
- throw lastError;
1833
- }
1834
- if (lastError.message.includes("401") || lastError.message.includes("403")) {
1835
- throw lastError;
1836
- }
1837
- if (attempt === MAX_RETRIES3) {
1838
- break;
2625
+ const data = await response.json();
2626
+ const textContent = data.candidates?.[0]?.content?.parts?.[0]?.text;
2627
+ if (!textContent) {
2628
+ throw new Error("Invalid response format from Google API");
2629
+ }
2630
+ return parseResponse(textContent, date);
2631
+ } finally {
2632
+ clearTimeout(timeoutId);
2633
+ }
2634
+ },
2635
+ {
2636
+ maxRetries: MAX_RETRIES3,
2637
+ baseDelayMs: BASE_DELAY_MS2,
2638
+ maxDelayMs: MAX_DELAY_MS2,
2639
+ isRetryable: isTransientError
1839
2640
  }
1840
- const delay = BASE_RETRY_DELAY_MS3 * Math.pow(2, attempt);
1841
- await sleep3(delay);
1842
- }
1843
- }
1844
- const attempts = String(MAX_RETRIES3 + 1);
1845
- throw new Error(
1846
- `Google analysis failed after ${attempts} attempts: ${lastError?.message ?? "Unknown error"}`
2641
+ )
1847
2642
  );
1848
2643
  }
1849
2644
  };
1850
- function sleep3(ms) {
1851
- return new Promise((resolve) => setTimeout(resolve, ms));
1852
- }
1853
2645
 
1854
2646
  // src/providers/index.ts
1855
2647
  function createProvider(type, config) {
@@ -1868,19 +2660,28 @@ async function getAvailableProvider(config, onFallback) {
1868
2660
  "No providers configured. Please run hyntx setup to configure providers."
1869
2661
  );
1870
2662
  }
2663
+ logger.debug(
2664
+ `Checking ${String(config.services.length)} configured provider(s): ${config.services.join(", ")}`,
2665
+ "provider"
2666
+ );
1871
2667
  let firstProvider;
1872
2668
  for (const type of config.services) {
1873
2669
  const provider = createProvider(type, config);
1874
2670
  firstProvider ??= provider;
2671
+ logger.debug(`Checking availability of ${provider.name}...`, "provider");
1875
2672
  try {
1876
2673
  const isAvailable = await provider.isAvailable();
1877
2674
  if (isAvailable) {
2675
+ logger.debug(`${provider.name} is available`, "provider");
1878
2676
  if (onFallback && provider !== firstProvider) {
1879
2677
  onFallback(firstProvider.name, provider.name);
1880
2678
  }
1881
2679
  return provider;
2680
+ } else {
2681
+ logger.debug(`${provider.name} is not available`, "provider");
1882
2682
  }
1883
2683
  } catch {
2684
+ logger.debug(`${provider.name} availability check failed`, "provider");
1884
2685
  continue;
1885
2686
  }
1886
2687
  }
@@ -1890,197 +2691,1388 @@ async function getAvailableProvider(config, onFallback) {
1890
2691
  }
1891
2692
 
1892
2693
  // src/index.ts
1893
- var currentDir = dirname(fileURLToPath(import.meta.url));
1894
- var packageJson = JSON.parse(
1895
- readFileSync(join(currentDir, "../package.json"), "utf-8")
1896
- );
1897
- var VERSION = packageJson.version;
1898
- function parseArguments() {
1899
- try {
1900
- const { values } = parseArgs({
1901
- options: {
1902
- date: {
1903
- type: "string",
1904
- default: "today"
1905
- },
1906
- help: {
1907
- type: "boolean",
1908
- short: "h",
1909
- default: false
1910
- },
1911
- version: {
1912
- type: "boolean",
1913
- default: false
1914
- }
1915
- },
1916
- strict: true,
1917
- allowPositionals: false
1918
- });
1919
- return {
1920
- date: values.date || "today",
1921
- help: values.help || false,
1922
- version: values.version || false
1923
- };
1924
- } catch (error) {
1925
- const errorMessage = error instanceof Error ? error.message : String(error);
1926
- throw new Error(`Invalid arguments: ${errorMessage}`);
1927
- }
1928
- }
1929
- function showHelp() {
1930
- const helpText = `
1931
- ${chalk3.bold("Usage:")} hyntx [options]
2694
+ init_logger();
1932
2695
 
1933
- ${chalk3.bold("Options:")}
1934
- --date <date> Date to analyze (today, yesterday, YYYY-MM-DD) [default: today]
1935
- -h, --help Show help
1936
- --version Show version
1937
-
1938
- ${chalk3.bold("Exit codes:")}
1939
- ${String(EXIT_CODES.SUCCESS)} - Success
1940
- ${String(EXIT_CODES.ERROR)} - Error
1941
- ${String(EXIT_CODES.NO_DATA)} - No data found
1942
- ${String(EXIT_CODES.PROVIDER_UNAVAILABLE)} - Provider unavailable
1943
-
1944
- ${chalk3.bold("Examples:")}
1945
- hyntx # Analyze today's prompts
1946
- hyntx --date yesterday # Analyze yesterday
1947
- hyntx --date 2025-01-20 # Specific date
1948
- `;
1949
- console.log(helpText);
1950
- process.exit(EXIT_CODES.SUCCESS);
1951
- }
1952
- function showVersion() {
1953
- console.log(`hyntx v${VERSION}`);
1954
- process.exit(EXIT_CODES.SUCCESS);
1955
- }
1956
- async function checkAndRunSetup() {
1957
- if (isFirstRun()) {
1958
- const spinner = ora("Running first-time setup...").start();
1959
- spinner.stop();
1960
- await runSetup();
2696
+ // src/utils/project-config.ts
2697
+ init_logger();
2698
+ var CONFIG_FILENAME = ".hyntxrc.json";
2699
+ var MAX_TRAVERSAL_DEPTH = 50;
2700
+ var PROJECT_CONTEXT_SCHEMA = z.object({
2701
+ role: z.string().optional(),
2702
+ techStack: z.array(z.string()).optional(),
2703
+ domain: z.string().optional(),
2704
+ guidelines: z.array(z.string()).optional(),
2705
+ projectType: z.string().optional()
2706
+ });
2707
+ var PROJECT_CONFIG_SCHEMA = z.object({
2708
+ context: PROJECT_CONTEXT_SCHEMA.optional()
2709
+ });
2710
+ var configCache = /* @__PURE__ */ new Map();
2711
+ function findProjectConfig(cwd) {
2712
+ let currentDir2 = cwd;
2713
+ const homeDirectory = homedir();
2714
+ let depth = 0;
2715
+ while (depth < MAX_TRAVERSAL_DEPTH) {
2716
+ const configPath = join(currentDir2, CONFIG_FILENAME);
2717
+ try {
2718
+ readFileSync(configPath, "utf-8");
2719
+ return configPath;
2720
+ } catch {
2721
+ }
2722
+ if (currentDir2 === homeDirectory || currentDir2 === "/") {
2723
+ break;
2724
+ }
2725
+ const parentDir = dirname(currentDir2);
2726
+ if (parentDir === currentDir2) {
2727
+ break;
2728
+ }
2729
+ currentDir2 = parentDir;
2730
+ depth++;
1961
2731
  }
2732
+ return null;
1962
2733
  }
1963
- async function readLogsWithSpinner(date) {
1964
- if (!claudeProjectsExist()) {
1965
- console.error(chalk3.red("Error: Claude Code logs directory not found"));
1966
- console.error(chalk3.dim(`Expected location: ${CLAUDE_PROJECTS_DIR}`));
1967
- console.error(
1968
- chalk3.dim(
1969
- "\nMake sure Claude Code is installed and has been used at least once."
1970
- )
1971
- );
1972
- process.exit(EXIT_CODES.NO_DATA);
1973
- }
1974
- const spinner = ora(`Reading Claude Code logs for ${date}...`).start();
2734
+ function loadProjectConfig(configPath) {
1975
2735
  try {
1976
- const result = await readLogs({ date });
1977
- if (result.prompts.length === 0) {
1978
- spinner.fail(chalk3.yellow(`No prompts found for ${date}`));
1979
- console.error(
1980
- chalk3.dim(
1981
- "\nTry a different date or check that Claude Code has been used recently."
1982
- )
2736
+ const fileContent = readFileSync(configPath, "utf-8");
2737
+ let parsed;
2738
+ try {
2739
+ parsed = JSON.parse(fileContent);
2740
+ } catch (error) {
2741
+ logger.collectWarning(
2742
+ `Invalid JSON in ${CONFIG_FILENAME}: ${error instanceof Error ? error.message : "Unknown error"}`,
2743
+ "config"
1983
2744
  );
1984
- process.exit(EXIT_CODES.NO_DATA);
2745
+ return null;
1985
2746
  }
1986
- spinner.succeed(
1987
- chalk3.green(`Found ${String(result.prompts.length)} prompts for ${date}`)
1988
- );
1989
- if (result.warnings.length > 0) {
1990
- for (const warning of result.warnings) {
1991
- console.warn(chalk3.yellow(`Warning: ${warning}`));
1992
- }
2747
+ const result = PROJECT_CONFIG_SCHEMA.safeParse(parsed);
2748
+ if (!result.success) {
2749
+ const errorMessages = result.error.issues.map((issue) => {
2750
+ const pathStr = issue.path.map(String).join(".");
2751
+ return `${pathStr}: ${issue.message}`;
2752
+ }).join(", ");
2753
+ logger.collectWarning(
2754
+ `Invalid ${CONFIG_FILENAME} schema: ${errorMessages}`,
2755
+ "config"
2756
+ );
2757
+ return null;
1993
2758
  }
1994
- return result.prompts.map((p) => p.content);
2759
+ return result.data;
1995
2760
  } catch (error) {
1996
- const errorMessage = error instanceof Error ? error.message : String(error);
1997
- spinner.fail(chalk3.red(`Failed to read logs: ${errorMessage}`));
1998
- process.exit(EXIT_CODES.ERROR);
2761
+ logger.collectWarning(
2762
+ `Failed to read ${CONFIG_FILENAME}: ${error instanceof Error ? error.message : "Unknown error"}`,
2763
+ "config"
2764
+ );
2765
+ return null;
1999
2766
  }
2000
2767
  }
2001
- async function connectProviderWithSpinner() {
2002
- const config = getEnvConfig();
2003
- if (config.services.length === 0) {
2004
- console.error(chalk3.red("Error: No providers configured"));
2005
- console.error(chalk3.dim("\nRun setup to configure at least one provider."));
2006
- process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
2768
+ function mergeConfigs(envConfig, projectConfig) {
2769
+ if (!projectConfig?.context) {
2770
+ return envConfig;
2007
2771
  }
2008
- const spinner = ora("Connecting to provider...").start();
2009
- try {
2010
- const provider = await getAvailableProvider(config, (from, to) => {
2011
- spinner.text = chalk3.yellow(
2012
- `Primary provider ${from} unavailable, falling back to ${to}...`
2013
- );
2014
- });
2015
- spinner.succeed(chalk3.green(`Connected to ${provider.name}`));
2016
- return provider;
2017
- } catch (error) {
2018
- const errorMessage = error instanceof Error ? error.message : String(error);
2019
- spinner.fail(chalk3.red("No providers available"));
2020
- console.error(chalk3.dim(`
2021
- ${errorMessage}`));
2022
- console.error(
2023
- chalk3.dim(
2024
- "\nCheck your provider configuration and ensure at least one provider is running."
2025
- )
2026
- );
2027
- process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
2772
+ const existingEnvConfig = envConfig;
2773
+ if (existingEnvConfig.context) {
2774
+ return existingEnvConfig;
2028
2775
  }
2776
+ return {
2777
+ ...envConfig,
2778
+ context: projectConfig.context
2779
+ };
2029
2780
  }
2030
- async function analyzeWithProgress(provider, prompts2, date) {
2031
- const spinner = ora(`Analyzing ${String(prompts2.length)} prompts...`).start();
2032
- try {
2033
- const result = await analyzePrompts({
2034
- provider,
2035
- prompts: prompts2,
2036
- date,
2037
- onProgress: (current, total) => {
2038
- if (total > 1) {
2039
- spinner.text = `Analyzing ${String(prompts2.length)} prompts (batch ${String(current + 1)}/${String(total)})...`;
2040
- }
2041
- }
2042
- });
2043
- spinner.succeed(chalk3.green("Analysis complete"));
2044
- return result;
2045
- } catch (error) {
2046
- const errorMessage = error instanceof Error ? error.message : String(error);
2047
- spinner.fail(chalk3.red(`Analysis failed: ${errorMessage}`));
2048
- process.exit(EXIT_CODES.ERROR);
2781
+ function loadProjectConfigForCwd(cwd) {
2782
+ if (configCache.has(cwd)) {
2783
+ return configCache.get(cwd) ?? null;
2049
2784
  }
2785
+ const configPath = findProjectConfig(cwd);
2786
+ if (!configPath) {
2787
+ configCache.set(cwd, null);
2788
+ return null;
2789
+ }
2790
+ const config = loadProjectConfig(configPath);
2791
+ configCache.set(cwd, config);
2792
+ return config;
2050
2793
  }
2051
- function displayResults(result) {
2052
- console.log("");
2053
- printReport(result);
2794
+ init_logger();
2795
+ function isValidUrl(url) {
2796
+ try {
2797
+ new URL(url);
2798
+ return true;
2799
+ } catch {
2800
+ return false;
2801
+ }
2054
2802
  }
2055
- function handleError(error) {
2056
- console.error(chalk3.red(`
2057
- Error: ${error.message}`));
2058
- process.exit(EXIT_CODES.ERROR);
2803
+ function isValidApiKeyFormat(apiKey) {
2804
+ if (!apiKey || apiKey.trim() === "") {
2805
+ return false;
2806
+ }
2807
+ return apiKey.length >= 10 && !/\s/.test(apiKey);
2059
2808
  }
2060
- async function main() {
2809
+ async function validateOllama(config) {
2810
+ const checks = [];
2811
+ const { ollama } = config;
2812
+ checks.push({
2813
+ name: "Model",
2814
+ status: ollama.model ? "pass" : "fail",
2815
+ message: ollama.model || "Not configured"
2816
+ });
2817
+ const hostValid = isValidUrl(ollama.host);
2818
+ checks.push({
2819
+ name: "Host",
2820
+ status: hostValid ? "pass" : "fail",
2821
+ message: hostValid ? ollama.host : `Invalid URL: ${ollama.host}`
2822
+ });
2823
+ if (hostValid) {
2824
+ try {
2825
+ const provider = createProvider("ollama", config);
2826
+ const isAvailable = await provider.isAvailable();
2827
+ checks.push({
2828
+ name: "Connection",
2829
+ status: isAvailable ? "pass" : "fail",
2830
+ message: isAvailable ? "Reachable" : "Cannot connect"
2831
+ });
2832
+ if (isAvailable) {
2833
+ checks.push({
2834
+ name: "Model available",
2835
+ status: "pass",
2836
+ message: "Yes"
2837
+ });
2838
+ } else {
2839
+ checks.push({
2840
+ name: "Model available",
2841
+ status: "warn",
2842
+ message: "Cannot verify (connection failed)"
2843
+ });
2844
+ }
2845
+ } catch (error) {
2846
+ const message = error instanceof Error ? error.message : String(error);
2847
+ checks.push({
2848
+ name: "Connection",
2849
+ status: "fail",
2850
+ message: `Error: ${message}`
2851
+ });
2852
+ }
2853
+ } else {
2854
+ checks.push({
2855
+ name: "Connection",
2856
+ status: "warn",
2857
+ message: "Cannot test (invalid host URL)"
2858
+ });
2859
+ }
2860
+ const allPass = checks.every((c) => c.status === "pass");
2861
+ return {
2862
+ provider: "ollama",
2863
+ displayName: "Ollama",
2864
+ valid: allPass,
2865
+ checks
2866
+ };
2867
+ }
2868
+ async function validateAnthropic(config) {
2869
+ const checks = [];
2870
+ const { anthropic } = config;
2871
+ checks.push({
2872
+ name: "Model",
2873
+ status: anthropic.model ? "pass" : "fail",
2874
+ message: anthropic.model || "Not configured"
2875
+ });
2876
+ const apiKeyValid = isValidApiKeyFormat(anthropic.apiKey);
2877
+ checks.push({
2878
+ name: "API Key",
2879
+ status: apiKeyValid ? "pass" : "fail",
2880
+ message: apiKeyValid ? "Configured" : "Missing or invalid"
2881
+ });
2882
+ if (apiKeyValid) {
2883
+ try {
2884
+ const provider = createProvider("anthropic", config);
2885
+ const isAvailable = await provider.isAvailable();
2886
+ checks.push({
2887
+ name: "Connection",
2888
+ status: isAvailable ? "pass" : "fail",
2889
+ message: isAvailable ? "API key valid" : "API key invalid or connection failed"
2890
+ });
2891
+ } catch (error) {
2892
+ const message = error instanceof Error ? error.message : String(error);
2893
+ checks.push({
2894
+ name: "Connection",
2895
+ status: "fail",
2896
+ message: `Error: ${message}`
2897
+ });
2898
+ }
2899
+ } else {
2900
+ checks.push({
2901
+ name: "Connection",
2902
+ status: "warn",
2903
+ message: "Cannot test (invalid API key)"
2904
+ });
2905
+ }
2906
+ const allPass = checks.every((c) => c.status === "pass");
2907
+ return {
2908
+ provider: "anthropic",
2909
+ displayName: "Anthropic",
2910
+ valid: allPass,
2911
+ checks
2912
+ };
2913
+ }
2914
+ async function validateGoogle(config) {
2915
+ const checks = [];
2916
+ const { google } = config;
2917
+ checks.push({
2918
+ name: "Model",
2919
+ status: google.model ? "pass" : "fail",
2920
+ message: google.model || "Not configured"
2921
+ });
2922
+ const apiKeyValid = isValidApiKeyFormat(google.apiKey);
2923
+ checks.push({
2924
+ name: "API Key",
2925
+ status: apiKeyValid ? "pass" : "fail",
2926
+ message: apiKeyValid ? "Configured" : "Missing or invalid"
2927
+ });
2928
+ if (apiKeyValid) {
2929
+ try {
2930
+ const provider = createProvider("google", config);
2931
+ const isAvailable = await provider.isAvailable();
2932
+ checks.push({
2933
+ name: "Connection",
2934
+ status: isAvailable ? "pass" : "fail",
2935
+ message: isAvailable ? "API key valid" : "API key invalid or connection failed"
2936
+ });
2937
+ } catch (error) {
2938
+ const message = error instanceof Error ? error.message : String(error);
2939
+ checks.push({
2940
+ name: "Connection",
2941
+ status: "fail",
2942
+ message: `Error: ${message}`
2943
+ });
2944
+ }
2945
+ } else {
2946
+ checks.push({
2947
+ name: "Connection",
2948
+ status: "warn",
2949
+ message: "Cannot test (invalid API key)"
2950
+ });
2951
+ }
2952
+ const allPass = checks.every((c) => c.status === "pass");
2953
+ return {
2954
+ provider: "google",
2955
+ displayName: "Google",
2956
+ valid: allPass,
2957
+ checks
2958
+ };
2959
+ }
2960
+ async function validateProvider(type, config) {
2961
+ switch (type) {
2962
+ case "ollama":
2963
+ return validateOllama(config);
2964
+ case "anthropic":
2965
+ return validateAnthropic(config);
2966
+ case "google":
2967
+ return validateGoogle(config);
2968
+ }
2969
+ }
2970
+ async function validateAllProviders(config) {
2971
+ const results = [];
2972
+ for (const type of config.services) {
2973
+ logger.debug(`Validating ${type} provider...`, "health-check");
2974
+ const result = await validateProvider(type, config);
2975
+ results.push(result);
2976
+ }
2977
+ const availableCount = results.filter((r) => r.valid).length;
2978
+ const unavailableCount = results.filter((r) => !r.valid).length;
2979
+ return {
2980
+ providers: results,
2981
+ summary: {
2982
+ availableCount,
2983
+ unavailableCount,
2984
+ totalConfigured: config.services.length
2985
+ },
2986
+ allValid: unavailableCount === 0 && config.services.length > 0
2987
+ };
2988
+ }
2989
+ function formatStatusIcon(status) {
2990
+ switch (status) {
2991
+ case "pass":
2992
+ return chalk6.green("\u2705");
2993
+ case "fail":
2994
+ return chalk6.red("\u274C");
2995
+ case "warn":
2996
+ return chalk6.yellow("\u26A0\uFE0F");
2997
+ }
2998
+ }
2999
+ function printHealthCheckResult(result, config) {
3000
+ console.log("");
3001
+ console.log(chalk6.bold("\u{1F50D} Configuration Health Check"));
3002
+ console.log(chalk6.dim("\u2550".repeat(43)));
3003
+ console.log("");
3004
+ console.log(chalk6.bold("Configuration:"));
3005
+ if (config.services.length === 0) {
3006
+ console.log(chalk6.dim(" No providers configured"));
3007
+ } else {
3008
+ console.log(` Services: ${config.services.join(", ")}`);
3009
+ }
3010
+ console.log(` Reminder: ${config.reminder}`);
3011
+ console.log("");
3012
+ for (const provider of result.providers) {
3013
+ console.log(chalk6.bold(`${provider.displayName} Provider:`));
3014
+ for (const check of provider.checks) {
3015
+ const icon = formatStatusIcon(check.status);
3016
+ const message = check.message ? `: ${check.message}` : "";
3017
+ console.log(` ${icon} ${check.name}${message}`);
3018
+ }
3019
+ console.log("");
3020
+ }
3021
+ console.log(chalk6.bold("Summary:"));
3022
+ if (config.services.length === 0) {
3023
+ console.log(chalk6.yellow(" \u26A0\uFE0F No providers configured"));
3024
+ console.log(chalk6.dim(" Run hyntx setup to configure providers"));
3025
+ } else if (result.allValid) {
3026
+ console.log(
3027
+ chalk6.green(
3028
+ ` \u2705 All ${String(result.summary.totalConfigured)} provider(s) ready to use`
3029
+ )
3030
+ );
3031
+ } else {
3032
+ if (result.summary.unavailableCount > 0) {
3033
+ console.log(
3034
+ chalk6.yellow(
3035
+ ` \u26A0\uFE0F ${String(result.summary.unavailableCount)} provider(s) configured but unavailable`
3036
+ )
3037
+ );
3038
+ }
3039
+ if (result.summary.availableCount > 0) {
3040
+ console.log(
3041
+ chalk6.green(
3042
+ ` \u2705 ${String(result.summary.availableCount)} provider(s) ready to use`
3043
+ )
3044
+ );
3045
+ } else {
3046
+ console.log(chalk6.red(" \u274C No providers available"));
3047
+ }
3048
+ }
3049
+ console.log("");
3050
+ }
3051
+ init_logger();
3052
+ var REMINDER_FREQUENCIES = {
3053
+ "7d": 7,
3054
+ "14d": 14,
3055
+ "30d": 30
3056
+ };
3057
+ var REMINDER_OPTIONS2 = [
3058
+ { title: "Continue with analysis", value: "continue" },
3059
+ { title: "Remind me later", value: "postpone" },
3060
+ { title: "Disable reminders", value: "disable" }
3061
+ ];
3062
+ function getLastRun() {
3063
+ if (!existsSync(LAST_RUN_FILE)) {
3064
+ return null;
3065
+ }
3066
+ try {
3067
+ const content = readFileSync(LAST_RUN_FILE, "utf-8").trim();
3068
+ const date = parseISO(content);
3069
+ if (isNaN(date.getTime())) {
3070
+ return null;
3071
+ }
3072
+ return content;
3073
+ } catch {
3074
+ return null;
3075
+ }
3076
+ }
3077
+ function saveLastRun() {
3078
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3079
+ try {
3080
+ const dir = dirname(LAST_RUN_FILE);
3081
+ if (!existsSync(dir)) {
3082
+ mkdirSync(dir, { recursive: true });
3083
+ }
3084
+ writeFileSync(LAST_RUN_FILE, now, "utf-8");
3085
+ } catch (error) {
3086
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
3087
+ logger.warn(
3088
+ `Failed to save last run timestamp to ${LAST_RUN_FILE}: ${errorMessage}`,
3089
+ "reminder"
3090
+ );
3091
+ }
3092
+ }
3093
+ function getDaysElapsed() {
3094
+ const lastRun = getLastRun();
3095
+ if (!lastRun) {
3096
+ return null;
3097
+ }
3098
+ const lastRunDate = parseISO(lastRun);
3099
+ const now = /* @__PURE__ */ new Date();
3100
+ return differenceInDays(now, lastRunDate);
3101
+ }
3102
+ function shouldShowReminder() {
3103
+ const config = getEnvConfig();
3104
+ const reminder = config.reminder;
3105
+ if (reminder === "never") {
3106
+ return false;
3107
+ }
3108
+ const days = getDaysElapsed();
3109
+ if (days === null) {
3110
+ return true;
3111
+ }
3112
+ const threshold = REMINDER_FREQUENCIES[reminder];
3113
+ if (!threshold) {
3114
+ return false;
3115
+ }
3116
+ return days >= threshold;
3117
+ }
3118
+ async function showReminder() {
3119
+ const days = getDaysElapsed();
3120
+ const message = days === null ? chalk6.cyan("It's time to analyze your prompts!") : chalk6.cyan(
3121
+ `It's been ${chalk6.bold(days)} days since your last analysis.`
3122
+ );
3123
+ console.log("\n" + message + "\n");
3124
+ const response = await prompts({
3125
+ type: "select",
3126
+ name: "action",
3127
+ message: "What would you like to do?",
3128
+ choices: [...REMINDER_OPTIONS2]
3129
+ });
3130
+ const action = response.action;
3131
+ if (action === "continue") {
3132
+ return true;
3133
+ }
3134
+ if (action === "disable") {
3135
+ console.log(
3136
+ "\n" + chalk6.yellow("To disable reminders, set ") + chalk6.bold("HYNTX_REMINDER=never") + chalk6.yellow(" in your shell config.\n")
3137
+ );
3138
+ return false;
3139
+ }
3140
+ return false;
3141
+ }
3142
+ async function checkReminder() {
3143
+ if (!shouldShowReminder()) {
3144
+ return true;
3145
+ }
3146
+ return await showReminder();
3147
+ }
3148
+ init_logger();
3149
+ async function ensureHistoryDir() {
3150
+ try {
3151
+ await mkdir(HYNTX_HISTORY_DIR, { recursive: true, mode: 448 });
3152
+ } catch (error) {
3153
+ const errorMessage = error instanceof Error ? error.message : String(error);
3154
+ throw new Error(
3155
+ `Failed to create history directory ${HYNTX_HISTORY_DIR}: ${errorMessage}`
3156
+ );
3157
+ }
3158
+ }
3159
+ function getHistoryFilePath(date) {
3160
+ return join(HYNTX_HISTORY_DIR, `${date}.json`);
3161
+ }
3162
+ async function saveAnalysisResult(result, metadata) {
3163
+ try {
3164
+ await ensureHistoryDir();
3165
+ const sanitizedResult = {
3166
+ ...result,
3167
+ patterns: result.patterns.map((pattern) => ({
3168
+ ...pattern,
3169
+ examples: pattern.examples.map((example) => sanitize(example).text)
3170
+ }))
3171
+ };
3172
+ const entry = {
3173
+ result: sanitizedResult,
3174
+ metadata
3175
+ };
3176
+ const filePath = getHistoryFilePath(result.date);
3177
+ const content = JSON.stringify(entry, null, 2);
3178
+ const tmpFile = `${filePath}.tmp`;
3179
+ await writeFile(tmpFile, content, "utf-8");
3180
+ await rename(tmpFile, filePath);
3181
+ logger.debug(`Saved history to ${filePath}`, "history");
3182
+ } catch (error) {
3183
+ const errorMessage = error instanceof Error ? error.message : String(error);
3184
+ logger.warn(
3185
+ `Failed to save analysis to history: ${errorMessage}`,
3186
+ "history"
3187
+ );
3188
+ }
3189
+ }
3190
+ async function loadAnalysisResult(date) {
3191
+ const filePath = getHistoryFilePath(date);
3192
+ if (!existsSync(filePath)) {
3193
+ return null;
3194
+ }
3195
+ try {
3196
+ const content = await readFile(filePath, "utf-8");
3197
+ const entry = JSON.parse(content);
3198
+ if (entry.result === void 0 || entry.metadata === void 0) {
3199
+ logger.warn(`Invalid history entry in ${filePath}`, "history");
3200
+ return null;
3201
+ }
3202
+ return entry;
3203
+ } catch (error) {
3204
+ const errorMessage = error instanceof Error ? error.message : String(error);
3205
+ logger.warn(
3206
+ `Failed to load history from ${filePath}: ${errorMessage}`,
3207
+ "history"
3208
+ );
3209
+ return null;
3210
+ }
3211
+ }
3212
+ async function listAvailableDates(options) {
3213
+ if (!existsSync(HYNTX_HISTORY_DIR)) {
3214
+ return [];
3215
+ }
3216
+ try {
3217
+ const files = readdirSync(HYNTX_HISTORY_DIR);
3218
+ const dates = [];
3219
+ for (const file of files) {
3220
+ if (!file.endsWith(".json")) {
3221
+ continue;
3222
+ }
3223
+ const date = file.slice(0, -5);
3224
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
3225
+ continue;
3226
+ }
3227
+ if (options) ;
3228
+ dates.push(date);
3229
+ }
3230
+ return dates.sort((a, b) => b.localeCompare(a));
3231
+ } catch (error) {
3232
+ const errorMessage = error instanceof Error ? error.message : String(error);
3233
+ logger.warn(`Failed to list history dates: ${errorMessage}`, "history");
3234
+ return [];
3235
+ }
3236
+ }
3237
+ function compareResults(before, after) {
3238
+ const scoreDelta = after.stats.overallScore - before.stats.overallScore;
3239
+ const beforePatterns = new Map(before.patterns.map((p) => [p.id, p]));
3240
+ const afterPatterns = new Map(after.patterns.map((p) => [p.id, p]));
3241
+ const newPatterns = [];
3242
+ for (const pattern of after.patterns) {
3243
+ if (!beforePatterns.has(pattern.id)) {
3244
+ newPatterns.push(pattern);
3245
+ }
3246
+ }
3247
+ const resolvedPatterns = [];
3248
+ for (const pattern of before.patterns) {
3249
+ if (!afterPatterns.has(pattern.id)) {
3250
+ resolvedPatterns.push(pattern);
3251
+ }
3252
+ }
3253
+ const changedPatterns = [];
3254
+ for (const [id, beforePattern] of beforePatterns) {
3255
+ const afterPattern = afterPatterns.get(id);
3256
+ if (!afterPattern) {
3257
+ continue;
3258
+ }
3259
+ const frequencyChanged = beforePattern.frequency !== afterPattern.frequency;
3260
+ const severityChanged = beforePattern.severity !== afterPattern.severity;
3261
+ if (frequencyChanged || severityChanged) {
3262
+ changedPatterns.push({
3263
+ id,
3264
+ name: beforePattern.name,
3265
+ status: "changed",
3266
+ frequencyBefore: beforePattern.frequency,
3267
+ frequencyAfter: afterPattern.frequency,
3268
+ severityBefore: beforePattern.severity,
3269
+ severityAfter: afterPattern.severity
3270
+ });
3271
+ }
3272
+ }
3273
+ const changes = {
3274
+ scoreDelta,
3275
+ newPatterns,
3276
+ resolvedPatterns,
3277
+ changedPatterns
3278
+ };
3279
+ return {
3280
+ before,
3281
+ after,
3282
+ changes
3283
+ };
3284
+ }
3285
+ function getDateOneWeekAgo(fromDate) {
3286
+ const date = typeof fromDate === "string" ? parseISO(fromDate) : fromDate;
3287
+ const weekAgo = subDays(date, 7);
3288
+ return format(weekAgo, "yyyy-MM-dd");
3289
+ }
3290
+ function getDateOneMonthAgo(fromDate) {
3291
+ const date = typeof fromDate === "string" ? parseISO(fromDate) : fromDate;
3292
+ const monthAgo = subMonths(date, 1);
3293
+ return format(monthAgo, "yyyy-MM-dd");
3294
+ }
3295
+
3296
+ // src/index.ts
3297
+ var currentDir = dirname(fileURLToPath(import.meta.url));
3298
+ var packageJson = JSON.parse(
3299
+ readFileSync(join(currentDir, "../package.json"), "utf-8")
3300
+ );
3301
+ var VERSION = packageJson.version;
3302
+ function parseArguments() {
3303
+ try {
3304
+ const { values } = parseArgs({
3305
+ options: {
3306
+ date: {
3307
+ type: "string",
3308
+ default: "today"
3309
+ },
3310
+ from: {
3311
+ type: "string"
3312
+ },
3313
+ to: {
3314
+ type: "string"
3315
+ },
3316
+ project: {
3317
+ type: "string"
3318
+ },
3319
+ output: {
3320
+ type: "string",
3321
+ short: "o"
3322
+ },
3323
+ "dry-run": {
3324
+ type: "boolean",
3325
+ default: false
3326
+ },
3327
+ "check-reminder": {
3328
+ type: "boolean",
3329
+ default: false
3330
+ },
3331
+ format: {
3332
+ type: "string",
3333
+ default: "terminal"
3334
+ },
3335
+ compact: {
3336
+ type: "boolean",
3337
+ default: false
3338
+ },
3339
+ verbose: {
3340
+ type: "boolean",
3341
+ short: "v",
3342
+ default: false
3343
+ },
3344
+ "check-config": {
3345
+ type: "boolean",
3346
+ default: false
3347
+ },
3348
+ "compare-with": {
3349
+ type: "string"
3350
+ },
3351
+ "compare-week": {
3352
+ type: "boolean",
3353
+ default: false
3354
+ },
3355
+ "compare-month": {
3356
+ type: "boolean",
3357
+ default: false
3358
+ },
3359
+ history: {
3360
+ type: "boolean",
3361
+ default: false
3362
+ },
3363
+ "history-summary": {
3364
+ type: "boolean",
3365
+ default: false
3366
+ },
3367
+ "no-history": {
3368
+ type: "boolean",
3369
+ default: false
3370
+ },
3371
+ help: {
3372
+ type: "boolean",
3373
+ short: "h",
3374
+ default: false
3375
+ },
3376
+ version: {
3377
+ type: "boolean",
3378
+ default: false
3379
+ }
3380
+ },
3381
+ strict: true,
3382
+ allowPositionals: false
3383
+ });
3384
+ return {
3385
+ date: values.date || "today",
3386
+ from: values.from,
3387
+ to: values.to,
3388
+ project: values.project,
3389
+ output: values.output,
3390
+ dryRun: values["dry-run"] || false,
3391
+ checkReminder: values["check-reminder"] || false,
3392
+ help: values.help || false,
3393
+ version: values.version || false,
3394
+ verbose: values.verbose || false,
3395
+ checkConfig: values["check-config"] || false,
3396
+ format: values.format || "terminal",
3397
+ compact: values.compact || false,
3398
+ compareWith: values["compare-with"],
3399
+ compareWeek: values["compare-week"] || false,
3400
+ compareMonth: values["compare-month"] || false,
3401
+ history: values.history || false,
3402
+ historySummary: values["history-summary"] || false,
3403
+ noHistory: values["no-history"] || false
3404
+ };
3405
+ } catch (error) {
3406
+ const errorMessage = error instanceof Error ? error.message : String(error);
3407
+ throw new Error(`Invalid arguments: ${errorMessage}`);
3408
+ }
3409
+ }
3410
+ function validateArguments(args) {
3411
+ if (args.date !== "today" && (args.from || args.to)) {
3412
+ throw new Error(
3413
+ "Cannot use --date with --from/--to. Use either --date for a single day or --from/--to for a date range."
3414
+ );
3415
+ }
3416
+ if (args.from && !args.to || !args.from && args.to) {
3417
+ throw new Error("Both --from and --to must be provided together.");
3418
+ }
3419
+ if (args.from && args.to) {
3420
+ try {
3421
+ const fromDate = parseDate(args.from);
3422
+ const toDate = parseDate(args.to);
3423
+ if (isAfter(fromDate, toDate)) {
3424
+ throw new Error(
3425
+ `Invalid date range: --from (${args.from}) must be before or equal to --to (${args.to})`
3426
+ );
3427
+ }
3428
+ } catch (error) {
3429
+ if (error instanceof Error && error.message.includes("Invalid date range")) {
3430
+ throw error;
3431
+ }
3432
+ throw new Error(
3433
+ `Invalid date format in --from or --to: ${error instanceof Error ? error.message : String(error)}`
3434
+ );
3435
+ }
3436
+ }
3437
+ if (args.output) {
3438
+ const ext = extname(args.output);
3439
+ if (ext !== ".md" && ext !== ".json") {
3440
+ throw new Error(
3441
+ `Invalid output file extension: ${ext}. Expected .md or .json`
3442
+ );
3443
+ }
3444
+ }
3445
+ if (args.dryRun && args.output) {
3446
+ throw new Error("Cannot use --output with --dry-run mode.");
3447
+ }
3448
+ const comparisonFlags = [
3449
+ args.compareWith,
3450
+ args.compareWeek,
3451
+ args.compareMonth
3452
+ ].filter(Boolean);
3453
+ if (comparisonFlags.length > 1) {
3454
+ throw new Error(
3455
+ "Cannot use multiple comparison flags together. Choose one: --compare-with, --compare-week, or --compare-month."
3456
+ );
3457
+ }
3458
+ if (args.history && args.historySummary) {
3459
+ throw new Error(
3460
+ "Cannot use --history and --history-summary together. Choose one."
3461
+ );
3462
+ }
3463
+ const isComparisonMode = args.compareWith !== void 0 || args.compareWeek || args.compareMonth;
3464
+ const isHistoryMode = args.history || args.historySummary;
3465
+ if (isComparisonMode && args.from) {
3466
+ throw new Error("Cannot use comparison flags with --from/--to date range.");
3467
+ }
3468
+ if (isHistoryMode && (args.from || args.to || args.date !== "today")) {
3469
+ throw new Error(
3470
+ "Cannot use history listing flags with date filters (--date, --from, --to)."
3471
+ );
3472
+ }
3473
+ if (isHistoryMode && isComparisonMode) {
3474
+ throw new Error("Cannot use history listing flags with comparison flags.");
3475
+ }
3476
+ }
3477
+ function getOutputFilePath(basePath, date) {
3478
+ if (!date) {
3479
+ return resolve(basePath);
3480
+ }
3481
+ const ext = extname(basePath);
3482
+ const baseWithoutExt = basePath.slice(0, -ext.length);
3483
+ return resolve(`${baseWithoutExt}-${date}${ext}`);
3484
+ }
3485
+ async function writeOutputFile(filePath, result, format2, compact) {
3486
+ try {
3487
+ const content = format2 === "json" ? formatJson(result, compact) : formatMarkdown(result);
3488
+ const dir = dirname(filePath);
3489
+ await mkdir(dir, { recursive: true });
3490
+ const tmpFile = `${filePath}.tmp`;
3491
+ await writeFile(tmpFile, content, "utf-8");
3492
+ await rename(tmpFile, filePath);
3493
+ } catch (error) {
3494
+ const errorMessage = error instanceof Error ? error.message : String(error);
3495
+ throw new Error(`Failed to write output file ${filePath}: ${errorMessage}`);
3496
+ }
3497
+ }
3498
+ async function writeMultiDayJsonOutput(filePath, results, compact) {
3499
+ try {
3500
+ const content = compact ? JSON.stringify(results) : JSON.stringify(results, null, 2);
3501
+ const dir = dirname(filePath);
3502
+ await mkdir(dir, { recursive: true });
3503
+ const tmpFile = `${filePath}.tmp`;
3504
+ await writeFile(tmpFile, content, "utf-8");
3505
+ await rename(tmpFile, filePath);
3506
+ } catch (error) {
3507
+ const errorMessage = error instanceof Error ? error.message : String(error);
3508
+ throw new Error(`Failed to write output file ${filePath}: ${errorMessage}`);
3509
+ }
3510
+ }
3511
+ function displayDryRunSummary(prompts3, args) {
3512
+ console.log("");
3513
+ console.log(chalk6.bold.cyan("Dry Run Mode - Preview"));
3514
+ console.log("");
3515
+ if (args.from && args.to) {
3516
+ console.log(chalk6.bold("Date Range:"), `${args.from} to ${args.to}`);
3517
+ } else {
3518
+ console.log(chalk6.bold("Date:"), args.date);
3519
+ }
3520
+ if (args.project) {
3521
+ console.log(chalk6.bold("Project Filter:"), args.project);
3522
+ }
3523
+ const projects = Array.from(new Set(prompts3.map((p) => p.project))).sort();
3524
+ console.log(chalk6.bold("Projects Found:"), projects.join(", "));
3525
+ console.log(chalk6.bold("Total Prompts:"), String(prompts3.length));
3526
+ console.log("");
3527
+ console.log(chalk6.bold("Sample Prompts:"));
3528
+ console.log("");
3529
+ const samples = prompts3.slice(0, 3);
3530
+ for (const [index, prompt] of samples.entries()) {
3531
+ const truncated = prompt.content.length > 150 ? prompt.content.slice(0, 150) + "..." : prompt.content;
3532
+ console.log(chalk6.dim(`${String(index + 1)}. ${truncated}`));
3533
+ }
3534
+ if (prompts3.length > 3) {
3535
+ console.log(chalk6.dim(`... and ${String(prompts3.length - 3)} more`));
3536
+ }
3537
+ console.log("");
3538
+ console.log(
3539
+ chalk6.yellow("This is a dry run. No analysis will be performed.")
3540
+ );
3541
+ }
3542
+ function showReminderStatus() {
3543
+ const config = getEnvConfig();
3544
+ const lastRun = getLastRun();
3545
+ const daysElapsed = getDaysElapsed();
3546
+ console.log("");
3547
+ console.log(chalk6.bold.cyan("Reminder Status"));
3548
+ console.log("");
3549
+ if (lastRun) {
3550
+ console.log(chalk6.bold("Last Run:"), lastRun);
3551
+ console.log(chalk6.bold("Days Elapsed:"), String(daysElapsed));
3552
+ } else {
3553
+ console.log(chalk6.bold("Last Run:"), chalk6.dim("Never"));
3554
+ }
3555
+ console.log(chalk6.bold("Reminder Frequency:"), config.reminder);
3556
+ const isDue = shouldShowReminder();
3557
+ const status = isDue ? chalk6.yellow("Due") : chalk6.green("Not Due");
3558
+ console.log(chalk6.bold("Status:"), status);
3559
+ console.log("");
3560
+ process.exit(EXIT_CODES.SUCCESS);
3561
+ }
3562
+ function showHelp() {
3563
+ const helpText = `
3564
+ ${chalk6.bold("Usage:")} hyntx [options]
3565
+
3566
+ ${chalk6.bold("Options:")}
3567
+ ${chalk6.bold("Date Filtering:")}
3568
+ --date <date> Date to analyze (today, yesterday, YYYY-MM-DD) [default: today]
3569
+ --from <date> Start date for range (requires --to, YYYY-MM-DD)
3570
+ --to <date> End date for range (requires --from, YYYY-MM-DD)
3571
+
3572
+ ${chalk6.bold("Filtering:")}
3573
+ --project <name> Filter by project name (partial match, case-insensitive)
3574
+
3575
+ ${chalk6.bold("Output:")}
3576
+ --format <type> Output format: terminal, json [default: terminal]
3577
+ --compact Compact JSON output (only with --format json)
3578
+ -o, --output <file> Write results to file (.md or .json extension)
3579
+ --dry-run Preview prompts without performing analysis
3580
+
3581
+ ${chalk6.bold("Comparison:")}
3582
+ --compare-with <date> Compare current analysis with a specific date (YYYY-MM-DD)
3583
+ --compare-week Compare current analysis with one week ago
3584
+ --compare-month Compare current analysis with one month ago
3585
+
3586
+ ${chalk6.bold("History:")}
3587
+ --history List all analysis history entries
3588
+ --history-summary Show summary statistics of analysis history
3589
+ --no-history Skip saving this analysis to history
3590
+
3591
+ ${chalk6.bold("Configuration:")}
3592
+ -v, --verbose Enable debug output to stderr
3593
+ --check-config Validate configuration and test provider connectivity
3594
+ --check-reminder Show reminder status and exit
3595
+
3596
+ ${chalk6.bold("Information:")}
3597
+ -h, --help Show help
3598
+ --version Show version
3599
+
3600
+ ${chalk6.bold("Exit codes:")}
3601
+ ${String(EXIT_CODES.SUCCESS)} - Success
3602
+ ${String(EXIT_CODES.ERROR)} - Error
3603
+ ${String(EXIT_CODES.NO_DATA)} - No data found
3604
+ ${String(EXIT_CODES.PROVIDER_UNAVAILABLE)} - Provider unavailable
3605
+
3606
+ ${chalk6.bold("Examples:")}
3607
+ ${chalk6.bold("Basic usage:")}
3608
+ hyntx # Analyze today's prompts
3609
+ hyntx --date yesterday # Analyze yesterday
3610
+ hyntx --date 2025-01-20 # Specific date
3611
+
3612
+ ${chalk6.bold("Date ranges:")}
3613
+ hyntx --from 2025-01-20 --to 2025-01-25 # Analyze date range
3614
+
3615
+ ${chalk6.bold("Filtering:")}
3616
+ hyntx --project my-app # Filter by project name
3617
+ hyntx --from 2025-01-20 --to 2025-01-25 --project backend
3618
+
3619
+ ${chalk6.bold("Output formats:")}
3620
+ hyntx --format json # Output as formatted JSON
3621
+ hyntx --format json --compact # Output as compact JSON
3622
+ hyntx -o report.md # Save as Markdown file
3623
+ hyntx -o report.json # Save as JSON file
3624
+ hyntx --from 2025-01-20 --to 2025-01-25 -o report.md # Multi-day creates separate files
3625
+
3626
+ ${chalk6.bold("Dry run:")}
3627
+ hyntx --dry-run # Preview without analysis
3628
+ hyntx --from 2025-01-20 --to 2025-01-25 --dry-run # Preview date range
3629
+
3630
+ ${chalk6.bold("Comparison:")}
3631
+ hyntx --compare-week # Compare today with one week ago
3632
+ hyntx --compare-month # Compare today with one month ago
3633
+ hyntx --compare-with 2025-01-15 # Compare with specific date
3634
+
3635
+ ${chalk6.bold("History:")}
3636
+ hyntx --history # List all history entries
3637
+ hyntx --history-summary # Show history statistics
3638
+ hyntx --no-history # Analyze without saving to history
3639
+
3640
+ ${chalk6.bold("Status checks:")}
3641
+ hyntx --check-config # Validate configuration
3642
+ hyntx --check-reminder # Show reminder status
3643
+ `;
3644
+ console.log(helpText);
3645
+ process.exit(EXIT_CODES.SUCCESS);
3646
+ }
3647
+ function showVersion() {
3648
+ console.log(`hyntx v${VERSION}`);
3649
+ process.exit(EXIT_CODES.SUCCESS);
3650
+ }
3651
+ async function runConfigCheck() {
3652
+ const config = getEnvConfig();
3653
+ logger.debug("Running configuration health check", "cli");
3654
+ const result = await validateAllProviders(config);
3655
+ printHealthCheckResult(result, config);
3656
+ if (result.allValid) {
3657
+ process.exit(EXIT_CODES.SUCCESS);
3658
+ } else if (result.summary.availableCount > 0) {
3659
+ process.exit(EXIT_CODES.SUCCESS);
3660
+ } else {
3661
+ process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
3662
+ }
3663
+ }
3664
+ async function checkAndRunSetup(isJsonMode) {
3665
+ if (isFirstRun()) {
3666
+ if (!isJsonMode) {
3667
+ const spinner = ora("Running first-time setup...").start();
3668
+ spinner.stop();
3669
+ }
3670
+ await runSetup();
3671
+ }
3672
+ }
3673
+ async function readLogsWithSpinner(args, isJsonMode) {
3674
+ if (!claudeProjectsExist()) {
3675
+ if (isJsonMode) {
3676
+ const errorResponse = {
3677
+ error: "Claude Code logs directory not found",
3678
+ code: "NO_DATA"
3679
+ };
3680
+ console.log(JSON.stringify(errorResponse));
3681
+ } else {
3682
+ logger.error("Claude Code logs directory not found");
3683
+ process.stderr.write(
3684
+ chalk6.dim(`Expected location: ${CLAUDE_PROJECTS_DIR}
3685
+ `)
3686
+ );
3687
+ process.stderr.write(
3688
+ chalk6.dim(
3689
+ "\nMake sure Claude Code is installed and has been used at least once.\n"
3690
+ )
3691
+ );
3692
+ }
3693
+ process.exit(EXIT_CODES.NO_DATA);
3694
+ }
3695
+ let spinnerMessage = "Reading Claude Code logs";
3696
+ if (args.from && args.to) {
3697
+ spinnerMessage += ` from ${args.from} to ${args.to}`;
3698
+ } else {
3699
+ spinnerMessage += ` for ${args.date}`;
3700
+ }
3701
+ if (args.project) {
3702
+ spinnerMessage += ` (project: ${args.project})`;
3703
+ }
3704
+ spinnerMessage += "...";
3705
+ const spinner = isJsonMode ? null : ora(spinnerMessage).start();
3706
+ try {
3707
+ const options = {
3708
+ date: args.from || args.to ? void 0 : args.date,
3709
+ from: args.from,
3710
+ to: args.to,
3711
+ project: args.project
3712
+ };
3713
+ const result = await readLogs(options);
3714
+ if (result.prompts.length === 0) {
3715
+ const noDataMessage = args.from && args.to ? `No prompts found from ${args.from} to ${args.to}` : `No prompts found for ${args.date}`;
3716
+ if (isJsonMode) {
3717
+ const errorResponse = {
3718
+ error: noDataMessage,
3719
+ code: "NO_DATA"
3720
+ };
3721
+ console.log(JSON.stringify(errorResponse));
3722
+ } else {
3723
+ spinner?.fail(chalk6.yellow(noDataMessage));
3724
+ process.stderr.write(
3725
+ chalk6.dim(
3726
+ "\nTry a different date or check that Claude Code has been used recently.\n"
3727
+ )
3728
+ );
3729
+ }
3730
+ process.exit(EXIT_CODES.NO_DATA);
3731
+ }
3732
+ if (!isJsonMode) {
3733
+ const successMessage = args.from && args.to ? `Found ${String(result.prompts.length)} prompts from ${args.from} to ${args.to}` : `Found ${String(result.prompts.length)} prompts for ${args.date}`;
3734
+ spinner?.succeed(chalk6.green(successMessage));
3735
+ }
3736
+ return result;
3737
+ } catch (error) {
3738
+ const errorMessage = error instanceof Error ? error.message : String(error);
3739
+ if (isJsonMode) {
3740
+ const errorResponse = {
3741
+ error: `Failed to read logs: ${errorMessage}`,
3742
+ code: "ERROR"
3743
+ };
3744
+ console.log(JSON.stringify(errorResponse));
3745
+ } else {
3746
+ spinner?.fail(chalk6.red(`Failed to read logs: ${errorMessage}`));
3747
+ }
3748
+ process.exit(EXIT_CODES.ERROR);
3749
+ }
3750
+ }
3751
+ async function connectProviderWithSpinner(isJsonMode) {
3752
+ const config = getEnvConfig();
3753
+ if (config.services.length === 0) {
3754
+ if (isJsonMode) {
3755
+ const errorResponse = {
3756
+ error: "No providers configured",
3757
+ code: "PROVIDER_UNAVAILABLE"
3758
+ };
3759
+ console.log(JSON.stringify(errorResponse));
3760
+ } else {
3761
+ logger.error("No providers configured");
3762
+ process.stderr.write(
3763
+ chalk6.dim("\nRun setup to configure at least one provider.\n")
3764
+ );
3765
+ }
3766
+ process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
3767
+ }
3768
+ const spinner = isJsonMode ? null : ora("Connecting to provider...").start();
3769
+ try {
3770
+ const provider = await getAvailableProvider(config, (from, to) => {
3771
+ if (!isJsonMode && spinner) {
3772
+ spinner.text = chalk6.yellow(
3773
+ `Primary provider ${from} unavailable, falling back to ${to}...`
3774
+ );
3775
+ }
3776
+ logger.collectWarning(
3777
+ `Provider ${from} unavailable, fell back to ${to}`,
3778
+ "provider"
3779
+ );
3780
+ });
3781
+ if (!isJsonMode) {
3782
+ spinner?.succeed(chalk6.green(`Connected to ${provider.name}`));
3783
+ }
3784
+ return provider;
3785
+ } catch (error) {
3786
+ const errorMessage = error instanceof Error ? error.message : String(error);
3787
+ if (isJsonMode) {
3788
+ const errorResponse = {
3789
+ error: errorMessage,
3790
+ code: "PROVIDER_UNAVAILABLE"
3791
+ };
3792
+ console.log(JSON.stringify(errorResponse));
3793
+ } else {
3794
+ spinner?.fail(chalk6.red("No providers available"));
3795
+ process.stderr.write(chalk6.dim(`
3796
+ ${errorMessage}
3797
+ `));
3798
+ process.stderr.write(
3799
+ chalk6.dim(
3800
+ "\nCheck your provider configuration and ensure at least one provider is running.\n"
3801
+ )
3802
+ );
3803
+ }
3804
+ process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
3805
+ }
3806
+ }
3807
+ async function analyzeWithProgress(provider, prompts3, date, context, isJsonMode) {
3808
+ const spinner = isJsonMode ? null : ora(`Analyzing ${String(prompts3.length)} prompts...`).start();
3809
+ try {
3810
+ const result = await analyzePrompts({
3811
+ provider,
3812
+ prompts: prompts3,
3813
+ date,
3814
+ context,
3815
+ onProgress: (current, total) => {
3816
+ if (!isJsonMode && spinner && total > 1) {
3817
+ spinner.text = `Analyzing ${String(prompts3.length)} prompts (batch ${String(current + 1)}/${String(total)})...`;
3818
+ }
3819
+ }
3820
+ });
3821
+ if (!isJsonMode) {
3822
+ spinner?.succeed(chalk6.green("Analysis complete"));
3823
+ }
3824
+ return result;
3825
+ } catch (error) {
3826
+ const errorMessage = error instanceof Error ? error.message : String(error);
3827
+ if (isJsonMode) {
3828
+ const errorResponse = {
3829
+ error: `Analysis failed: ${errorMessage}`,
3830
+ code: "ERROR"
3831
+ };
3832
+ console.log(JSON.stringify(errorResponse));
3833
+ } else {
3834
+ spinner?.fail(chalk6.red(`Analysis failed: ${errorMessage}`));
3835
+ }
3836
+ process.exit(EXIT_CODES.ERROR);
3837
+ }
3838
+ }
3839
+ function displayResults(result, format2, compact) {
3840
+ if (format2 === "json") {
3841
+ console.log(formatJson(result, compact));
3842
+ } else {
3843
+ console.log("");
3844
+ printReport(result);
3845
+ }
3846
+ }
3847
+ function handleError(error, isJsonMode) {
3848
+ if (isJsonMode) {
3849
+ const errorResponse = {
3850
+ error: error.message,
3851
+ code: "ERROR"
3852
+ };
3853
+ console.log(JSON.stringify(errorResponse));
3854
+ } else {
3855
+ logger.error(error.message);
3856
+ }
3857
+ process.exit(EXIT_CODES.ERROR);
3858
+ }
3859
+ async function main() {
3860
+ let isJsonMode = false;
2061
3861
  try {
2062
3862
  const args = parseArguments();
3863
+ validateArguments(args);
3864
+ isJsonMode = args.format === "json";
3865
+ if (args.verbose) {
3866
+ logger.setVerbose(true);
3867
+ logger.debug("Verbose mode enabled");
3868
+ }
2063
3869
  if (args.help) {
2064
3870
  showHelp();
2065
3871
  }
2066
3872
  if (args.version) {
2067
3873
  showVersion();
2068
3874
  }
2069
- await checkAndRunSetup();
2070
- const prompts2 = await readLogsWithSpinner(args.date);
2071
- const provider = await connectProviderWithSpinner();
2072
- const result = await analyzeWithProgress(provider, prompts2, args.date);
2073
- displayResults(result);
3875
+ if (args.checkConfig) {
3876
+ await runConfigCheck();
3877
+ }
3878
+ if (args.checkReminder) {
3879
+ showReminderStatus();
3880
+ }
3881
+ if (args.history || args.historySummary) {
3882
+ const dates = await listAvailableDates();
3883
+ const entries = [];
3884
+ for (const date of dates) {
3885
+ const entry = await loadAnalysisResult(date);
3886
+ if (entry) {
3887
+ entries.push([date, entry]);
3888
+ }
3889
+ }
3890
+ if (args.history) {
3891
+ printHistoryList(entries);
3892
+ } else {
3893
+ printHistorySummary(entries);
3894
+ }
3895
+ process.exit(EXIT_CODES.SUCCESS);
3896
+ }
3897
+ await checkAndRunSetup(isJsonMode);
3898
+ if (!args.dryRun && !isJsonMode) {
3899
+ const shouldContinue = await checkReminder();
3900
+ if (!shouldContinue) {
3901
+ process.exit(EXIT_CODES.SUCCESS);
3902
+ }
3903
+ }
3904
+ const envConfig = getEnvConfig();
3905
+ const projectConfig = loadProjectConfigForCwd(process.cwd());
3906
+ const config = mergeConfigs(envConfig, projectConfig);
3907
+ const logResult = await readLogsWithSpinner(args, isJsonMode);
3908
+ if (args.dryRun) {
3909
+ displayDryRunSummary(logResult.prompts, args);
3910
+ process.exit(EXIT_CODES.SUCCESS);
3911
+ }
3912
+ const isMultiDay = Boolean(args.from && args.to);
3913
+ const groups = isMultiDay ? groupByDay(logResult.prompts) : [];
3914
+ const provider = await connectProviderWithSpinner(isJsonMode);
3915
+ if (isMultiDay && groups.length > 0) {
3916
+ const results = [];
3917
+ for (const group of groups) {
3918
+ const prompts3 = group.prompts.map((p) => p.content);
3919
+ const result = await analyzeWithProgress(
3920
+ provider,
3921
+ prompts3,
3922
+ group.date,
3923
+ config.context,
3924
+ isJsonMode
3925
+ );
3926
+ results.push(result);
3927
+ }
3928
+ if (args.output) {
3929
+ const ext = extname(args.output);
3930
+ const format2 = ext === ".json" ? "json" : "md";
3931
+ if (format2 === "json") {
3932
+ const outputPath = getOutputFilePath(args.output);
3933
+ await writeMultiDayJsonOutput(outputPath, results, args.compact);
3934
+ if (!isJsonMode) {
3935
+ console.log("");
3936
+ console.log(chalk6.green(`Results written to ${outputPath}`));
3937
+ }
3938
+ } else {
3939
+ const outputBasePath = args.output;
3940
+ const writeResults = await Promise.allSettled(
3941
+ results.map(async (result) => {
3942
+ const outputPath = getOutputFilePath(outputBasePath, result.date);
3943
+ await writeOutputFile(outputPath, result, "md", false);
3944
+ return { date: result.date, path: outputPath };
3945
+ })
3946
+ );
3947
+ const failures = writeResults.filter((r) => r.status === "rejected");
3948
+ if (failures.length > 0) {
3949
+ if (isJsonMode) {
3950
+ const errorResponse = {
3951
+ error: `Failed to write ${String(failures.length)} file(s)`,
3952
+ code: "ERROR"
3953
+ };
3954
+ console.log(JSON.stringify(errorResponse));
3955
+ } else {
3956
+ logger.error(
3957
+ `Failed to write ${String(failures.length)} file(s)`,
3958
+ "cli"
3959
+ );
3960
+ for (const f of failures) {
3961
+ logger.error(` ${String(f.reason)}`, "cli");
3962
+ }
3963
+ }
3964
+ process.exit(EXIT_CODES.ERROR);
3965
+ }
3966
+ if (!isJsonMode) {
3967
+ writeResults.forEach((r) => {
3968
+ if (r.status === "fulfilled") {
3969
+ console.log(
3970
+ chalk6.green(`\u2713 ${r.value.date} written to ${r.value.path}`)
3971
+ );
3972
+ }
3973
+ });
3974
+ }
3975
+ }
3976
+ }
3977
+ if (!args.output || !isJsonMode) {
3978
+ if (args.format === "json") {
3979
+ console.log(
3980
+ args.compact ? JSON.stringify(results) : JSON.stringify(results, null, 2)
3981
+ );
3982
+ } else {
3983
+ for (const result of results) {
3984
+ console.log("");
3985
+ console.log(chalk6.bold.cyan(`Results for ${result.date}`));
3986
+ displayResults(result, "terminal", false);
3987
+ }
3988
+ }
3989
+ }
3990
+ } else {
3991
+ const prompts3 = logResult.prompts.map((p) => p.content);
3992
+ const date = args.date;
3993
+ const result = await analyzeWithProgress(
3994
+ provider,
3995
+ prompts3,
3996
+ date,
3997
+ config.context,
3998
+ isJsonMode
3999
+ );
4000
+ if (args.output) {
4001
+ const ext = extname(args.output);
4002
+ const format2 = ext === ".json" ? "json" : "md";
4003
+ const outputPath = getOutputFilePath(args.output);
4004
+ await writeOutputFile(outputPath, result, format2, args.compact);
4005
+ if (!isJsonMode) {
4006
+ console.log("");
4007
+ console.log(chalk6.green(`Results written to ${outputPath}`));
4008
+ }
4009
+ }
4010
+ if (!args.output || !isJsonMode) {
4011
+ displayResults(result, args.format, args.compact);
4012
+ }
4013
+ if (!args.noHistory) {
4014
+ const projects = Array.from(
4015
+ new Set(logResult.prompts.map((p) => p.project))
4016
+ );
4017
+ const metadata = {
4018
+ provider: provider.name,
4019
+ promptCount: prompts3.length,
4020
+ projects
4021
+ };
4022
+ await saveAnalysisResult(result, metadata);
4023
+ }
4024
+ if (args.compareWith !== void 0 || args.compareWeek || args.compareMonth) {
4025
+ const compareDate = args.compareWith ?? (args.compareWeek ? getDateOneWeekAgo(result.date) : getDateOneMonthAgo(result.date));
4026
+ const beforeEntry = await loadAnalysisResult(compareDate);
4027
+ if (!beforeEntry) {
4028
+ if (isJsonMode) {
4029
+ const errorResponse = {
4030
+ error: `No history found for ${compareDate}`,
4031
+ code: "NO_DATA"
4032
+ };
4033
+ console.log(JSON.stringify(errorResponse));
4034
+ } else {
4035
+ logger.error(`No history found for ${compareDate}`);
4036
+ process.stderr.write(
4037
+ chalk6.dim(
4038
+ "\nRun analysis for that date first to enable comparison.\n"
4039
+ )
4040
+ );
4041
+ }
4042
+ process.exit(EXIT_CODES.NO_DATA);
4043
+ }
4044
+ const comparison = compareResults(beforeEntry.result, result);
4045
+ if (isJsonMode) {
4046
+ console.log(formatComparisonJson(comparison, args.compact));
4047
+ } else {
4048
+ printComparison(comparison);
4049
+ }
4050
+ }
4051
+ }
4052
+ saveLastRun();
4053
+ if (!isJsonMode) {
4054
+ logger.reportWarnings();
4055
+ }
2074
4056
  process.exit(EXIT_CODES.SUCCESS);
2075
4057
  } catch (error) {
2076
- handleError(error instanceof Error ? error : new Error(String(error)));
4058
+ if (!isJsonMode) {
4059
+ logger.reportWarnings();
4060
+ }
4061
+ handleError(
4062
+ error instanceof Error ? error : new Error(String(error)),
4063
+ isJsonMode
4064
+ );
2077
4065
  }
2078
4066
  }
2079
- var isMainModule = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
4067
+ var isMainModule = (() => {
4068
+ try {
4069
+ return process.argv[1] !== void 0 && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
4070
+ } catch {
4071
+ return false;
4072
+ }
4073
+ })();
2080
4074
  if (isMainModule) {
2081
4075
  void main();
2082
4076
  }
2083
4077
 
2084
- export { analyzeWithProgress, checkAndRunSetup, connectProviderWithSpinner, displayResults, handleError, main, parseArguments, readLogsWithSpinner, showHelp, showVersion };
2085
- //# sourceMappingURL=index.js.map
2086
- //# sourceMappingURL=index.js.map
4078
+ export { analyzeWithProgress, checkAndRunSetup, connectProviderWithSpinner, displayDryRunSummary, displayResults, getOutputFilePath, handleError, main, parseArguments, readLogsWithSpinner, runConfigCheck, showHelp, showReminderStatus, showVersion, validateArguments, writeMultiDayJsonOutput, writeOutputFile };