hyntx 3.0.1 → 4.0.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.
@@ -1,1083 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- /**
4
- * Schema variants and issue taxonomy for AI analysis providers.
5
- *
6
- * This module provides:
7
- * - Issue taxonomy with predefined metadata
8
- * - System prompts for different schema types
9
- * - Type definitions for schema variants
10
- * - Rules configuration utilities
11
- */
12
-
13
- /**
14
- * Metadata for a predefined issue type.
15
- * Used by the aggregator to convert minimal issue IDs to full patterns.
16
- */
17
- type IssueMetadata = {
18
- readonly name: string;
19
- readonly severity: PatternSeverity;
20
- readonly suggestion: string;
21
- readonly exampleBefore?: string;
22
- readonly exampleAfter?: string;
23
- };
24
- /**
25
- * Taxonomy mapping issue IDs to their metadata.
26
- */
27
- type IssueTaxonomy = Record<string, IssueMetadata>;
28
- /**
29
- * Schema type identifier.
30
- * - minimal: Lightweight schema for small models (issue IDs + score)
31
- * - simple: Medium schema with issue objects
32
- * - full: Complete schema with patterns and stats
33
- * - individual: Hybrid approach - batch processing with individual result schema
34
- */
35
- type SchemaType = 'minimal' | 'simple' | 'full' | 'individual';
36
-
37
- /**
38
- * Aggregator for converting minimal analysis results to full AnalysisResult.
39
- *
40
- * This module provides utilities to:
41
- * - Convert minimal responses (issue IDs + score) to full AnalysisResult
42
- * - Aggregate multiple minimal results into a single result
43
- * - Look up issue metadata from the taxonomy with graceful fallback
44
- */
45
-
46
- /**
47
- * Minimal result from small models.
48
- * Contains only issue IDs and a quality score.
49
- */
50
- type MinimalResult = {
51
- readonly issues: readonly string[];
52
- readonly score: number;
53
- };
54
-
55
- /**
56
- * Hyntx - TypeScript Type Definitions
57
- *
58
- * This module contains all shared type definitions for the Hyntx system.
59
- * All types are designed to be composable and type-safe.
60
- */
61
-
62
- /**
63
- * Schema version for Claude Code JSONL logs.
64
- * Used for graceful degradation when log format changes.
65
- */
66
- type SchemaVersion = {
67
- readonly major: number;
68
- readonly minor: number;
69
- readonly detected: string;
70
- };
71
- /**
72
- * Message structure in Claude Code JSONL logs.
73
- * Represents a single entry in the conversation log.
74
- */
75
- type ClaudeMessage = {
76
- readonly type: 'user' | 'assistant' | 'system';
77
- readonly message: {
78
- readonly role: 'user' | 'assistant' | 'system';
79
- readonly content: string;
80
- };
81
- readonly timestamp: string;
82
- readonly sessionId: string;
83
- readonly cwd: string;
84
- };
85
- /**
86
- * Log entry type alias for JSONL files.
87
- * Used in test utilities and log parsing.
88
- */
89
- type LogEntry = ClaudeMessage;
90
- /**
91
- * Data extracted from Claude Code messages.
92
- * Contains the sanitized prompt and metadata.
93
- */
94
- type ExtractedPrompt = {
95
- readonly content: string;
96
- readonly timestamp: string;
97
- readonly sessionId: string;
98
- readonly project: string;
99
- readonly date: string;
100
- };
101
- /**
102
- * Result of reading logs from the filesystem.
103
- */
104
- type LogReadResult = {
105
- readonly prompts: readonly ExtractedPrompt[];
106
- readonly warnings: readonly string[];
107
- };
108
- /**
109
- * Grouping of prompts by day for analysis.
110
- */
111
- type DayGroup = {
112
- readonly date: string;
113
- readonly prompts: readonly ExtractedPrompt[];
114
- readonly projects: readonly string[];
115
- };
116
- /**
117
- * Before/after rewrite example for a pattern.
118
- * Shows concrete improvement for a detected issue.
119
- */
120
- type BeforeAfter = {
121
- readonly before: string;
122
- readonly after: string;
123
- };
124
- /**
125
- * Severity levels for detected patterns.
126
- */
127
- type PatternSeverity = 'low' | 'medium' | 'high';
128
- /**
129
- * Detected improvement pattern from analysis.
130
- * Each pattern includes concrete examples and actionable suggestions.
131
- */
132
- type AnalysisPattern = {
133
- readonly id: string;
134
- readonly name: string;
135
- readonly frequency: number;
136
- readonly severity: PatternSeverity;
137
- readonly examples: readonly string[];
138
- readonly suggestion: string;
139
- readonly beforeAfter: BeforeAfter;
140
- };
141
- /**
142
- * Statistics from the analysis.
143
- */
144
- type AnalysisStats = {
145
- readonly totalPrompts: number;
146
- readonly promptsWithIssues: number;
147
- readonly overallScore: number;
148
- };
149
- /**
150
- * Complete analysis result from a provider.
151
- * Contains patterns, statistics, and top suggestion.
152
- */
153
- type AnalysisResult = {
154
- readonly date: string;
155
- readonly patterns: readonly AnalysisPattern[];
156
- readonly stats: AnalysisStats;
157
- readonly topSuggestion: string;
158
- };
159
- /**
160
- * Prompt analysis without the date field.
161
- * Used for raw provider responses before date context is added.
162
- */
163
- type PromptAnalysis = Omit<AnalysisResult, 'date'>;
164
- /**
165
- * Supported AI provider types.
166
- */
167
- type ProviderType = 'ollama' | 'anthropic' | 'google';
168
- /**
169
- * Batch strategy type identifier.
170
- */
171
- type BatchStrategyType = 'micro' | 'small' | 'standard';
172
- /**
173
- * Batch strategy configuration for different model sizes.
174
- */
175
- type BatchStrategy = {
176
- readonly maxTokensPerBatch: number;
177
- readonly maxPromptsPerBatch: number;
178
- readonly description: string;
179
- };
180
- /**
181
- * Available batch strategies by model size.
182
- */
183
- declare const BATCH_STRATEGIES: Record<BatchStrategyType, BatchStrategy>;
184
- /**
185
- * Context limits for each provider.
186
- * Used for intelligent batching of prompts.
187
- */
188
- type ProviderLimits = {
189
- readonly maxTokensPerBatch: number;
190
- readonly maxPromptsPerBatch?: number;
191
- readonly prioritization: 'longest-first' | 'chronological';
192
- };
193
- /**
194
- * Provider limits by type.
195
- */
196
- declare const PROVIDER_LIMITS: Record<ProviderType, ProviderLimits>;
197
- /**
198
- * Configuration for a single analysis rule.
199
- * Allows enabling/disabling rules and overriding their severity.
200
- */
201
- type RuleConfig = {
202
- readonly enabled?: boolean;
203
- readonly severity?: PatternSeverity;
204
- };
205
- /**
206
- * Configuration for all analysis rules.
207
- * Maps rule IDs to their configuration.
208
- */
209
- type RulesConfig = Record<string, RuleConfig>;
210
- /**
211
- * Project-specific context information.
212
- * Loaded from .hyntxrc.json files to provide additional context during analysis.
213
- */
214
- type ProjectContext = {
215
- readonly role?: string;
216
- readonly techStack?: readonly string[];
217
- readonly domain?: string;
218
- readonly guidelines?: readonly string[];
219
- readonly projectType?: string;
220
- };
221
- /**
222
- * Interface for AI analysis providers.
223
- * All providers must implement this interface.
224
- */
225
- type AnalysisProvider = {
226
- readonly name: string;
227
- isAvailable(): Promise<boolean>;
228
- analyze(prompts: readonly string[], date: string, context?: ProjectContext): Promise<AnalysisResult>;
229
- getBatchLimits?(): ProviderLimits;
230
- };
231
- /**
232
- * Ollama provider configuration.
233
- */
234
- type OllamaConfig = {
235
- readonly model: string;
236
- readonly host: string;
237
- readonly schemaOverride?: 'batch' | 'individual';
238
- };
239
- /**
240
- * Anthropic provider configuration.
241
- */
242
- type AnthropicConfig = {
243
- readonly model: string;
244
- readonly apiKey: string;
245
- };
246
- /**
247
- * Google provider configuration.
248
- */
249
- type GoogleConfig = {
250
- readonly model: string;
251
- readonly apiKey: string;
252
- };
253
- /**
254
- * Complete configuration from environment variables.
255
- */
256
- type EnvConfig = {
257
- readonly services: readonly ProviderType[];
258
- readonly reminder: string;
259
- readonly ollama: OllamaConfig;
260
- readonly anthropic: AnthropicConfig;
261
- readonly google: GoogleConfig;
262
- };
263
- /**
264
- * Default values for environment configuration.
265
- */
266
- declare const ENV_DEFAULTS: {
267
- readonly reminder: "7d";
268
- readonly ollama: {
269
- readonly model: "gemma3:4b";
270
- readonly host: "http://localhost:11434";
271
- };
272
- readonly anthropic: {
273
- readonly model: "claude-3-5-haiku-latest";
274
- };
275
- readonly google: {
276
- readonly model: "gemini-2.0-flash-exp";
277
- };
278
- };
279
- /**
280
- * Result of shell config file update operation.
281
- */
282
- type ShellConfigResult = {
283
- readonly success: boolean;
284
- readonly shellFile: string;
285
- readonly message: string;
286
- readonly action: 'created' | 'updated' | 'skipped' | 'failed';
287
- };
288
- /**
289
- * Supported shell types for auto-configuration.
290
- */
291
- type ShellType = 'zsh' | 'bash' | 'fish' | 'unknown';
292
- /**
293
- * Exit codes for the CLI.
294
- */
295
- declare const EXIT_CODES: {
296
- readonly SUCCESS: 0;
297
- readonly ERROR: 1;
298
- readonly NO_DATA: 2;
299
- readonly PROVIDER_UNAVAILABLE: 3;
300
- };
301
- type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];
302
- /**
303
- * Options parsed from CLI arguments.
304
- */
305
- type CliOptions = {
306
- readonly date: string;
307
- readonly from?: string;
308
- readonly to?: string;
309
- readonly project?: string;
310
- readonly output?: string;
311
- readonly verbose: boolean;
312
- readonly dryRun: boolean;
313
- readonly checkReminder: boolean;
314
- readonly help: boolean;
315
- readonly version: boolean;
316
- };
317
- /**
318
- * Output format for reports.
319
- */
320
- type OutputFormat = 'terminal' | 'markdown' | 'json';
321
- /**
322
- * JSON error response structure.
323
- */
324
- type JsonErrorResponse = {
325
- readonly error: string;
326
- readonly code: string;
327
- };
328
- /**
329
- * Metadata about the analysis execution.
330
- */
331
- type HistoryMetadata = {
332
- readonly provider: string;
333
- readonly promptCount: number;
334
- readonly projects: readonly string[];
335
- };
336
- /**
337
- * Complete history entry stored in history files.
338
- */
339
- type HistoryEntry = {
340
- readonly result: AnalysisResult;
341
- readonly metadata: HistoryMetadata;
342
- };
343
- /**
344
- * Options for listing history entries.
345
- */
346
- type ListHistoryOptions = {
347
- readonly provider?: string;
348
- readonly project?: string;
349
- readonly minScore?: number;
350
- readonly maxScore?: number;
351
- };
352
- /**
353
- * Change detected in a pattern between two analyses.
354
- */
355
- type PatternChange = {
356
- readonly id: string;
357
- readonly name: string;
358
- readonly status: 'new' | 'resolved' | 'changed';
359
- readonly frequencyBefore?: number;
360
- readonly frequencyAfter?: number;
361
- readonly severityBefore?: PatternSeverity;
362
- readonly severityAfter?: PatternSeverity;
363
- };
364
- /**
365
- * All detected changes between two analyses.
366
- */
367
- type ComparisonChanges = {
368
- readonly scoreDelta: number;
369
- readonly newPatterns: readonly AnalysisPattern[];
370
- readonly resolvedPatterns: readonly AnalysisPattern[];
371
- readonly changedPatterns: readonly PatternChange[];
372
- };
373
- /**
374
- * Result of comparing two analysis results.
375
- */
376
- type ComparisonResult = {
377
- readonly before: AnalysisResult;
378
- readonly after: AnalysisResult;
379
- readonly changes: ComparisonChanges;
380
- };
381
- /**
382
- * Event emitted when a new prompt is detected in the logs.
383
- * Contains the extracted prompt and the file path where it was found.
384
- */
385
- type PromptEvent = {
386
- readonly prompt: ExtractedPrompt;
387
- readonly filePath: string;
388
- };
389
- /**
390
- * Options for configuring the log watcher.
391
- */
392
- type WatcherOptions = {
393
- readonly debounceMs?: number;
394
- readonly projectFilter?: string;
395
- readonly signal?: AbortSignal;
396
- readonly baseDir?: string;
397
- };
398
- /**
399
- * Tracks the current position in a file for incremental reading.
400
- * Used to only read new content when files are modified.
401
- */
402
- type FilePosition = {
403
- readonly path: string;
404
- readonly size: number;
405
- readonly lastModified: number;
406
- };
407
- /**
408
- * Interface for the log watcher.
409
- * Watches Claude Code JSONL files for new prompts in real-time.
410
- */
411
- type LogWatcher = {
412
- start(): Promise<void>;
413
- stop(): Promise<void>;
414
- on(event: 'prompt', callback: (event: PromptEvent) => void): void;
415
- on(event: 'error', callback: (error: Error) => void): void;
416
- on(event: 'ready', callback: () => void): void;
417
- };
418
- /**
419
- * Metadata stored with cached analysis results.
420
- * Used for cache validation and invalidation.
421
- */
422
- type CacheMetadata = {
423
- readonly cachedAt: number;
424
- readonly promptCount: number;
425
- readonly model: string;
426
- readonly systemPromptHash: string;
427
- };
428
- /**
429
- * Complete cached batch result including metadata.
430
- * Stored as JSON files in the cache directory.
431
- */
432
- type CachedBatchResult = {
433
- readonly result: AnalysisResult;
434
- readonly metadata: CacheMetadata;
435
- };
436
- /**
437
- * Options for cache operations.
438
- */
439
- type CacheOptions = {
440
- readonly ttlMs: number;
441
- };
442
- /**
443
- * Default values for cache configuration.
444
- */
445
- declare const CACHE_DEFAULTS: {
446
- readonly ttlMs: number;
447
- };
448
-
449
- /**
450
- * Prompt Analyzer for Hyntx
451
- *
452
- * This module provides core analysis functionality for batching prompts,
453
- * merging results, and orchestrating the analysis workflow.
454
- */
455
-
456
- /**
457
- * Options for analyzing prompts.
458
- */
459
- type AnalyzePromptsOptions = {
460
- readonly provider: AnalysisProvider;
461
- readonly prompts: readonly string[];
462
- readonly date: string;
463
- readonly context?: ProjectContext;
464
- readonly rules?: RulesConfig;
465
- readonly onProgress?: (current: number, total: number) => void;
466
- readonly noCache?: boolean;
467
- /**
468
- * Pre-cached results from incremental results storage.
469
- * When provided, these will be merged with newly analyzed results
470
- * using mergeBatchResults(). This enables incremental analysis
471
- * where only new prompts are analyzed.
472
- */
473
- readonly cachedResults?: ReadonlyMap<string, AnalysisResult>;
474
- };
475
- /**
476
- * Analyzes prompts using the provided AI provider.
477
- *
478
- * Orchestrates the full analysis workflow:
479
- * 1. Sanitizes prompts to remove secrets
480
- * 2. Batches prompts based on provider limits
481
- * 3. Checks cache for existing results (unless noCache is true)
482
- * 4. Processes batches sequentially with progress updates
483
- * 5. Stores results in cache for future use
484
- * 6. Merges batch results with any provided cached results
485
- * 7. Applies rules configuration to filter/modify patterns
486
- *
487
- * For incremental analysis, use the `cachedResults` option to provide
488
- * pre-loaded results from the incremental results storage. This allows
489
- * the analyzer to only process new prompts and merge the results.
490
- *
491
- * @param options - Analysis options
492
- * @returns Analysis result
493
- *
494
- * @example
495
- * ```typescript
496
- * // Basic usage
497
- * const result = await analyzePrompts({
498
- * provider: ollamaProvider,
499
- * prompts: ['prompt1', 'prompt2', 'prompt3'],
500
- * date: '2025-01-15',
501
- * context: { role: 'developer', techStack: ['TypeScript'] },
502
- * onProgress: (current, total) => console.log(`${current}/${total}`),
503
- * noCache: false
504
- * });
505
- *
506
- * // With incremental cached results
507
- * const { cached, toAnalyze } = await getPromptsWithCache(prompts, model, schema);
508
- * const result = await analyzePrompts({
509
- * provider,
510
- * prompts: toAnalyze.map(p => p.content),
511
- * date: '2025-01-15',
512
- * cachedResults: cached, // Pre-loaded results from incremental storage
513
- * });
514
- * ```
515
- */
516
- declare function analyzePrompts(options: AnalyzePromptsOptions): Promise<AnalysisResult>;
517
-
518
- /**
519
- * Basic JSONL Log Reader for Claude Code logs.
520
- *
521
- * This module provides functionality to read and parse Claude Code JSONL log files.
522
- * It extracts user prompts with metadata for analysis.
523
- */
524
-
525
- /**
526
- * Options for filtering logs.
527
- */
528
- type ReadLogsOptions = {
529
- readonly date?: string;
530
- readonly from?: string;
531
- readonly to?: string;
532
- readonly project?: string;
533
- };
534
- /**
535
- * Checks if the Claude projects directory exists.
536
- *
537
- * @returns true if ~/.claude/projects/ exists
538
- *
539
- * @example
540
- * ```typescript
541
- * if (!claudeProjectsExist()) {
542
- * console.error('Claude Code logs not found');
543
- * }
544
- * ```
545
- */
546
- declare function claudeProjectsExist(): boolean;
547
- /**
548
- * Extracts the project name from a JSONL file path.
549
- * The project hash is the directory name containing the JSONL file.
550
- *
551
- * @param filePath - Full path to the JSONL file
552
- * @returns The project hash/name
553
- */
554
- declare function extractProjectName(filePath: string): string;
555
- /**
556
- * Parses date strings into Date objects.
557
- * Supports 'today', 'yesterday', and ISO date format (YYYY-MM-DD).
558
- *
559
- * @param dateStr - Date string to parse
560
- * @returns Parsed Date object
561
- * @throws Error if date string is invalid
562
- *
563
- * @example
564
- * ```typescript
565
- * parseDate('today') // Returns current date at start of day
566
- * parseDate('yesterday') // Returns yesterday at start of day
567
- * parseDate('2025-01-23') // Returns specific date
568
- * ```
569
- */
570
- declare function parseDate(dateStr: string): Date;
571
- /**
572
- * Groups prompts by day.
573
- *
574
- * @param prompts - Array of prompts to group
575
- * @returns Array of DayGroup objects, sorted by date
576
- *
577
- * @example
578
- * ```typescript
579
- * const groups = groupByDay(prompts);
580
- * // [
581
- * // { date: '2025-01-23', prompts: [...], projects: ['project-a'] },
582
- * // { date: '2025-01-24', prompts: [...], projects: ['project-b'] }
583
- * // ]
584
- * ```
585
- */
586
- declare function groupByDay(prompts: readonly ExtractedPrompt[]): readonly DayGroup[];
587
- /**
588
- * Reads all Claude Code logs and extracts user prompts.
589
- *
590
- * This function finds all JSONL files in the Claude projects directory,
591
- * parses them, and extracts user messages sorted chronologically.
592
- * Supports filtering by date range, single date, and project name.
593
- *
594
- * @param options - Optional filtering options
595
- * @returns LogReadResult containing prompts and warnings
596
- *
597
- * @example
598
- * ```typescript
599
- * // Read all logs
600
- * const result = await readLogs();
601
- *
602
- * // Filter by date
603
- * const today = await readLogs({ date: 'today' });
604
- *
605
- * // Filter by date range
606
- * const range = await readLogs({ from: '2025-01-20', to: '2025-01-25' });
607
- *
608
- * // Filter by project
609
- * const project = await readLogs({ project: 'my-app' });
610
- *
611
- * // Combine filters
612
- * const combined = await readLogs({
613
- * from: '2025-01-20',
614
- * to: '2025-01-25',
615
- * project: 'my-app'
616
- * });
617
- * ```
618
- */
619
- declare function readLogs(options?: ReadLogsOptions): Promise<LogReadResult>;
620
-
621
- /**
622
- * Secret Sanitizer for Hyntx
623
- *
624
- * This module provides functionality to automatically redact secrets and sensitive
625
- * information from prompts before sending them to AI providers.
626
- */
627
- /**
628
- * Result of sanitizing a single text.
629
- */
630
- type SanitizeResult = {
631
- readonly text: string;
632
- readonly redacted: number;
633
- };
634
- /**
635
- * Result of sanitizing multiple prompts.
636
- */
637
- type SanitizePromptsResult = {
638
- readonly prompts: readonly string[];
639
- readonly totalRedacted: number;
640
- };
641
- /**
642
- * Sanitizes a single text by redacting all detected secrets.
643
- *
644
- * @param text - Text to sanitize
645
- * @returns Sanitized text and count of redactions
646
- *
647
- * @example
648
- * ```typescript
649
- * const result = sanitize('My API key is sk-1234567890abcdef...');
650
- * // { text: 'My API key is [REDACTED_OPENAI_KEY]', redacted: 1 }
651
- * ```
652
- */
653
- declare function sanitize(text: string): SanitizeResult;
654
- /**
655
- * Sanitizes an array of prompts and returns sanitized prompts with total redaction count.
656
- *
657
- * @param prompts - Array of prompts to sanitize
658
- * @returns Sanitized prompts and total number of redactions across all prompts
659
- *
660
- * @example
661
- * ```typescript
662
- * const prompts = [
663
- * 'My key is sk-123...',
664
- * 'Email me at user@example.com'
665
- * ];
666
- * const result = sanitizePrompts(prompts);
667
- * // {
668
- * // prompts: ['My key is [REDACTED_OPENAI_KEY]', 'Email me at [REDACTED_EMAIL]'],
669
- * // totalRedacted: 2
670
- * // }
671
- * ```
672
- */
673
- declare function sanitizePrompts(prompts: readonly string[]): SanitizePromptsResult;
674
-
675
- /**
676
- * History management for Hyntx.
677
- *
678
- * This module provides functions to save, load, and compare analysis results.
679
- * History files are stored in ~/.hyntx/history/ with filenames as YYYY-MM-DD.json.
680
- */
681
-
682
- /**
683
- * Gets the history directory path.
684
- *
685
- * @returns History directory path
686
- */
687
- declare function getHistoryDir(): string;
688
- /**
689
- * Ensures the history directory exists with proper permissions.
690
- * Creates the directory if it doesn't exist.
691
- *
692
- * @throws Error if directory creation fails
693
- */
694
- declare function ensureHistoryDir(): Promise<void>;
695
- /**
696
- * Saves an analysis result to history with atomic write.
697
- * Sanitizes pattern examples before saving to protect privacy.
698
- * Does not throw on failure - logs warning instead.
699
- *
700
- * @param result - Analysis result to save
701
- * @param metadata - Analysis execution metadata
702
- */
703
- declare function saveAnalysisResult(result: AnalysisResult, metadata: HistoryMetadata): Promise<void>;
704
- /**
705
- * Loads an analysis result from history for a specific date.
706
- *
707
- * @param date - Date string (YYYY-MM-DD)
708
- * @returns History entry or null if not found
709
- */
710
- declare function loadAnalysisResult(date: string): Promise<HistoryEntry | null>;
711
- /**
712
- * Lists all available history dates.
713
- * Returns dates in descending order (newest first).
714
- *
715
- * @param options - Optional filtering options
716
- * @returns Array of date strings (YYYY-MM-DD)
717
- */
718
- declare function listAvailableDates(options?: ListHistoryOptions): Promise<readonly string[]>;
719
- /**
720
- * Compares two analysis results and identifies changes.
721
- *
722
- * @param before - Earlier analysis result
723
- * @param after - Later analysis result
724
- * @returns Comparison result with detected changes
725
- */
726
- declare function compareResults(before: AnalysisResult, after: AnalysisResult): ComparisonResult;
727
- /**
728
- * Calculates the date one week ago from a given date.
729
- *
730
- * @param fromDate - Date string (YYYY-MM-DD) or Date object
731
- * @returns Date string one week ago (YYYY-MM-DD)
732
- */
733
- declare function getDateOneWeekAgo(fromDate: string | Date): string;
734
- /**
735
- * Calculates the date one month ago from a given date.
736
- *
737
- * @param fromDate - Date string (YYYY-MM-DD) or Date object
738
- * @returns Date string one month ago (YYYY-MM-DD)
739
- */
740
- declare function getDateOneMonthAgo(fromDate: string | Date): string;
741
-
742
- /**
743
- * Provider factory with multi-provider support and fallback.
744
- *
745
- * This module provides factory functions for creating and selecting AI providers
746
- * with automatic fallback support when the primary provider is unavailable.
747
- */
748
-
749
- /**
750
- * Callback type for fallback notifications.
751
- * Called when getAvailableProvider falls back to a different provider.
752
- *
753
- * @param from - The provider that was unavailable
754
- * @param to - The provider that will be used instead
755
- */
756
- type FallbackCallback = (from: string, to: string) => void;
757
- /**
758
- * Creates a provider instance for the given type.
759
- *
760
- * @param type - The provider type to create
761
- * @param config - Environment configuration with provider settings
762
- * @param analysisMode - Optional analysis mode override ('batch' or 'individual')
763
- * @returns The created provider instance
764
- *
765
- * @example
766
- * const config = getEnvConfig();
767
- * const provider = createProvider('ollama', config, 'individual');
768
- */
769
- declare function createProvider(type: ProviderType, config: EnvConfig, analysisMode?: 'batch' | 'individual'): AnalysisProvider;
770
- /**
771
- * Gets the first available provider from the configured services list.
772
- * Tests each provider in order and returns the first one that is available.
773
- * Optionally calls a callback when falling back to a different provider.
774
- *
775
- * @param config - Environment configuration with services list and provider settings
776
- * @param onFallback - Optional callback called when falling back to a different provider
777
- * @param analysisMode - Optional analysis mode override ('batch' or 'individual')
778
- * @returns Promise resolving to the first available provider
779
- * @throws Error if no providers are configured or none are available
780
- *
781
- * @example
782
- * const config = getEnvConfig();
783
- * const provider = await getAvailableProvider(config, (from, to) => {
784
- * console.log(`Falling back from ${from} to ${to}`);
785
- * }, 'individual');
786
- */
787
- declare function getAvailableProvider(config: EnvConfig, onFallback?: FallbackCallback, analysisMode?: 'batch' | 'individual'): Promise<AnalysisProvider>;
788
- /**
789
- * Gets all configured providers as instances.
790
- * Returns providers for all types listed in the services configuration.
791
- *
792
- * @param config - Environment configuration with services list and provider settings
793
- * @param analysisMode - Optional analysis mode override ('batch' or 'individual')
794
- * @returns Array of provider instances
795
- * @throws Error if no providers are configured
796
- *
797
- * @example
798
- * const config = getEnvConfig();
799
- * const providers = getAllProviders(config, 'individual');
800
- * // [OllamaProvider, AnthropicProvider, ...]
801
- */
802
- declare function getAllProviders(config: EnvConfig, analysisMode?: 'batch' | 'individual'): readonly AnalysisProvider[];
803
-
804
- /**
805
- * Environment variable management for Hyntx.
806
- *
807
- * This module provides functions for reading and parsing environment
808
- * configuration, detecting first-time usage, and managing provider settings.
809
- */
810
-
811
- /**
812
- * Checks if this is the first run of Hyntx.
813
- * First run is detected when HYNTX_SERVICES is not set in process.env
814
- * AND no configuration exists in the shell config file.
815
- *
816
- * @returns true if this is the first run
817
- */
818
- declare function isFirstRun(): boolean;
819
- /**
820
- * Parses the HYNTX_SERVICES environment variable into an array of valid providers.
821
- * Invalid provider names are filtered out.
822
- *
823
- * @param services - Comma-separated list of provider names (e.g., "ollama,anthropic")
824
- * @returns Array of valid ProviderType values
825
- *
826
- * @example
827
- * parseServices('ollama,anthropic') // ['ollama', 'anthropic']
828
- * parseServices('ollama,invalid,google') // ['ollama', 'google']
829
- * parseServices('') // []
830
- * parseServices(undefined) // []
831
- */
832
- declare function parseServices(services: string | undefined): readonly ProviderType[];
833
- /**
834
- * Gets the complete configuration from environment variables.
835
- * Missing values are filled with defaults from ENV_DEFAULTS.
836
- *
837
- * @returns Complete EnvConfig object with all settings
838
- *
839
- * @example
840
- * // With environment variables set:
841
- * // HYNTX_SERVICES=ollama,anthropic
842
- * // HYNTX_ANTHROPIC_KEY=sk-ant-xxx
843
- *
844
- * const config = getEnvConfig();
845
- * // {
846
- * // services: ['ollama', 'anthropic'],
847
- * // reminder: '7d',
848
- * // ollama: { model: 'llama3.2', host: 'http://localhost:11434' },
849
- * // anthropic: { model: 'claude-3-5-haiku-latest', apiKey: 'sk-ant-xxx' },
850
- * // google: { model: 'gemini-2.0-flash-exp', apiKey: '' }
851
- * // }
852
- */
853
- declare function getEnvConfig(): EnvConfig;
854
-
855
- /**
856
- * Project-specific configuration system.
857
- *
858
- * This module provides utilities for loading and merging project-specific
859
- * configurations from `.hyntxrc.json` files. Project configs are merged with
860
- * environment configs, with env vars taking precedence.
861
- *
862
- * Features:
863
- * - Directory tree traversal to find config files
864
- * - JSON validation with Zod schema
865
- * - Config caching for performance
866
- * - Graceful error handling (non-fatal)
867
- */
868
-
869
- /**
870
- * Zod schema for the .hyntxrc.json file.
871
- */
872
- declare const PROJECT_CONFIG_SCHEMA: z.ZodObject<{
873
- context: z.ZodOptional<z.ZodObject<{
874
- role: z.ZodOptional<z.ZodString>;
875
- techStack: z.ZodOptional<z.ZodArray<z.ZodString>>;
876
- domain: z.ZodOptional<z.ZodString>;
877
- guidelines: z.ZodOptional<z.ZodArray<z.ZodString>>;
878
- projectType: z.ZodOptional<z.ZodString>;
879
- }, z.core.$strip>>;
880
- rules: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
881
- enabled: z.ZodOptional<z.ZodBoolean>;
882
- severity: z.ZodOptional<z.ZodEnum<{
883
- medium: "medium";
884
- low: "low";
885
- high: "high";
886
- }>>;
887
- }, z.core.$strip>>>;
888
- }, z.core.$strip>;
889
- /**
890
- * Type for the validated project config.
891
- */
892
- type ProjectConfig = z.infer<typeof PROJECT_CONFIG_SCHEMA>;
893
- /**
894
- * Loads and validates a project configuration file.
895
- *
896
- * Reads the JSON file, parses it, and validates against the Zod schema.
897
- * Errors are non-fatal and logged as warnings.
898
- *
899
- * @param configPath - Path to the .hyntxrc.json file
900
- * @returns Validated config object, or null if loading/validation fails
901
- *
902
- * @example
903
- * ```typescript
904
- * const config = loadProjectConfig('/path/to/.hyntxrc.json');
905
- * if (config?.context) {
906
- * console.log('Project role:', config.context.role);
907
- * }
908
- * ```
909
- */
910
- declare function loadProjectConfig(configPath: string): ProjectConfig | null;
911
- /**
912
- * Merges a project config with an environment config.
913
- *
914
- * Merging rules:
915
- * - Environment variables take precedence over project config
916
- * - If envConfig.context is set (from env vars), it overrides project context
917
- * - Otherwise, project context is used if available
918
- * - Rules from project config are always included if present
919
- *
920
- * @param envConfig - Configuration from environment variables
921
- * @param projectConfig - Configuration from .hyntxrc.json
922
- * @returns Merged configuration with context and rules fields
923
- *
924
- * @example
925
- * ```typescript
926
- * const merged = mergeConfigs(envConfig, projectConfig);
927
- * if (merged.context) {
928
- * // Use project context in analysis
929
- * }
930
- * if (merged.rules) {
931
- * // Apply custom rules configuration
932
- * }
933
- * ```
934
- */
935
- declare function mergeConfigs(envConfig: EnvConfig, projectConfig: ProjectConfig | null): EnvConfig & {
936
- context?: ProjectContext;
937
- rules?: RulesConfig;
938
- };
939
- /**
940
- * Loads project configuration for the specified working directory.
941
- *
942
- * This is the main entry point for loading project configs. It:
943
- * 1. Checks the cache first
944
- * 2. Searches for .hyntxrc.json up the directory tree
945
- * 3. Loads and validates the config file
946
- * 4. Caches the result
947
- *
948
- * @param cwd - Current working directory
949
- * @returns Loaded config or null if not found/invalid
950
- *
951
- * @example
952
- * ```typescript
953
- * const config = loadProjectConfigForCwd(process.cwd());
954
- * const merged = mergeConfigs(envConfig, config);
955
- * ```
956
- */
957
- declare function loadProjectConfigForCwd(cwd: string): ProjectConfig | null;
958
-
959
- /**
960
- * Disk-based cache for analysis results.
961
- *
962
- * This module provides caching functionality to avoid redundant API calls
963
- * for the same prompts. Cache entries are invalidated when:
964
- * - TTL expires (default: 7 days)
965
- * - Model changes
966
- * - System prompt changes
967
- */
968
-
969
- /**
970
- * Generates a cache key from prompts, model, and schema type.
971
- * The cache key uniquely identifies a batch of prompts for a specific model and schema.
972
- *
973
- * @param prompts - Array of prompt strings
974
- * @param model - Model identifier
975
- * @param schemaType - Schema type used for analysis (defaults to 'full' for backward compatibility)
976
- * @returns Cache key hash
977
- *
978
- * @example
979
- * ```typescript
980
- * const key = generateCacheKey(['prompt1', 'prompt2'], 'llama3.2', 'minimal');
981
- * // Returns: 'a3f2b1...' (SHA-256 hash)
982
- * ```
983
- */
984
- declare function generateCacheKey(prompts: readonly string[], model: string, schemaType?: string): string;
985
- /**
986
- * Hashes the system prompt for invalidation detection.
987
- * When the system prompt changes, all cache entries become invalid.
988
- *
989
- * @returns System prompt hash
990
- */
991
- declare function hashSystemPrompt(): string;
992
- /**
993
- * Validates that the system prompt has not changed.
994
- * If it has changed, clears the entire cache.
995
- *
996
- * @returns True if system prompt is valid, false if cache was invalidated
997
- */
998
- declare function validateSystemPrompt(): Promise<boolean>;
999
- /**
1000
- * Gets a cached result if it exists and is valid.
1001
- * Returns null if cache miss or entry is invalid (expired, wrong model, etc).
1002
- *
1003
- * @param prompts - Array of prompt strings
1004
- * @param model - Model identifier
1005
- * @param options - Cache options
1006
- * @returns Cached result or null
1007
- */
1008
- declare function getCachedResult(prompts: readonly string[], model: string, options?: CacheOptions): Promise<AnalysisResult | null>;
1009
- /**
1010
- * Stores an analysis result in the cache with atomic write.
1011
- * Does not throw on failure - logs warning instead.
1012
- *
1013
- * @param prompts - Array of prompt strings
1014
- * @param model - Model identifier
1015
- * @param result - Analysis result to cache
1016
- */
1017
- declare function setCachedResult(prompts: readonly string[], model: string, result: AnalysisResult): Promise<void>;
1018
- /**
1019
- * Clears all cached entries.
1020
- * Removes the entire cache analysis directory.
1021
- */
1022
- declare function clearCache(): Promise<void>;
1023
- /**
1024
- * Removes expired cache entries based on TTL.
1025
- * Useful for periodic cleanup to prevent disk bloat.
1026
- *
1027
- * @param options - Cache options
1028
- * @returns Number of entries removed
1029
- */
1030
- declare function cleanupExpiredEntries(options?: CacheOptions): Promise<number>;
1031
-
1032
- /**
1033
- * Path constants for Hyntx.
1034
- *
1035
- * This module provides path constants for accessing Claude Code logs
1036
- * and Hyntx state files.
1037
- */
1038
- /**
1039
- * Path to Claude Code projects directory.
1040
- * Contains JSONL log files organized by project hash.
1041
- *
1042
- * Structure: ~/.claude/projects/<project-hash>/*.jsonl
1043
- *
1044
- * Can be overridden via HYNTX_CLAUDE_PROJECTS_DIR environment variable.
1045
- * This is useful for testing or custom Claude Code installations.
1046
- */
1047
- declare const CLAUDE_PROJECTS_DIR: string;
1048
- /**
1049
- * Path to Hyntx last run timestamp file.
1050
- * Used by the reminder system to track when analysis was last run.
1051
- */
1052
- declare const LAST_RUN_FILE: string;
1053
- /**
1054
- * Path to Hyntx history directory.
1055
- * Contains analysis history files organized by date (YYYY-MM-DD.json).
1056
- *
1057
- * Structure: ~/.hyntx/history/YYYY-MM-DD.json
1058
- *
1059
- * Can be overridden via HYNTX_HISTORY_DIR environment variable.
1060
- */
1061
- declare const HYNTX_HISTORY_DIR: string;
1062
- /**
1063
- * Path to Hyntx cache directory.
1064
- * Contains cached analysis results to avoid redundant API calls.
1065
- *
1066
- * Structure: ~/.hyntx-cache/analysis/<cache-key>.json
1067
- * ~/.hyntx-cache/analysis/.metadata.json
1068
- *
1069
- * Can be overridden via HYNTX_CACHE_DIR environment variable.
1070
- */
1071
- declare const HYNTX_CACHE_DIR: string;
1072
- /**
1073
- * Path to cache analysis subdirectory.
1074
- * Contains individual cache entry files.
1075
- */
1076
- declare const CACHE_ANALYSIS_DIR: string;
1077
- /**
1078
- * Path to cache metadata file.
1079
- * Stores system prompt hash for invalidation detection.
1080
- */
1081
- declare const CACHE_META_FILE: string;
1082
-
1083
- export { type AnalysisPattern, type AnalysisProvider, type AnalysisResult, type AnalysisStats, type AnthropicConfig, BATCH_STRATEGIES, type BatchStrategy, type BatchStrategyType, type BeforeAfter, CACHE_ANALYSIS_DIR, CACHE_DEFAULTS, CACHE_META_FILE, CLAUDE_PROJECTS_DIR, type CacheMetadata, type CacheOptions, type CachedBatchResult, type ClaudeMessage, type CliOptions, type ComparisonChanges, type ComparisonResult, type DayGroup, ENV_DEFAULTS, EXIT_CODES, type EnvConfig, type ExitCode, type ExtractedPrompt, type FallbackCallback, type FilePosition, type GoogleConfig, HYNTX_CACHE_DIR, HYNTX_HISTORY_DIR, type HistoryEntry, type HistoryMetadata, type IssueMetadata, type IssueTaxonomy, type JsonErrorResponse, LAST_RUN_FILE, type ListHistoryOptions, type LogEntry, type LogReadResult, type LogWatcher, type MinimalResult, type OllamaConfig, type OutputFormat, PROVIDER_LIMITS, type PatternChange, type PatternSeverity, type ProjectContext, type PromptAnalysis, type PromptEvent, type ProviderLimits, type ProviderType, type ReadLogsOptions, type SanitizePromptsResult, type SanitizeResult, type SchemaType, type SchemaVersion, type ShellConfigResult, type ShellType, type WatcherOptions, analyzePrompts, claudeProjectsExist, cleanupExpiredEntries, clearCache, compareResults, createProvider, ensureHistoryDir, extractProjectName, generateCacheKey, getAllProviders, getAvailableProvider, getCachedResult, getDateOneMonthAgo, getDateOneWeekAgo, getEnvConfig, getHistoryDir, groupByDay, hashSystemPrompt, isFirstRun, listAvailableDates, loadAnalysisResult, loadProjectConfig, loadProjectConfigForCwd, mergeConfigs, parseDate, parseServices, readLogs, sanitize, sanitizePrompts, saveAnalysisResult, setCachedResult, validateSystemPrompt };