hyntx 1.1.0 → 1.3.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,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import chalk3 from 'chalk';
3
- import { readFileSync, existsSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
2
+ import chalk6 from 'chalk';
3
+ import { readFileSync, realpathSync, existsSync, readdirSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
4
4
  import { homedir } from 'os';
5
- import { join, dirname, basename } from 'path';
5
+ import { join, dirname, extname, resolve, basename } from 'path';
6
6
  import { parseArgs } from 'util';
7
+ import { readFile, mkdir, writeFile, rename } from 'fs/promises';
7
8
  import { fileURLToPath } from 'url';
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';
@@ -54,7 +54,7 @@ var init_logger = __esm({
54
54
  */
55
55
  error(message, context) {
56
56
  const prefix = context ? `[${context}] ` : "";
57
- process.stderr.write(chalk3.red(`ERROR: ${prefix}${message}
57
+ process.stderr.write(chalk6.red(`ERROR: ${prefix}${message}
58
58
  `));
59
59
  }
60
60
  /**
@@ -65,7 +65,7 @@ var init_logger = __esm({
65
65
  */
66
66
  warn(message, context) {
67
67
  const prefix = context ? `[${context}] ` : "";
68
- process.stderr.write(chalk3.yellow(`WARN: ${prefix}${message}
68
+ process.stderr.write(chalk6.yellow(`WARN: ${prefix}${message}
69
69
  `));
70
70
  }
71
71
  /**
@@ -74,7 +74,7 @@ var init_logger = __esm({
74
74
  * @param message - Info message
75
75
  */
76
76
  info(message) {
77
- process.stderr.write(chalk3.blue(`INFO: ${message}
77
+ process.stderr.write(chalk6.blue(`INFO: ${message}
78
78
  `));
79
79
  }
80
80
  /**
@@ -86,7 +86,7 @@ var init_logger = __esm({
86
86
  debug(message, context) {
87
87
  if (this.verboseEnabled) {
88
88
  const prefix = context ? `[${context}] ` : "";
89
- process.stderr.write(chalk3.gray(`[DEBUG] ${prefix}${message}
89
+ process.stderr.write(chalk6.gray(`[DEBUG] ${prefix}${message}
90
90
  `));
91
91
  }
92
92
  }
@@ -131,13 +131,13 @@ var init_logger = __esm({
131
131
  return;
132
132
  }
133
133
  process.stderr.write(
134
- chalk3.yellow(`
134
+ chalk6.yellow(`
135
135
  \u26A0\uFE0F ${String(this.warnings.length)} warning(s):
136
136
  `)
137
137
  );
138
138
  for (const warning of this.warnings) {
139
139
  const prefix = warning.context ? `[${warning.context}] ` : "";
140
- process.stderr.write(chalk3.yellow(` - ${prefix}${warning.message}
140
+ process.stderr.write(chalk6.yellow(` - ${prefix}${warning.message}
141
141
  `));
142
142
  }
143
143
  this.clearWarnings();
@@ -163,11 +163,48 @@ var init_logger = __esm({
163
163
  var shell_config_exports = {};
164
164
  __export(shell_config_exports, {
165
165
  detectShellConfigFile: () => detectShellConfigFile,
166
+ findMarkerPositions: () => findMarkerPositions,
166
167
  generateEnvExports: () => generateEnvExports,
167
168
  getManualInstructions: () => getManualInstructions,
169
+ removeMalformedMarkers: () => removeMalformedMarkers,
168
170
  saveConfigToShell: () => saveConfigToShell,
169
171
  updateShellConfig: () => updateShellConfig
170
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
+ }
171
208
  function detectShellConfigFile() {
172
209
  const home = homedir();
173
210
  const shell = process.env["SHELL"] ?? "";
@@ -222,15 +259,13 @@ function generateEnvExports(config) {
222
259
  return lines;
223
260
  }
224
261
  function updateShellConfig(configFile, exports$1) {
225
- const startMarker = "# >>> hyntx config >>>";
226
- const endMarker = "# <<< hyntx config <<<";
227
262
  const exportLines = exports$1.map((line) => ` ${line}`).join("\n");
228
- const configBlock = `${startMarker}
263
+ const configBlock = `${START_MARKER}
229
264
  ${exportLines}
230
265
 
231
266
  # Uncomment to enable periodic reminders:
232
267
  # hyntx --check-reminder 2>/dev/null
233
- ${endMarker}
268
+ ${END_MARKER}
234
269
  `;
235
270
  try {
236
271
  let content = "";
@@ -239,27 +274,24 @@ ${endMarker}
239
274
  content = readFileSync(configFile, "utf-8");
240
275
  action = "updated";
241
276
  }
242
- const hasStartMarker = content.includes(startMarker);
243
- const hasEndMarker = content.includes(endMarker);
244
- if (hasStartMarker && hasEndMarker) {
245
- const startIndex = content.indexOf(startMarker);
246
- const endIndex = content.indexOf(endMarker) + endMarker.length;
247
- const before = content.slice(0, startIndex);
248
- const after = content.slice(endIndex);
249
- const beforeTrimmed = before.endsWith("\n") ? before.slice(0, -1) : before;
250
- content = `${beforeTrimmed}
251
- ${configBlock}${after}`.trim() + "\n";
252
- } else if (hasStartMarker || hasEndMarker) {
253
- const startIndex = hasStartMarker ? content.indexOf(startMarker) : content.indexOf(endMarker);
254
- const endIndex = hasEndMarker ? content.indexOf(endMarker) + endMarker.length : content.indexOf(startMarker) + startMarker.length;
255
- const before = content.slice(0, startIndex);
256
- 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);
257
284
  const beforeTrimmed = before.endsWith("\n") ? before.slice(0, -1) : before;
258
285
  content = `${beforeTrimmed}
259
286
  ${configBlock}${after}`.trim() + "\n";
260
287
  } else {
261
- const separator = content && !content.endsWith("\n") ? "\n\n" : "\n";
262
- 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}`;
263
295
  }
264
296
  try {
265
297
  mkdirSync(dirname(configFile), { recursive: true });
@@ -317,9 +349,12 @@ function getManualInstructions(config) {
317
349
  ];
318
350
  return instructions.join("\n");
319
351
  }
352
+ var START_MARKER, END_MARKER;
320
353
  var init_shell_config = __esm({
321
354
  "src/utils/shell-config.ts"() {
322
355
  init_logger();
356
+ START_MARKER = "# >>> hyntx config >>>";
357
+ END_MARKER = "# <<< hyntx config <<<";
323
358
  }
324
359
  });
325
360
 
@@ -385,8 +420,9 @@ function getEnvConfig() {
385
420
  };
386
421
  }
387
422
  var HOME = homedir();
388
- var CLAUDE_PROJECTS_DIR = join(HOME, ".claude", "projects");
389
- 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");
390
426
 
391
427
  // src/core/schema-validator.ts
392
428
  var SUPPORTED_VERSIONS = ["1.0"];
@@ -535,6 +571,13 @@ function extractDate(timestamp) {
535
571
  return "unknown";
536
572
  }
537
573
  }
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
+ }
538
581
  function parseLine(line, lineNumber, filePath) {
539
582
  if (!line.trim()) {
540
583
  return null;
@@ -550,6 +593,10 @@ function parseLine(line, lineNumber, filePath) {
550
593
  );
551
594
  return null;
552
595
  }
596
+ if (!isClaudeMessage(parsed)) {
597
+ logger.debug("Type guard validation failed", context);
598
+ return null;
599
+ }
553
600
  return parsed;
554
601
  } catch (error) {
555
602
  const errorMessage = error instanceof Error ? error.message : "Parse error";
@@ -561,14 +608,10 @@ function isUserMessage(message) {
561
608
  return message.type === "user" && message.message.role === "user";
562
609
  }
563
610
  function extractContent(message) {
564
- const content = message.message.content;
565
- if (typeof content === "string") {
566
- return content;
567
- }
568
- return "";
611
+ return message.message.content;
569
612
  }
570
613
  async function readJsonlFile(filePath) {
571
- const prompts2 = [];
614
+ const prompts3 = [];
572
615
  const warnings = [];
573
616
  const projectName = extractProjectName(filePath);
574
617
  try {
@@ -592,7 +635,7 @@ async function readJsonlFile(filePath) {
592
635
  if (!extractedContent.trim()) {
593
636
  continue;
594
637
  }
595
- prompts2.push({
638
+ prompts3.push({
596
639
  content: extractedContent,
597
640
  timestamp: message.timestamp,
598
641
  sessionId: message.sessionId,
@@ -611,35 +654,94 @@ async function readJsonlFile(filePath) {
611
654
  warnings.push(warning);
612
655
  logger.error(warning, "log-reader");
613
656
  }
614
- return { prompts: prompts2, warnings };
657
+ return { prompts: prompts3, warnings };
615
658
  }
616
- function filterByDateRange(prompts2, fromDate, toDate) {
617
- return prompts2.filter((prompt) => {
659
+ function filterByDateRange(prompts3, fromDate, toDate) {
660
+ return prompts3.filter((prompt) => {
618
661
  try {
619
662
  const promptDate = parseISO(prompt.timestamp);
620
663
  const promptDay = startOfDay(promptDate);
621
664
  return (isSameDay(promptDay, fromDate) || isAfter(promptDay, fromDate)) && (isSameDay(promptDay, toDate) || isBefore(promptDay, toDate));
622
- } 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
+ );
623
671
  return false;
624
672
  }
625
673
  });
626
674
  }
627
- function filterByDate(prompts2, targetDate) {
628
- return prompts2.filter((prompt) => {
675
+ function filterByDate(prompts3, targetDate) {
676
+ return prompts3.filter((prompt) => {
629
677
  try {
630
678
  const promptDate = parseISO(prompt.timestamp);
631
679
  return isSameDay(startOfDay(promptDate), targetDate);
632
- } 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
+ );
633
686
  return false;
634
687
  }
635
688
  });
636
689
  }
637
- function filterByProject(prompts2, projectName) {
690
+ function filterByProject(prompts3, projectName) {
638
691
  const normalizedProject = projectName.toLowerCase().trim();
639
- return prompts2.filter(
692
+ return prompts3.filter(
640
693
  (prompt) => prompt.project.toLowerCase().includes(normalizedProject)
641
694
  );
642
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
+ }
643
745
  async function readLogs(options) {
644
746
  logger.debug(`Scanning ${CLAUDE_PROJECTS_DIR}`, "log-reader");
645
747
  if (!claudeProjectsExist()) {
@@ -652,7 +754,18 @@ async function readLogs(options) {
652
754
  };
653
755
  }
654
756
  const pattern = `${CLAUDE_PROJECTS_DIR}/**/*.jsonl`;
655
- 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
+ }
656
769
  logger.debug(`Found ${String(files.length)} JSONL files`, "log-reader");
657
770
  if (files.length === 0) {
658
771
  return {
@@ -662,10 +775,14 @@ async function readLogs(options) {
662
775
  }
663
776
  const allPrompts = [];
664
777
  const allWarnings = [];
665
- for (const file of files) {
666
- const { prompts: prompts2, warnings } = await readJsonlFile(file);
667
- allPrompts.push(...prompts2);
668
- 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
+ }
669
786
  }
670
787
  logger.debug(
671
788
  `Parsed ${String(allPrompts.length)} total prompts from all files`,
@@ -724,7 +841,12 @@ async function readLogs(options) {
724
841
  const dateA = parseISO(a.timestamp);
725
842
  const dateB = parseISO(b.timestamp);
726
843
  return dateA.getTime() - dateB.getTime();
727
- } 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
+ );
728
850
  return 0;
729
851
  }
730
852
  });
@@ -769,12 +891,20 @@ async function configureProvider(provider, config) {
769
891
  message: "Ollama model to use:",
770
892
  initial: ENV_DEFAULTS.ollama.model
771
893
  });
894
+ if (!("model" in response2)) {
895
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
896
+ process.exit(EXIT_CODES.ERROR);
897
+ }
772
898
  const hostResponse = await prompts({
773
899
  type: "text",
774
900
  name: "host",
775
901
  message: "Ollama host:",
776
902
  initial: ENV_DEFAULTS.ollama.host
777
903
  });
904
+ if (!("host" in hostResponse)) {
905
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
906
+ process.exit(EXIT_CODES.ERROR);
907
+ }
778
908
  return {
779
909
  ...config,
780
910
  ollama: {
@@ -790,12 +920,20 @@ async function configureProvider(provider, config) {
790
920
  message: "Anthropic model to use:",
791
921
  initial: ENV_DEFAULTS.anthropic.model
792
922
  });
923
+ if (!("model" in response2)) {
924
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
925
+ process.exit(EXIT_CODES.ERROR);
926
+ }
793
927
  const apiKeyResponse2 = await prompts({
794
928
  type: "password",
795
929
  name: "apiKey",
796
930
  message: "Anthropic API key:",
797
931
  validate: (value) => value.trim() !== "" || "API key is required"
798
932
  });
933
+ if (!("apiKey" in apiKeyResponse2)) {
934
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
935
+ process.exit(EXIT_CODES.ERROR);
936
+ }
799
937
  return {
800
938
  ...config,
801
939
  anthropic: {
@@ -810,12 +948,20 @@ async function configureProvider(provider, config) {
810
948
  message: "Google model to use:",
811
949
  initial: ENV_DEFAULTS.google.model
812
950
  });
951
+ if (!("model" in response)) {
952
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
953
+ process.exit(EXIT_CODES.ERROR);
954
+ }
813
955
  const apiKeyResponse = await prompts({
814
956
  type: "password",
815
957
  name: "apiKey",
816
958
  message: "Google API key:",
817
959
  validate: (value) => value.trim() !== "" || "API key is required"
818
960
  });
961
+ if (!("apiKey" in apiKeyResponse)) {
962
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
963
+ process.exit(EXIT_CODES.ERROR);
964
+ }
819
965
  return {
820
966
  ...config,
821
967
  google: {
@@ -826,12 +972,12 @@ async function configureProvider(provider, config) {
826
972
  }
827
973
  function showManualInstructions(config) {
828
974
  const instructions = getManualInstructions(config);
829
- console.log("\n" + chalk3.green("\u2705 Setup complete!"));
975
+ console.log("\n" + chalk6.green("\u2705 Setup complete!"));
830
976
  console.log("\n" + instructions + "\n");
831
977
  }
832
978
  async function runSetup() {
833
979
  console.log(
834
- boxen2(chalk3.bold("\u{1F44B} Welcome to Hyntx!"), {
980
+ boxen2(chalk6.bold("\u{1F44B} Welcome to Hyntx!"), {
835
981
  padding: 1,
836
982
  borderColor: "cyan"
837
983
  })
@@ -846,8 +992,8 @@ async function runSetup() {
846
992
  });
847
993
  const providers = providerResponse.providers;
848
994
  if (!providers || providers.length === 0) {
849
- console.log(chalk3.red("No providers selected. Setup cancelled."));
850
- process.exit(1);
995
+ console.log(chalk6.red("No providers selected. Setup cancelled."));
996
+ process.exit(EXIT_CODES.ERROR);
851
997
  }
852
998
  let config = {
853
999
  services: providers,
@@ -873,6 +1019,10 @@ async function runSetup() {
873
1019
  initial: 1
874
1020
  // Default to 7d
875
1021
  });
1022
+ if (!("reminder" in reminderResponse)) {
1023
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
1024
+ process.exit(EXIT_CODES.ERROR);
1025
+ }
876
1026
  const reminder = reminderResponse.reminder;
877
1027
  if (reminder && reminder !== "never") {
878
1028
  config = { ...config, reminder };
@@ -899,18 +1049,22 @@ async function runSetup() {
899
1049
  message: `Save configuration to ${configFile}?`,
900
1050
  initial: true
901
1051
  });
1052
+ if (!("saveToShell" in saveToShellResponse)) {
1053
+ console.log(chalk6.yellow("\nSetup cancelled by user."));
1054
+ process.exit(EXIT_CODES.ERROR);
1055
+ }
902
1056
  const saveToShell = saveToShellResponse.saveToShell ?? false;
903
1057
  if (saveToShell) {
904
1058
  const result = saveConfigToShell(config);
905
1059
  if (result.success) {
906
- console.log("\n" + chalk3.green("\u2705 " + result.message));
1060
+ console.log("\n" + chalk6.green("\u2705 " + result.message));
907
1061
  console.log(
908
- chalk3.dim(
1062
+ chalk6.dim(
909
1063
  " Run 'source " + result.shellFile + "' or open a new terminal to apply."
910
1064
  )
911
1065
  );
912
1066
  } else {
913
- console.log("\n" + chalk3.yellow("\u26A0\uFE0F " + result.message));
1067
+ console.log("\n" + chalk6.yellow("\u26A0\uFE0F " + result.message));
914
1068
  showManualInstructions(config);
915
1069
  }
916
1070
  } else {
@@ -1131,17 +1285,17 @@ function sanitize(text) {
1131
1285
  redacted
1132
1286
  };
1133
1287
  }
1134
- function sanitizePrompts(prompts2) {
1135
- if (prompts2.length === 0) {
1288
+ function sanitizePrompts(prompts3) {
1289
+ if (prompts3.length === 0) {
1136
1290
  return { prompts: [], totalRedacted: 0 };
1137
1291
  }
1138
1292
  logger.debug(
1139
- `Sanitizing ${String(prompts2.length)} prompts for secrets`,
1293
+ `Sanitizing ${String(prompts3.length)} prompts for secrets`,
1140
1294
  "sanitizer"
1141
1295
  );
1142
1296
  const sanitizedPrompts = [];
1143
1297
  let totalRedacted = 0;
1144
- for (const prompt of prompts2) {
1298
+ for (const prompt of prompts3) {
1145
1299
  const result = sanitize(prompt);
1146
1300
  sanitizedPrompts.push(result.text);
1147
1301
  totalRedacted += result.redacted;
@@ -1217,12 +1371,12 @@ function estimateTokens(text) {
1217
1371
  return Math.ceil(text.length / CHARS_PER_TOKEN);
1218
1372
  }
1219
1373
  function batchPrompts(options) {
1220
- const { prompts: prompts2, maxTokensPerBatch, prioritization } = options;
1221
- if (prompts2.length === 0) {
1374
+ const { prompts: prompts3, maxTokensPerBatch, prioritization } = options;
1375
+ if (prompts3.length === 0) {
1222
1376
  return [];
1223
1377
  }
1224
1378
  const effectiveLimit = maxTokensPerBatch - SYSTEM_OVERHEAD_TOKENS;
1225
- const promptsWithTokens = prompts2.map((prompt) => ({
1379
+ const promptsWithTokens = prompts3.map((prompt) => ({
1226
1380
  prompt,
1227
1381
  tokens: estimateTokens(prompt)
1228
1382
  }));
@@ -1342,15 +1496,15 @@ function mergeBatchResults(options) {
1342
1496
  };
1343
1497
  }
1344
1498
  async function analyzePrompts(options) {
1345
- const { provider, prompts: prompts2, date, context, onProgress } = options;
1499
+ const { provider, prompts: prompts3, date, context, onProgress } = options;
1346
1500
  logger.debug(
1347
- `Starting analysis of ${String(prompts2.length)} prompts for ${date}`,
1501
+ `Starting analysis of ${String(prompts3.length)} prompts for ${date}`,
1348
1502
  "analyzer"
1349
1503
  );
1350
- if (prompts2.length === 0) {
1504
+ if (prompts3.length === 0) {
1351
1505
  throw new Error("Cannot analyze empty prompts array");
1352
1506
  }
1353
- const { prompts: sanitizedPrompts, totalRedacted } = sanitizePrompts(prompts2);
1507
+ const { prompts: sanitizedPrompts, totalRedacted } = sanitizePrompts(prompts3);
1354
1508
  if (totalRedacted > 0) {
1355
1509
  logger.debug(
1356
1510
  `Sanitizer redacted ${String(totalRedacted)} secrets`,
@@ -1439,12 +1593,12 @@ function severityIcon(severity) {
1439
1593
  }
1440
1594
  function scoreColor(score, text) {
1441
1595
  if (score >= 8) {
1442
- return chalk3.green(text);
1596
+ return chalk6.green(text);
1443
1597
  }
1444
1598
  if (score >= 6) {
1445
- return chalk3.yellow(text);
1599
+ return chalk6.yellow(text);
1446
1600
  }
1447
- return chalk3.red(text);
1601
+ return chalk6.red(text);
1448
1602
  }
1449
1603
  function truncateText(text, maxLength) {
1450
1604
  if (text.length <= maxLength) {
@@ -1464,16 +1618,16 @@ function formatHeader(title) {
1464
1618
  font: "Standard",
1465
1619
  horizontalLayout: "default"
1466
1620
  });
1467
- return chalk3.cyan(ascii);
1621
+ return chalk6.cyan(ascii);
1468
1622
  } catch {
1469
- return chalk3.cyan.bold(`
1623
+ return chalk6.cyan.bold(`
1470
1624
  ${headerText}
1471
1625
  `);
1472
1626
  }
1473
1627
  }
1474
1628
  function formatStats(stats, projectCount) {
1475
1629
  const table = new Table({
1476
- head: [chalk3.bold("Metric"), chalk3.bold("Value")],
1630
+ head: [chalk6.bold("Metric"), chalk6.bold("Value")],
1477
1631
  colWidths: [30, 20]
1478
1632
  });
1479
1633
  table.push(
@@ -1489,25 +1643,25 @@ function formatStats(stats, projectCount) {
1489
1643
  function formatPattern(pattern, index) {
1490
1644
  const lines = [];
1491
1645
  lines.push(
1492
- chalk3.bold(
1646
+ chalk6.bold(
1493
1647
  `${String(index + 1)}. ${severityIcon(pattern.severity)} ${pattern.name}`
1494
1648
  )
1495
1649
  );
1496
1650
  lines.push(
1497
- chalk3.dim(
1651
+ chalk6.dim(
1498
1652
  ` Frequency: ${String(pattern.frequency)} | Severity: ${pattern.severity}`
1499
1653
  )
1500
1654
  );
1501
1655
  lines.push("");
1502
1656
  if (pattern.examples.length > 0) {
1503
- lines.push(chalk3.yellow(" Examples:"));
1657
+ lines.push(chalk6.yellow(" Examples:"));
1504
1658
  for (const example of pattern.examples) {
1505
- lines.push(chalk3.dim(` \u2022 ${example}`));
1659
+ lines.push(chalk6.dim(` \u2022 ${example}`));
1506
1660
  }
1507
1661
  lines.push("");
1508
1662
  }
1509
- lines.push(chalk3.green(" Suggestion:"));
1510
- lines.push(chalk3.dim(` ${pattern.suggestion}`));
1663
+ lines.push(chalk6.green(" Suggestion:"));
1664
+ lines.push(chalk6.dim(` ${pattern.suggestion}`));
1511
1665
  return boxen2(lines.join("\n"), {
1512
1666
  padding: 1,
1513
1667
  borderColor: pattern.severity === "high" ? "red" : "yellow",
@@ -1516,14 +1670,14 @@ function formatPattern(pattern, index) {
1516
1670
  }
1517
1671
  function formatBeforeAfter(beforeAfter) {
1518
1672
  const sections = [];
1519
- const beforeBox = boxen2(chalk3.red(beforeAfter.before), {
1673
+ const beforeBox = boxen2(chalk6.red(beforeAfter.before), {
1520
1674
  padding: 1,
1521
1675
  borderColor: "red",
1522
1676
  borderStyle: "round",
1523
1677
  title: "\u274C Before"
1524
1678
  });
1525
1679
  sections.push(beforeBox);
1526
- const afterBox = boxen2(chalk3.green(beforeAfter.after), {
1680
+ const afterBox = boxen2(chalk6.green(beforeAfter.after), {
1527
1681
  padding: 1,
1528
1682
  borderColor: "green",
1529
1683
  borderStyle: "round",
@@ -1533,7 +1687,7 @@ function formatBeforeAfter(beforeAfter) {
1533
1687
  return sections.join("\n\n");
1534
1688
  }
1535
1689
  function formatTopSuggestion(suggestion) {
1536
- return boxen2(chalk3.cyan.bold(suggestion), {
1690
+ return boxen2(chalk6.cyan.bold(suggestion), {
1537
1691
  padding: 1,
1538
1692
  borderColor: "cyan",
1539
1693
  borderStyle: "double",
@@ -1549,7 +1703,7 @@ function printReport(result, options) {
1549
1703
  output.push(formatHeader());
1550
1704
  output.push("");
1551
1705
  }
1552
- output.push(chalk3.bold("\u{1F4CA} Statistics"));
1706
+ output.push(chalk6.bold("\u{1F4CA} Statistics"));
1553
1707
  output.push("");
1554
1708
  output.push(formatStats(result.stats));
1555
1709
  output.push("");
@@ -1558,7 +1712,7 @@ function printReport(result, options) {
1558
1712
  output.push("");
1559
1713
  }
1560
1714
  if (result.patterns.length > 0) {
1561
- output.push(chalk3.bold("\u{1F50D} Detected Patterns"));
1715
+ output.push(chalk6.bold("\u{1F50D} Detected Patterns"));
1562
1716
  output.push("");
1563
1717
  for (const [index, pattern] of result.patterns.entries()) {
1564
1718
  const truncatedPattern = {
@@ -1580,15 +1734,249 @@ function printReport(result, options) {
1580
1734
  }
1581
1735
  }
1582
1736
  } else {
1583
- output.push(chalk3.green("\u2705 No issues detected!"));
1737
+ output.push(chalk6.green("\u2705 No issues detected!"));
1584
1738
  output.push("");
1585
1739
  }
1586
- output.push(chalk3.dim(`Analysis Date: ${result.date}`));
1740
+ output.push(chalk6.dim(`Analysis Date: ${result.date}`));
1587
1741
  console.log(output.join("\n"));
1588
1742
  }
1589
1743
  function formatJson(result, compact = false) {
1590
1744
  return compact ? JSON.stringify(result) : JSON.stringify(result, null, 2);
1591
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
+ }
1875
+ output.push("");
1876
+ }
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("");
1978
+ console.log(output.join("\n"));
1979
+ }
1592
1980
 
1593
1981
  // src/providers/index.ts
1594
1982
  init_logger();
@@ -1632,13 +2020,13 @@ Guidelines:
1632
2020
  - topSuggestion should be the most impactful single change
1633
2021
  - If no issues found, return empty patterns array with score 100
1634
2022
  - Be constructive and specific in suggestions`;
1635
- function buildUserPrompt(prompts2, date, context) {
1636
- if (prompts2.length === 0) {
2023
+ function buildUserPrompt(prompts3, date, context) {
2024
+ if (prompts3.length === 0) {
1637
2025
  throw new Error("Cannot build prompt from empty array");
1638
2026
  }
1639
- const promptsList = prompts2.map((prompt, index) => `${String(index + 1)}. ${prompt}`).join("\n\n");
1640
- const count = String(prompts2.length);
1641
- const plural = prompts2.length === 1 ? "" : "s";
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";
1642
2030
  let contextSection = "";
1643
2031
  if (context) {
1644
2032
  const contextParts = [];
@@ -1820,11 +2208,11 @@ var OllamaProvider = class {
1820
2208
  * @returns Promise resolving to AnalysisResult
1821
2209
  * @throws Error if analysis fails after retries or if response is invalid
1822
2210
  */
1823
- async analyze(prompts2, date, context) {
1824
- if (prompts2.length === 0) {
2211
+ async analyze(prompts3, date, context) {
2212
+ if (prompts3.length === 0) {
1825
2213
  throw new Error("Cannot analyze empty prompts array");
1826
2214
  }
1827
- const userPrompt = buildUserPrompt(prompts2, date, context);
2215
+ const userPrompt = buildUserPrompt(prompts3, date, context);
1828
2216
  let lastError;
1829
2217
  for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
1830
2218
  try {
@@ -1883,7 +2271,7 @@ var OllamaProvider = class {
1883
2271
  }
1884
2272
  };
1885
2273
  function sleep(ms) {
1886
- return new Promise((resolve) => setTimeout(resolve, ms));
2274
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1887
2275
  }
1888
2276
 
1889
2277
  // src/providers/anthropic.ts
@@ -1898,7 +2286,7 @@ function createRateLimiter(options) {
1898
2286
  const timeSinceLastRequest = now - lastRequestTime;
1899
2287
  if (lastRequestTime > 0 && timeSinceLastRequest < minIntervalMs) {
1900
2288
  const waitTime = minIntervalMs - timeSinceLastRequest;
1901
- await new Promise((resolve) => setTimeout(resolve, waitTime));
2289
+ await new Promise((resolve2) => setTimeout(resolve2, waitTime));
1902
2290
  }
1903
2291
  lastRequestTime = Date.now();
1904
2292
  return fn();
@@ -1943,7 +2331,7 @@ function isTransientError(error) {
1943
2331
  return false;
1944
2332
  }
1945
2333
  function sleep2(ms) {
1946
- return new Promise((resolve) => setTimeout(resolve, ms));
2334
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1947
2335
  }
1948
2336
  async function withRetry(fn, options = {}) {
1949
2337
  const opts = { ...DEFAULT_OPTIONS, ...options };
@@ -2049,11 +2437,11 @@ var AnthropicProvider = class {
2049
2437
  * @returns Promise resolving to AnalysisResult
2050
2438
  * @throws Error if analysis fails after retries or if response is invalid
2051
2439
  */
2052
- async analyze(prompts2, date, context) {
2053
- if (prompts2.length === 0) {
2440
+ async analyze(prompts3, date, context) {
2441
+ if (prompts3.length === 0) {
2054
2442
  throw new Error("Cannot analyze empty prompts array");
2055
2443
  }
2056
- const userPrompt = buildUserPrompt(prompts2, date, context);
2444
+ const userPrompt = buildUserPrompt(prompts3, date, context);
2057
2445
  return this.rateLimiter.throttle(
2058
2446
  () => withRetry(
2059
2447
  async () => {
@@ -2192,11 +2580,11 @@ var GoogleProvider = class {
2192
2580
  * @returns Promise resolving to AnalysisResult
2193
2581
  * @throws Error if analysis fails after retries or if response is invalid
2194
2582
  */
2195
- async analyze(prompts2, date, context) {
2196
- if (prompts2.length === 0) {
2583
+ async analyze(prompts3, date, context) {
2584
+ if (prompts3.length === 0) {
2197
2585
  throw new Error("Cannot analyze empty prompts array");
2198
2586
  }
2199
- const userPrompt = buildUserPrompt(prompts2, date, context);
2587
+ const userPrompt = buildUserPrompt(prompts3, date, context);
2200
2588
  return this.rateLimiter.throttle(
2201
2589
  () => withRetry(
2202
2590
  async () => {
@@ -2601,28 +2989,28 @@ async function validateAllProviders(config) {
2601
2989
  function formatStatusIcon(status) {
2602
2990
  switch (status) {
2603
2991
  case "pass":
2604
- return chalk3.green("\u2705");
2992
+ return chalk6.green("\u2705");
2605
2993
  case "fail":
2606
- return chalk3.red("\u274C");
2994
+ return chalk6.red("\u274C");
2607
2995
  case "warn":
2608
- return chalk3.yellow("\u26A0\uFE0F");
2996
+ return chalk6.yellow("\u26A0\uFE0F");
2609
2997
  }
2610
2998
  }
2611
2999
  function printHealthCheckResult(result, config) {
2612
3000
  console.log("");
2613
- console.log(chalk3.bold("\u{1F50D} Configuration Health Check"));
2614
- console.log(chalk3.dim("\u2550".repeat(43)));
3001
+ console.log(chalk6.bold("\u{1F50D} Configuration Health Check"));
3002
+ console.log(chalk6.dim("\u2550".repeat(43)));
2615
3003
  console.log("");
2616
- console.log(chalk3.bold("Configuration:"));
3004
+ console.log(chalk6.bold("Configuration:"));
2617
3005
  if (config.services.length === 0) {
2618
- console.log(chalk3.dim(" No providers configured"));
3006
+ console.log(chalk6.dim(" No providers configured"));
2619
3007
  } else {
2620
3008
  console.log(` Services: ${config.services.join(", ")}`);
2621
3009
  }
2622
3010
  console.log(` Reminder: ${config.reminder}`);
2623
3011
  console.log("");
2624
3012
  for (const provider of result.providers) {
2625
- console.log(chalk3.bold(`${provider.displayName} Provider:`));
3013
+ console.log(chalk6.bold(`${provider.displayName} Provider:`));
2626
3014
  for (const check of provider.checks) {
2627
3015
  const icon = formatStatusIcon(check.status);
2628
3016
  const message = check.message ? `: ${check.message}` : "";
@@ -2630,36 +3018,280 @@ function printHealthCheckResult(result, config) {
2630
3018
  }
2631
3019
  console.log("");
2632
3020
  }
2633
- console.log(chalk3.bold("Summary:"));
3021
+ console.log(chalk6.bold("Summary:"));
2634
3022
  if (config.services.length === 0) {
2635
- console.log(chalk3.yellow(" \u26A0\uFE0F No providers configured"));
2636
- console.log(chalk3.dim(" Run hyntx setup to configure providers"));
3023
+ console.log(chalk6.yellow(" \u26A0\uFE0F No providers configured"));
3024
+ console.log(chalk6.dim(" Run hyntx setup to configure providers"));
2637
3025
  } else if (result.allValid) {
2638
3026
  console.log(
2639
- chalk3.green(
3027
+ chalk6.green(
2640
3028
  ` \u2705 All ${String(result.summary.totalConfigured)} provider(s) ready to use`
2641
3029
  )
2642
3030
  );
2643
3031
  } else {
2644
3032
  if (result.summary.unavailableCount > 0) {
2645
3033
  console.log(
2646
- chalk3.yellow(
3034
+ chalk6.yellow(
2647
3035
  ` \u26A0\uFE0F ${String(result.summary.unavailableCount)} provider(s) configured but unavailable`
2648
3036
  )
2649
3037
  );
2650
3038
  }
2651
3039
  if (result.summary.availableCount > 0) {
2652
3040
  console.log(
2653
- chalk3.green(
3041
+ chalk6.green(
2654
3042
  ` \u2705 ${String(result.summary.availableCount)} provider(s) ready to use`
2655
3043
  )
2656
3044
  );
2657
3045
  } else {
2658
- console.log(chalk3.red(" \u274C No providers available"));
3046
+ console.log(chalk6.red(" \u274C No providers available"));
2659
3047
  }
2660
3048
  }
2661
3049
  console.log("");
2662
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
+ }
2663
3295
 
2664
3296
  // src/index.ts
2665
3297
  var currentDir = dirname(fileURLToPath(import.meta.url));
@@ -2675,6 +3307,27 @@ function parseArguments() {
2675
3307
  type: "string",
2676
3308
  default: "today"
2677
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
+ },
2678
3331
  format: {
2679
3332
  type: "string",
2680
3333
  default: "terminal"
@@ -2692,6 +3345,29 @@ function parseArguments() {
2692
3345
  type: "boolean",
2693
3346
  default: false
2694
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
+ },
2695
3371
  help: {
2696
3372
  type: "boolean",
2697
3373
  short: "h",
@@ -2707,43 +3383,263 @@ function parseArguments() {
2707
3383
  });
2708
3384
  return {
2709
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,
2710
3392
  help: values.help || false,
2711
3393
  version: values.version || false,
2712
3394
  verbose: values.verbose || false,
2713
3395
  checkConfig: values["check-config"] || false,
2714
3396
  format: values.format || "terminal",
2715
- compact: values.compact || false
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
2716
3404
  };
2717
3405
  } catch (error) {
2718
3406
  const errorMessage = error instanceof Error ? error.message : String(error);
2719
3407
  throw new Error(`Invalid arguments: ${errorMessage}`);
2720
3408
  }
2721
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
+ }
2722
3562
  function showHelp() {
2723
3563
  const helpText = `
2724
- ${chalk3.bold("Usage:")} hyntx [options]
3564
+ ${chalk6.bold("Usage:")} hyntx [options]
2725
3565
 
2726
- ${chalk3.bold("Options:")}
3566
+ ${chalk6.bold("Options:")}
3567
+ ${chalk6.bold("Date Filtering:")}
2727
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:")}
2728
3576
  --format <type> Output format: terminal, json [default: terminal]
2729
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:")}
2730
3592
  -v, --verbose Enable debug output to stderr
2731
3593
  --check-config Validate configuration and test provider connectivity
3594
+ --check-reminder Show reminder status and exit
3595
+
3596
+ ${chalk6.bold("Information:")}
2732
3597
  -h, --help Show help
2733
3598
  --version Show version
2734
3599
 
2735
- ${chalk3.bold("Exit codes:")}
3600
+ ${chalk6.bold("Exit codes:")}
2736
3601
  ${String(EXIT_CODES.SUCCESS)} - Success
2737
3602
  ${String(EXIT_CODES.ERROR)} - Error
2738
3603
  ${String(EXIT_CODES.NO_DATA)} - No data found
2739
3604
  ${String(EXIT_CODES.PROVIDER_UNAVAILABLE)} - Provider unavailable
2740
3605
 
2741
- ${chalk3.bold("Examples:")}
2742
- hyntx # Analyze today's prompts (terminal format)
2743
- hyntx --date yesterday # Analyze yesterday
2744
- hyntx --date 2025-01-20 # Specific date
2745
- hyntx --format json # Output as formatted JSON
2746
- hyntx --format json --compact # Output as compact JSON
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
2747
3643
  `;
2748
3644
  console.log(helpText);
2749
3645
  process.exit(EXIT_CODES.SUCCESS);
@@ -2774,7 +3670,7 @@ async function checkAndRunSetup(isJsonMode) {
2774
3670
  await runSetup();
2775
3671
  }
2776
3672
  }
2777
- async function readLogsWithSpinner(date, isJsonMode) {
3673
+ async function readLogsWithSpinner(args, isJsonMode) {
2778
3674
  if (!claudeProjectsExist()) {
2779
3675
  if (isJsonMode) {
2780
3676
  const errorResponse = {
@@ -2785,31 +3681,48 @@ async function readLogsWithSpinner(date, isJsonMode) {
2785
3681
  } else {
2786
3682
  logger.error("Claude Code logs directory not found");
2787
3683
  process.stderr.write(
2788
- chalk3.dim(`Expected location: ${CLAUDE_PROJECTS_DIR}
3684
+ chalk6.dim(`Expected location: ${CLAUDE_PROJECTS_DIR}
2789
3685
  `)
2790
3686
  );
2791
3687
  process.stderr.write(
2792
- chalk3.dim(
3688
+ chalk6.dim(
2793
3689
  "\nMake sure Claude Code is installed and has been used at least once.\n"
2794
3690
  )
2795
3691
  );
2796
3692
  }
2797
3693
  process.exit(EXIT_CODES.NO_DATA);
2798
3694
  }
2799
- const spinner = isJsonMode ? null : ora(`Reading Claude Code logs for ${date}...`).start();
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();
2800
3706
  try {
2801
- const result = await readLogs({ date });
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);
2802
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}`;
2803
3716
  if (isJsonMode) {
2804
3717
  const errorResponse = {
2805
- error: `No prompts found for ${date}`,
3718
+ error: noDataMessage,
2806
3719
  code: "NO_DATA"
2807
3720
  };
2808
3721
  console.log(JSON.stringify(errorResponse));
2809
3722
  } else {
2810
- spinner?.fail(chalk3.yellow(`No prompts found for ${date}`));
3723
+ spinner?.fail(chalk6.yellow(noDataMessage));
2811
3724
  process.stderr.write(
2812
- chalk3.dim(
3725
+ chalk6.dim(
2813
3726
  "\nTry a different date or check that Claude Code has been used recently.\n"
2814
3727
  )
2815
3728
  );
@@ -2817,13 +3730,10 @@ async function readLogsWithSpinner(date, isJsonMode) {
2817
3730
  process.exit(EXIT_CODES.NO_DATA);
2818
3731
  }
2819
3732
  if (!isJsonMode) {
2820
- spinner?.succeed(
2821
- chalk3.green(
2822
- `Found ${String(result.prompts.length)} prompts for ${date}`
2823
- )
2824
- );
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));
2825
3735
  }
2826
- return result.prompts.map((p) => p.content);
3736
+ return result;
2827
3737
  } catch (error) {
2828
3738
  const errorMessage = error instanceof Error ? error.message : String(error);
2829
3739
  if (isJsonMode) {
@@ -2833,7 +3743,7 @@ async function readLogsWithSpinner(date, isJsonMode) {
2833
3743
  };
2834
3744
  console.log(JSON.stringify(errorResponse));
2835
3745
  } else {
2836
- spinner?.fail(chalk3.red(`Failed to read logs: ${errorMessage}`));
3746
+ spinner?.fail(chalk6.red(`Failed to read logs: ${errorMessage}`));
2837
3747
  }
2838
3748
  process.exit(EXIT_CODES.ERROR);
2839
3749
  }
@@ -2850,7 +3760,7 @@ async function connectProviderWithSpinner(isJsonMode) {
2850
3760
  } else {
2851
3761
  logger.error("No providers configured");
2852
3762
  process.stderr.write(
2853
- chalk3.dim("\nRun setup to configure at least one provider.\n")
3763
+ chalk6.dim("\nRun setup to configure at least one provider.\n")
2854
3764
  );
2855
3765
  }
2856
3766
  process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
@@ -2859,7 +3769,7 @@ async function connectProviderWithSpinner(isJsonMode) {
2859
3769
  try {
2860
3770
  const provider = await getAvailableProvider(config, (from, to) => {
2861
3771
  if (!isJsonMode && spinner) {
2862
- spinner.text = chalk3.yellow(
3772
+ spinner.text = chalk6.yellow(
2863
3773
  `Primary provider ${from} unavailable, falling back to ${to}...`
2864
3774
  );
2865
3775
  }
@@ -2869,7 +3779,7 @@ async function connectProviderWithSpinner(isJsonMode) {
2869
3779
  );
2870
3780
  });
2871
3781
  if (!isJsonMode) {
2872
- spinner?.succeed(chalk3.green(`Connected to ${provider.name}`));
3782
+ spinner?.succeed(chalk6.green(`Connected to ${provider.name}`));
2873
3783
  }
2874
3784
  return provider;
2875
3785
  } catch (error) {
@@ -2881,12 +3791,12 @@ async function connectProviderWithSpinner(isJsonMode) {
2881
3791
  };
2882
3792
  console.log(JSON.stringify(errorResponse));
2883
3793
  } else {
2884
- spinner?.fail(chalk3.red("No providers available"));
2885
- process.stderr.write(chalk3.dim(`
3794
+ spinner?.fail(chalk6.red("No providers available"));
3795
+ process.stderr.write(chalk6.dim(`
2886
3796
  ${errorMessage}
2887
3797
  `));
2888
3798
  process.stderr.write(
2889
- chalk3.dim(
3799
+ chalk6.dim(
2890
3800
  "\nCheck your provider configuration and ensure at least one provider is running.\n"
2891
3801
  )
2892
3802
  );
@@ -2894,22 +3804,22 @@ ${errorMessage}
2894
3804
  process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
2895
3805
  }
2896
3806
  }
2897
- async function analyzeWithProgress(provider, prompts2, date, context, isJsonMode) {
2898
- const spinner = isJsonMode ? null : ora(`Analyzing ${String(prompts2.length)} prompts...`).start();
3807
+ async function analyzeWithProgress(provider, prompts3, date, context, isJsonMode) {
3808
+ const spinner = isJsonMode ? null : ora(`Analyzing ${String(prompts3.length)} prompts...`).start();
2899
3809
  try {
2900
3810
  const result = await analyzePrompts({
2901
3811
  provider,
2902
- prompts: prompts2,
3812
+ prompts: prompts3,
2903
3813
  date,
2904
3814
  context,
2905
3815
  onProgress: (current, total) => {
2906
3816
  if (!isJsonMode && spinner && total > 1) {
2907
- spinner.text = `Analyzing ${String(prompts2.length)} prompts (batch ${String(current + 1)}/${String(total)})...`;
3817
+ spinner.text = `Analyzing ${String(prompts3.length)} prompts (batch ${String(current + 1)}/${String(total)})...`;
2908
3818
  }
2909
3819
  }
2910
3820
  });
2911
3821
  if (!isJsonMode) {
2912
- spinner?.succeed(chalk3.green("Analysis complete"));
3822
+ spinner?.succeed(chalk6.green("Analysis complete"));
2913
3823
  }
2914
3824
  return result;
2915
3825
  } catch (error) {
@@ -2921,13 +3831,13 @@ async function analyzeWithProgress(provider, prompts2, date, context, isJsonMode
2921
3831
  };
2922
3832
  console.log(JSON.stringify(errorResponse));
2923
3833
  } else {
2924
- spinner?.fail(chalk3.red(`Analysis failed: ${errorMessage}`));
3834
+ spinner?.fail(chalk6.red(`Analysis failed: ${errorMessage}`));
2925
3835
  }
2926
3836
  process.exit(EXIT_CODES.ERROR);
2927
3837
  }
2928
3838
  }
2929
- function displayResults(result, format, compact) {
2930
- if (format === "json") {
3839
+ function displayResults(result, format2, compact) {
3840
+ if (format2 === "json") {
2931
3841
  console.log(formatJson(result, compact));
2932
3842
  } else {
2933
3843
  console.log("");
@@ -2950,6 +3860,7 @@ async function main() {
2950
3860
  let isJsonMode = false;
2951
3861
  try {
2952
3862
  const args = parseArguments();
3863
+ validateArguments(args);
2953
3864
  isJsonMode = args.format === "json";
2954
3865
  if (args.verbose) {
2955
3866
  logger.setVerbose(true);
@@ -2964,20 +3875,181 @@ async function main() {
2964
3875
  if (args.checkConfig) {
2965
3876
  await runConfigCheck();
2966
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
+ }
2967
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
+ }
2968
3904
  const envConfig = getEnvConfig();
2969
3905
  const projectConfig = loadProjectConfigForCwd(process.cwd());
2970
3906
  const config = mergeConfigs(envConfig, projectConfig);
2971
- const prompts2 = await readLogsWithSpinner(args.date, isJsonMode);
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) : [];
2972
3914
  const provider = await connectProviderWithSpinner(isJsonMode);
2973
- const result = await analyzeWithProgress(
2974
- provider,
2975
- prompts2,
2976
- args.date,
2977
- config.context,
2978
- isJsonMode
2979
- );
2980
- displayResults(result, args.format ?? "terminal", args.compact ?? false);
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();
2981
4053
  if (!isJsonMode) {
2982
4054
  logger.reportWarnings();
2983
4055
  }
@@ -2992,11 +4064,15 @@ async function main() {
2992
4064
  );
2993
4065
  }
2994
4066
  }
2995
- 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
+ })();
2996
4074
  if (isMainModule) {
2997
4075
  void main();
2998
4076
  }
2999
4077
 
3000
- export { analyzeWithProgress, checkAndRunSetup, connectProviderWithSpinner, displayResults, handleError, main, parseArguments, readLogsWithSpinner, runConfigCheck, showHelp, showVersion };
3001
- //# sourceMappingURL=index.js.map
3002
- //# sourceMappingURL=index.js.map
4078
+ export { analyzeWithProgress, checkAndRunSetup, connectProviderWithSpinner, displayDryRunSummary, displayResults, getOutputFilePath, handleError, main, parseArguments, readLogsWithSpinner, runConfigCheck, showHelp, showReminderStatus, showVersion, validateArguments, writeMultiDayJsonOutput, writeOutputFile };