@danielsimonjr/memoryjs 1.2.2 → 1.4.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.d.cts CHANGED
@@ -2,6 +2,222 @@ import { z, ZodError, ZodSchema } from 'zod';
2
2
  import workerpool, { Pool, PoolStats } from '@danielsimonjr/workerpool';
3
3
  import { EventEmitter } from 'events';
4
4
 
5
+ /**
6
+ * Search Types
7
+ *
8
+ * Type definitions for search operations, tracing, and explanation.
9
+ * Phase 1 Sprint 6-7: Query logging, tracing, and result explanation.
10
+ *
11
+ * @module types/search
12
+ */
13
+ /**
14
+ * Log level for query logging.
15
+ */
16
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
17
+ /**
18
+ * Entry in the query log.
19
+ */
20
+ interface QueryLogEntry {
21
+ /** ISO 8601 timestamp */
22
+ timestamp: string;
23
+ /** Unique identifier for the query */
24
+ queryId: string;
25
+ /** Log level */
26
+ level: LogLevel;
27
+ /** Event name */
28
+ event: string;
29
+ /** Original query text */
30
+ queryText?: string;
31
+ /** Type of search performed */
32
+ queryType?: string;
33
+ /** Duration in milliseconds */
34
+ duration?: number;
35
+ /** Number of results */
36
+ resultCount?: number;
37
+ /** Additional metadata */
38
+ metadata?: Record<string, unknown>;
39
+ }
40
+ /**
41
+ * Complete trace of a search query execution.
42
+ */
43
+ interface QueryTrace {
44
+ /** Unique identifier for this query */
45
+ queryId: string;
46
+ /** Original query text */
47
+ queryText: string;
48
+ /** Type of search performed */
49
+ queryType: 'basic' | 'fuzzy' | 'boolean' | 'ranked' | 'bm25' | 'semantic' | 'hybrid';
50
+ /** ISO 8601 timestamp when query started */
51
+ startTime: string;
52
+ /** ISO 8601 timestamp when query completed */
53
+ endTime: string;
54
+ /** Total duration in milliseconds */
55
+ durationMs: number;
56
+ /** Number of results returned */
57
+ resultCount: number;
58
+ /** Breakdown of time spent in each stage */
59
+ stages: QueryStage[];
60
+ /** Additional metadata */
61
+ metadata?: Record<string, unknown>;
62
+ }
63
+ /**
64
+ * A single stage in query execution.
65
+ */
66
+ interface QueryStage {
67
+ /** Name of this stage */
68
+ name: string;
69
+ /** Duration in milliseconds */
70
+ durationMs: number;
71
+ /** Items processed in this stage */
72
+ itemsProcessed?: number;
73
+ /** Additional stage-specific data */
74
+ metadata?: Record<string, unknown>;
75
+ }
76
+ /**
77
+ * Explanation of why an entity matched a search query.
78
+ */
79
+ interface SearchExplanation {
80
+ /** Entity that was matched */
81
+ entityName: string;
82
+ /** Final computed score */
83
+ totalScore: number;
84
+ /** Breakdown of scoring signals */
85
+ signals: ScoringSignal[];
86
+ /** Terms from query that matched */
87
+ matchedTerms: MatchedTerm[];
88
+ /** Boost factors applied */
89
+ boosts: ScoreBoost[];
90
+ /** Human-readable summary */
91
+ summary: string;
92
+ }
93
+ /**
94
+ * A single scoring signal contributing to the total score.
95
+ */
96
+ interface ScoringSignal {
97
+ /** Name of this signal (e.g., 'tf-idf', 'bm25', 'semantic') */
98
+ name: string;
99
+ /** Raw value of this signal */
100
+ value: number;
101
+ /** Weight applied to this signal */
102
+ weight: number;
103
+ /** Contribution to final score (value * weight) */
104
+ contribution: number;
105
+ /** Percentage of total score from this signal */
106
+ percentage: number;
107
+ /** Additional signal-specific details */
108
+ details?: Record<string, unknown>;
109
+ }
110
+ /**
111
+ * Information about a matched term.
112
+ */
113
+ interface MatchedTerm {
114
+ /** The term that matched */
115
+ term: string;
116
+ /** Where it matched (name, observation, tag) */
117
+ field: 'name' | 'entityType' | 'observation' | 'tag';
118
+ /** Number of times it matched */
119
+ frequency: number;
120
+ /** TF-IDF or similar score for this term */
121
+ termScore: number;
122
+ }
123
+ /**
124
+ * A boost factor applied to the score.
125
+ */
126
+ interface ScoreBoost {
127
+ /** Name of the boost */
128
+ name: string;
129
+ /** Multiplier applied */
130
+ multiplier: number;
131
+ /** Reason for the boost */
132
+ reason: string;
133
+ }
134
+ /**
135
+ * Search result with explanation attached.
136
+ */
137
+ interface ExplainedSearchResult<T = unknown> {
138
+ /** The matched entity */
139
+ entity: T;
140
+ /** Computed score */
141
+ score: number;
142
+ /** Detailed explanation */
143
+ explanation: SearchExplanation;
144
+ }
145
+ /**
146
+ * Union of all query node types.
147
+ */
148
+ type QueryNode = TermNode | PhraseNode | WildcardNode | ProximityNode | FieldNode | BooleanOpNode;
149
+ /**
150
+ * A simple term node.
151
+ */
152
+ interface TermNode {
153
+ type: 'term';
154
+ value: string;
155
+ }
156
+ /**
157
+ * An exact phrase node.
158
+ */
159
+ interface PhraseNode {
160
+ type: 'phrase';
161
+ terms: string[];
162
+ }
163
+ /**
164
+ * A wildcard pattern node.
165
+ */
166
+ interface WildcardNode {
167
+ type: 'wildcard';
168
+ pattern: string;
169
+ regex: RegExp;
170
+ }
171
+ /**
172
+ * A proximity search node.
173
+ */
174
+ interface ProximityNode {
175
+ type: 'proximity';
176
+ terms: string[];
177
+ distance: number;
178
+ }
179
+ /**
180
+ * A field-specific search node.
181
+ */
182
+ interface FieldNode {
183
+ type: 'field';
184
+ field: string;
185
+ query: QueryNode;
186
+ }
187
+ /**
188
+ * A boolean operator node in the query parser.
189
+ * Note: Different from BooleanQueryNode in types.ts which is for AST representation.
190
+ */
191
+ interface BooleanOpNode {
192
+ type: 'boolean';
193
+ operator: 'AND' | 'OR' | 'NOT';
194
+ operands: QueryNode[];
195
+ }
196
+ /**
197
+ * Builder for creating QueryTrace objects.
198
+ */
199
+ declare class QueryTraceBuilder {
200
+ private trace;
201
+ private stageStart?;
202
+ constructor(queryId: string, queryText: string, queryType: QueryTrace['queryType']);
203
+ /**
204
+ * Start timing a stage.
205
+ */
206
+ startStage(_name: string): this;
207
+ /**
208
+ * End timing the current stage and record it.
209
+ */
210
+ endStage(name: string, metadata?: Record<string, unknown>): this;
211
+ /**
212
+ * Add a completed stage with known duration.
213
+ */
214
+ addStage(name: string, durationMs: number, metadata?: Record<string, unknown>): this;
215
+ /**
216
+ * Complete the trace and return the final QueryTrace.
217
+ */
218
+ complete(resultCount: number, metadata?: Record<string, unknown>): QueryTrace;
219
+ }
220
+
5
221
  /**
6
222
  * Task Scheduler
7
223
  *
@@ -345,6 +561,44 @@ interface Entity {
345
561
  /** Optional parent entity name for hierarchical nesting */
346
562
  parentId?: string;
347
563
  }
564
+ /**
565
+ * Typed properties for relations.
566
+ * Use this for structured access to common relation attributes.
567
+ * For arbitrary key-value pairs, use the `metadata` field instead.
568
+ *
569
+ * @example
570
+ * ```typescript
571
+ * const relation: Relation = {
572
+ * from: 'Alice',
573
+ * to: 'Bob',
574
+ * relationType: 'knows',
575
+ * weight: 0.8,
576
+ * properties: {
577
+ * bidirectional: true,
578
+ * validFrom: '2024-01-01',
579
+ * source: 'social_network_import',
580
+ * },
581
+ * };
582
+ * ```
583
+ */
584
+ interface RelationProperties {
585
+ /** Whether this relation is bidirectional (A->B implies B->A) */
586
+ bidirectional?: boolean;
587
+ /** Temporal validity - when this relation became valid (ISO 8601) */
588
+ validFrom?: string;
589
+ /** Temporal validity - when this relation stops being valid (ISO 8601) */
590
+ validUntil?: string;
591
+ /** Source/provenance of this relation */
592
+ source?: string;
593
+ /** How this relation was established */
594
+ method?: 'observed' | 'inferred' | 'declared' | 'imported';
595
+ /** Number of times this relation has been confirmed */
596
+ confirmationCount?: number;
597
+ /** Number of times this relation has been contradicted */
598
+ contradictionCount?: number;
599
+ /** Custom typed properties for domain-specific extensions */
600
+ custom?: Record<string, unknown>;
601
+ }
348
602
  /**
349
603
  * Represents a directed relation between two entities.
350
604
  *
@@ -373,6 +627,14 @@ interface Relation {
373
627
  createdAt?: string;
374
628
  /** ISO 8601 timestamp when relation was last modified */
375
629
  lastModified?: string;
630
+ /** Relation weight/strength (0-1), useful for weighted graph algorithms */
631
+ weight?: number;
632
+ /** Confidence score for this relation (0-1) */
633
+ confidence?: number;
634
+ /** Structured properties for typed access */
635
+ properties?: RelationProperties;
636
+ /** Arbitrary metadata for custom attributes */
637
+ metadata?: Record<string, unknown>;
376
638
  }
377
639
  /**
378
640
  * Represents the complete knowledge graph structure.
@@ -1365,13 +1627,33 @@ interface CentralityResult {
1365
1627
  algorithm: 'degree' | 'betweenness' | 'pagerank';
1366
1628
  }
1367
1629
  /**
1368
- * Phase 4 Sprint 9: Extended relation with optional weight and metadata.
1630
+ * A relation that has a weight value (required).
1631
+ * Useful for weighted graph algorithms (e.g., shortest path with weights).
1632
+ *
1633
+ * NOTE: The base Relation interface now has optional weight/metadata (Phase 1 Sprint 4).
1634
+ * Use WeightedRelation when weight is required.
1369
1635
  */
1370
1636
  interface WeightedRelation extends Relation {
1371
- /** Optional weight for the relation (default: 1.0) */
1372
- weight?: number;
1373
- /** Optional metadata for the relation */
1374
- metadata?: Record<string, unknown>;
1637
+ /** Weight for the relation - required for weighted algorithms (0-1) */
1638
+ weight: number;
1639
+ }
1640
+ /**
1641
+ * A relation with temporal validity.
1642
+ * Use for time-varying knowledge that has a valid date range.
1643
+ */
1644
+ interface TemporalRelation extends Relation {
1645
+ properties: RelationProperties & {
1646
+ validFrom: string;
1647
+ };
1648
+ }
1649
+ /**
1650
+ * A bidirectional relation (symmetric: A->B implies B->A).
1651
+ * Use for symmetric relationships like "married_to", "sibling_of".
1652
+ */
1653
+ interface BidirectionalRelation extends Relation {
1654
+ properties: RelationProperties & {
1655
+ bidirectional: true;
1656
+ };
1375
1657
  }
1376
1658
  /**
1377
1659
  * Phase 12 Sprint 5: Embedding mode for query-optimized encoding.
@@ -3027,20 +3309,154 @@ interface AgentMetadata {
3027
3309
  metadata?: Record<string, unknown>;
3028
3310
  }
3029
3311
 
3312
+ /**
3313
+ * Progress Types
3314
+ *
3315
+ * Type definitions for progress reporting.
3316
+ * Phase 1 Sprint 10: Progress Callbacks and Error Improvements.
3317
+ *
3318
+ * @module types/progress
3319
+ */
3320
+ /**
3321
+ * Progress information for batch operations.
3322
+ */
3323
+ interface ProgressInfo {
3324
+ /** Current item index (0-based) */
3325
+ current: number;
3326
+ /** Total number of items */
3327
+ total: number;
3328
+ /** Percentage complete (0-100) */
3329
+ percentage: number;
3330
+ /** Human-readable progress message */
3331
+ message: string;
3332
+ /** Current phase of operation (for multi-phase operations) */
3333
+ phase?: string;
3334
+ /** Name/identifier of current item being processed */
3335
+ currentItem?: string;
3336
+ /** Estimated time remaining in milliseconds */
3337
+ estimatedRemainingMs?: number;
3338
+ /** Start time of operation (ISO 8601) */
3339
+ startedAt?: string;
3340
+ /** Whether operation can be cancelled */
3341
+ cancellable?: boolean;
3342
+ }
3343
+ /**
3344
+ * Callback for receiving detailed progress updates.
3345
+ * Uses ProgressInfo for rich progress information.
3346
+ * (Note: utils/taskScheduler.ts exports a simpler ProgressInfoCallback type)
3347
+ */
3348
+ type ProgressInfoCallback = (progress: ProgressInfo) => void;
3349
+ /**
3350
+ * Options for operations that support progress reporting.
3351
+ */
3352
+ interface ProgressOptions {
3353
+ /** Callback to receive progress updates */
3354
+ onProgress?: ProgressInfoCallback;
3355
+ /** Minimum interval between progress callbacks (ms) */
3356
+ progressInterval?: number;
3357
+ /** Cancellation token */
3358
+ signal?: AbortSignal;
3359
+ }
3360
+ /**
3361
+ * Helper to create progress info.
3362
+ */
3363
+ declare function createProgressInfo(current: number, total: number, options?: {
3364
+ phase?: string;
3365
+ currentItem?: string;
3366
+ message?: string;
3367
+ startedAt?: Date;
3368
+ cancellable?: boolean;
3369
+ }): ProgressInfo;
3370
+ /**
3371
+ * Throttle progress callbacks to avoid overwhelming consumers.
3372
+ */
3373
+ declare function createThrottledProgress(callback: ProgressInfoCallback, intervalMs?: number): ProgressInfoCallback;
3374
+ /**
3375
+ * Create a detailed progress reporter with automatic throttling.
3376
+ * Returns an object with report/complete/cancel methods.
3377
+ * (Note: utils/operationUtils.ts exports a simpler createProgressReporter function)
3378
+ */
3379
+ declare function createDetailedProgressReporter(total: number, callback?: ProgressInfoCallback, options?: {
3380
+ intervalMs?: number;
3381
+ phase?: string;
3382
+ cancellable?: boolean;
3383
+ }): {
3384
+ report: (current: number, item?: string) => void;
3385
+ complete: () => void;
3386
+ cancel: () => void;
3387
+ };
3388
+
3030
3389
  /**
3031
3390
  * Custom Error Types
3032
3391
  *
3033
3392
  * Defines custom error classes for better error handling and debugging.
3393
+ * Phase 1 Sprint 10: Enhanced with ErrorCode enum and suggestions.
3034
3394
  *
3035
3395
  * @module utils/errors
3036
3396
  */
3397
+ /**
3398
+ * Error codes for programmatic handling.
3399
+ * Phase 1 Sprint 10: Centralized error codes.
3400
+ */
3401
+ declare enum ErrorCode {
3402
+ VALIDATION_FAILED = "VALIDATION_ERROR",
3403
+ REQUIRED_FIELD_MISSING = "REQUIRED_FIELD_MISSING",
3404
+ INVALID_FIELD_VALUE = "INVALID_FIELD_VALUE",
3405
+ SCHEMA_VALIDATION_FAILED = "SCHEMA_VALIDATION_FAILED",
3406
+ STORAGE_READ_FAILED = "STORAGE_READ_FAILED",
3407
+ STORAGE_WRITE_FAILED = "STORAGE_WRITE_FAILED",
3408
+ ENTITY_NOT_FOUND = "ENTITY_NOT_FOUND",
3409
+ RELATION_NOT_FOUND = "RELATION_NOT_FOUND",
3410
+ DUPLICATE_ENTITY = "DUPLICATE_ENTITY",
3411
+ STORAGE_CORRUPTED = "STORAGE_CORRUPTED",
3412
+ FILE_OPERATION_ERROR = "FILE_OPERATION_ERROR",
3413
+ SEARCH_FAILED = "SEARCH_FAILED",
3414
+ INVALID_QUERY = "INVALID_QUERY",
3415
+ INDEX_NOT_READY = "INDEX_NOT_READY",
3416
+ EMBEDDING_FAILED = "EMBEDDING_FAILED",
3417
+ INVALID_CONFIG = "INVALID_CONFIG",
3418
+ MISSING_DEPENDENCY = "MISSING_DEPENDENCY",
3419
+ UNSUPPORTED_FEATURE = "UNSUPPORTED_FEATURE",
3420
+ CYCLE_DETECTED = "CYCLE_DETECTED",
3421
+ INVALID_IMPORTANCE = "INVALID_IMPORTANCE",
3422
+ INSUFFICIENT_ENTITIES = "INSUFFICIENT_ENTITIES",
3423
+ OPERATION_CANCELLED = "OPERATION_CANCELLED",
3424
+ IMPORT_ERROR = "IMPORT_ERROR",
3425
+ EXPORT_ERROR = "EXPORT_ERROR",
3426
+ UNKNOWN_ERROR = "UNKNOWN_ERROR"
3427
+ }
3428
+ /**
3429
+ * Options for enhanced error construction.
3430
+ */
3431
+ interface ErrorOptions {
3432
+ /** Additional context for debugging */
3433
+ context?: Record<string, unknown>;
3434
+ /** Recovery suggestions for the user */
3435
+ suggestions?: string[];
3436
+ /** Original error that caused this one */
3437
+ cause?: Error;
3438
+ }
3037
3439
  /**
3038
3440
  * Base error class for all knowledge graph errors.
3039
3441
  * Extends the native Error class with additional context.
3442
+ * Phase 1 Sprint 10: Enhanced with suggestions and context.
3040
3443
  */
3041
3444
  declare class KnowledgeGraphError extends Error {
3042
- readonly code?: string | undefined;
3043
- constructor(message: string, code?: string | undefined);
3445
+ /** Error code for programmatic handling */
3446
+ readonly code: string;
3447
+ /** Additional context for debugging */
3448
+ readonly context?: Record<string, unknown>;
3449
+ /** Recovery suggestions for the user */
3450
+ readonly suggestions: string[];
3451
+ constructor(message: string, code?: string, options?: ErrorOptions);
3452
+ /**
3453
+ * Get a formatted error message with suggestions.
3454
+ */
3455
+ getDetailedMessage(): string;
3456
+ /**
3457
+ * Convert to a plain object for serialization.
3458
+ */
3459
+ toJSON(): Record<string, unknown>;
3044
3460
  }
3045
3461
  /**
3046
3462
  * Error thrown when an entity is not found.
@@ -3062,6 +3478,7 @@ declare class DuplicateEntityError extends KnowledgeGraphError {
3062
3478
  }
3063
3479
  /**
3064
3480
  * Error thrown when validation fails.
3481
+ * Note: Maintains backward-compatible signature with errors: string[].
3065
3482
  */
3066
3483
  declare class ValidationError extends KnowledgeGraphError {
3067
3484
  readonly errors: string[];
@@ -3122,6 +3539,24 @@ declare class OperationCancelledError extends KnowledgeGraphError {
3122
3539
  constructor(operation?: string);
3123
3540
  }
3124
3541
 
3542
+ /**
3543
+ * Error Suggestion Generator
3544
+ *
3545
+ * Provides context-specific suggestions for error recovery.
3546
+ * Phase 1 Sprint 10: Progress Callbacks and Error Improvements.
3547
+ *
3548
+ * @module utils/errorSuggestions
3549
+ */
3550
+
3551
+ /**
3552
+ * Generate context-specific suggestions based on error code and context.
3553
+ */
3554
+ declare function generateSuggestions(code: ErrorCode | string, context?: Record<string, unknown>): string[];
3555
+ /**
3556
+ * Get a single-line recovery hint for an error code.
3557
+ */
3558
+ declare function getQuickHint(code: ErrorCode | string): string;
3559
+
3125
3560
  /**
3126
3561
  * Application Constants
3127
3562
  *
@@ -4531,16 +4966,16 @@ declare const SavedSearchInputSchema: z.ZodObject<{
4531
4966
  maxImportance: z.ZodOptional<z.ZodNumber>;
4532
4967
  entityType: z.ZodOptional<z.ZodString>;
4533
4968
  }, "strict", z.ZodTypeAny, {
4534
- query: string;
4535
4969
  name: string;
4970
+ query: string;
4536
4971
  entityType?: string | undefined;
4537
4972
  tags?: string[] | undefined;
4538
4973
  description?: string | undefined;
4539
4974
  minImportance?: number | undefined;
4540
4975
  maxImportance?: number | undefined;
4541
4976
  }, {
4542
- query: string;
4543
4977
  name: string;
4978
+ query: string;
4544
4979
  entityType?: string | undefined;
4545
4980
  tags?: string[] | undefined;
4546
4981
  description?: string | undefined;
@@ -4559,15 +4994,15 @@ declare const SavedSearchUpdateSchema: z.ZodObject<{
4559
4994
  maxImportance: z.ZodOptional<z.ZodNumber>;
4560
4995
  entityType: z.ZodOptional<z.ZodString>;
4561
4996
  }, "strict", z.ZodTypeAny, {
4562
- query?: string | undefined;
4563
4997
  entityType?: string | undefined;
4998
+ query?: string | undefined;
4564
4999
  tags?: string[] | undefined;
4565
5000
  description?: string | undefined;
4566
5001
  minImportance?: number | undefined;
4567
5002
  maxImportance?: number | undefined;
4568
5003
  }, {
4569
- query?: string | undefined;
4570
5004
  entityType?: string | undefined;
5005
+ query?: string | undefined;
4571
5006
  tags?: string[] | undefined;
4572
5007
  description?: string | undefined;
4573
5008
  minImportance?: number | undefined;
@@ -5963,180 +6398,758 @@ declare function mapParallel<TInput, TOutput>(items: TInput[], mapper: (item: TI
5963
6398
  declare function filterParallel<T>(items: T[], predicate: (item: T, index: number) => Promise<boolean>, concurrency?: number): Promise<T[]>;
5964
6399
 
5965
6400
  /**
5966
- * Memory Usage Monitor
5967
- *
5968
- * Phase 12 Sprint 6: Track memory usage across all components
5969
- * with human-readable formatting.
5970
- *
5971
- * @module utils/MemoryMonitor
6401
+ * Memory Usage Monitor
6402
+ *
6403
+ * Phase 12 Sprint 6: Track memory usage across all components
6404
+ * with human-readable formatting.
6405
+ *
6406
+ * @module utils/MemoryMonitor
6407
+ */
6408
+ /**
6409
+ * Memory usage for a single component.
6410
+ */
6411
+ interface ComponentMemoryUsage {
6412
+ /** Component name */
6413
+ name: string;
6414
+ /** Estimated memory usage in bytes */
6415
+ bytes: number;
6416
+ /** Item count (if applicable) */
6417
+ itemCount?: number;
6418
+ /** Average bytes per item */
6419
+ bytesPerItem?: number;
6420
+ }
6421
+ /**
6422
+ * Aggregate memory usage statistics.
6423
+ */
6424
+ interface MemoryUsageStats {
6425
+ /** Total memory usage in bytes */
6426
+ totalBytes: number;
6427
+ /** Formatted total memory */
6428
+ totalFormatted: string;
6429
+ /** Per-component breakdown */
6430
+ components: ComponentMemoryUsage[];
6431
+ /** Timestamp of measurement */
6432
+ timestamp: Date;
6433
+ /** Node.js heap stats (if available) */
6434
+ heapStats?: {
6435
+ heapUsed: number;
6436
+ heapTotal: number;
6437
+ external: number;
6438
+ rss: number;
6439
+ };
6440
+ }
6441
+ /**
6442
+ * Memory threshold configuration.
6443
+ */
6444
+ interface MemoryThresholds {
6445
+ /** Warning threshold in bytes */
6446
+ warning: number;
6447
+ /** Critical threshold in bytes */
6448
+ critical: number;
6449
+ }
6450
+ /**
6451
+ * Memory alert.
6452
+ */
6453
+ interface MemoryAlert {
6454
+ /** Alert level */
6455
+ level: 'warning' | 'critical';
6456
+ /** Component that triggered the alert */
6457
+ component: string;
6458
+ /** Current usage */
6459
+ currentBytes: number;
6460
+ /** Threshold exceeded */
6461
+ threshold: number;
6462
+ /** Message */
6463
+ message: string;
6464
+ }
6465
+ /**
6466
+ * Callback for memory change events.
6467
+ */
6468
+ type MemoryChangeCallback = (usage: MemoryUsageStats) => void;
6469
+ /**
6470
+ * Memory Monitor for tracking usage across components.
6471
+ *
6472
+ * @example
6473
+ * ```typescript
6474
+ * const monitor = new MemoryMonitor();
6475
+ *
6476
+ * // Register components
6477
+ * monitor.registerComponent('entities', () => entities.length * 500);
6478
+ * monitor.registerComponent('vectors', () => vectors.size * dimension * 4);
6479
+ *
6480
+ * // Get usage stats
6481
+ * const stats = monitor.getUsage();
6482
+ * console.log(`Total memory: ${stats.totalFormatted}`);
6483
+ *
6484
+ * // Check for alerts
6485
+ * const alerts = monitor.checkThresholds();
6486
+ * ```
6487
+ */
6488
+ declare class MemoryMonitor {
6489
+ private componentEstimators;
6490
+ private itemCounters;
6491
+ private thresholds;
6492
+ private listeners;
6493
+ private lastUsage;
6494
+ constructor(thresholds?: Partial<MemoryThresholds>);
6495
+ /**
6496
+ * Register a component for memory tracking.
6497
+ *
6498
+ * @param name - Component name
6499
+ * @param estimator - Function that returns estimated bytes
6500
+ * @param itemCounter - Optional function that returns item count
6501
+ */
6502
+ registerComponent(name: string, estimator: () => number, itemCounter?: () => number): void;
6503
+ /**
6504
+ * Unregister a component.
6505
+ *
6506
+ * @param name - Component name
6507
+ */
6508
+ unregisterComponent(name: string): void;
6509
+ /**
6510
+ * Get current memory usage statistics.
6511
+ */
6512
+ getUsage(): MemoryUsageStats;
6513
+ /**
6514
+ * Get memory usage for a specific component.
6515
+ *
6516
+ * @param name - Component name
6517
+ */
6518
+ getComponentUsage(name: string): ComponentMemoryUsage | undefined;
6519
+ /**
6520
+ * Check memory thresholds and return alerts.
6521
+ */
6522
+ checkThresholds(): MemoryAlert[];
6523
+ /**
6524
+ * Set memory thresholds.
6525
+ *
6526
+ * @param thresholds - New threshold values
6527
+ */
6528
+ setThresholds(thresholds: Partial<MemoryThresholds>): void;
6529
+ /**
6530
+ * Get current thresholds.
6531
+ */
6532
+ getThresholds(): MemoryThresholds;
6533
+ /**
6534
+ * Add a listener for memory changes.
6535
+ *
6536
+ * @param callback - Callback to invoke on memory changes
6537
+ */
6538
+ addListener(callback: MemoryChangeCallback): void;
6539
+ /**
6540
+ * Remove a listener.
6541
+ *
6542
+ * @param callback - Callback to remove
6543
+ */
6544
+ removeListener(callback: MemoryChangeCallback): void;
6545
+ /**
6546
+ * Get a human-readable summary of memory usage.
6547
+ */
6548
+ getSummary(): string;
6549
+ /**
6550
+ * Get the last recorded usage without triggering a new measurement.
6551
+ */
6552
+ getLastUsage(): MemoryUsageStats | null;
6553
+ /**
6554
+ * Format bytes as human-readable string.
6555
+ *
6556
+ * @param bytes - Number of bytes
6557
+ */
6558
+ formatBytes(bytes: number): string;
6559
+ /**
6560
+ * Parse a formatted byte string back to number.
6561
+ *
6562
+ * @param formatted - Formatted string like "10 MB"
6563
+ */
6564
+ parseBytes(formatted: string): number;
6565
+ /**
6566
+ * Clear all registered components.
6567
+ */
6568
+ clear(): void;
6569
+ private notifyListeners;
6570
+ }
6571
+ /**
6572
+ * Singleton instance for global memory monitoring.
6573
+ */
6574
+ declare const globalMemoryMonitor: MemoryMonitor;
6575
+
6576
+ /**
6577
+ * Relation Helper Utilities
6578
+ *
6579
+ * Type guards and builder pattern for working with relations.
6580
+ *
6581
+ * @module utils/relationHelpers
6582
+ */
6583
+
6584
+ /**
6585
+ * Type guard to check if a relation has a weight.
6586
+ *
6587
+ * @param relation - The relation to check
6588
+ * @returns True if the relation has a numeric weight
6589
+ *
6590
+ * @example
6591
+ * ```typescript
6592
+ * const rel: Relation = { from: 'A', to: 'B', relationType: 'knows', weight: 0.5 };
6593
+ * if (isWeightedRelation(rel)) {
6594
+ * console.log(rel.weight); // TypeScript knows weight is number
6595
+ * }
6596
+ * ```
6597
+ */
6598
+ declare function isWeightedRelation(relation: Relation): relation is WeightedRelation;
6599
+ /**
6600
+ * Type guard to check if a relation has temporal validity.
6601
+ *
6602
+ * @param relation - The relation to check
6603
+ * @returns True if the relation has a validFrom property
6604
+ *
6605
+ * @example
6606
+ * ```typescript
6607
+ * if (isTemporalRelation(rel)) {
6608
+ * console.log(`Valid from: ${rel.properties.validFrom}`);
6609
+ * }
6610
+ * ```
6611
+ */
6612
+ declare function isTemporalRelation(relation: Relation): relation is TemporalRelation;
6613
+ /**
6614
+ * Type guard to check if a relation is bidirectional.
6615
+ *
6616
+ * @param relation - The relation to check
6617
+ * @returns True if the relation is marked as bidirectional
6618
+ *
6619
+ * @example
6620
+ * ```typescript
6621
+ * if (isBidirectionalRelation(rel)) {
6622
+ * // This relation implies the reverse relation exists
6623
+ * }
6624
+ * ```
6625
+ */
6626
+ declare function isBidirectionalRelation(relation: Relation): relation is BidirectionalRelation;
6627
+ /**
6628
+ * Check if a relation has a confidence score.
6629
+ *
6630
+ * @param relation - The relation to check
6631
+ * @returns True if the relation has a confidence score
6632
+ */
6633
+ declare function hasConfidence(relation: Relation): boolean;
6634
+ /**
6635
+ * Check if a relation is currently valid based on temporal properties.
6636
+ *
6637
+ * @param relation - The relation to check
6638
+ * @param referenceDate - Date to check against (default: now)
6639
+ * @returns True if the relation is valid at the reference date
6640
+ */
6641
+ declare function isCurrentlyValid(relation: Relation, referenceDate?: Date): boolean;
6642
+ /**
6643
+ * Fluent builder for constructing relations.
6644
+ *
6645
+ * Provides a convenient way to build relations with validation.
6646
+ *
6647
+ * @example
6648
+ * ```typescript
6649
+ * const relation = new RelationBuilder('Alice', 'Bob', 'knows')
6650
+ * .withWeight(0.8)
6651
+ * .withConfidence(0.95)
6652
+ * .bidirectional()
6653
+ * .validFrom('2024-01-01')
6654
+ * .build();
6655
+ * ```
6656
+ */
6657
+ declare class RelationBuilder {
6658
+ private relation;
6659
+ /**
6660
+ * Create a new RelationBuilder.
6661
+ *
6662
+ * @param from - Source entity name
6663
+ * @param to - Target entity name
6664
+ * @param relationType - Type of relationship
6665
+ */
6666
+ constructor(from: string, to: string, relationType: string);
6667
+ /**
6668
+ * Set the weight for this relation.
6669
+ *
6670
+ * @param weight - Weight value (must be between 0 and 1)
6671
+ * @throws Error if weight is out of range
6672
+ */
6673
+ withWeight(weight: number): this;
6674
+ /**
6675
+ * Set the confidence score for this relation.
6676
+ *
6677
+ * @param confidence - Confidence value (must be between 0 and 1)
6678
+ * @throws Error if confidence is out of range
6679
+ */
6680
+ withConfidence(confidence: number): this;
6681
+ /**
6682
+ * Mark this relation as bidirectional.
6683
+ *
6684
+ * @param value - Whether the relation is bidirectional (default: true)
6685
+ */
6686
+ bidirectional(value?: boolean): this;
6687
+ /**
6688
+ * Set when this relation becomes valid.
6689
+ *
6690
+ * @param date - ISO 8601 date string
6691
+ */
6692
+ validFrom(date: string): this;
6693
+ /**
6694
+ * Set when this relation stops being valid.
6695
+ *
6696
+ * @param date - ISO 8601 date string
6697
+ */
6698
+ validUntil(date: string): this;
6699
+ /**
6700
+ * Set the source/provenance of this relation.
6701
+ *
6702
+ * @param source - Source identifier
6703
+ */
6704
+ withSource(source: string): this;
6705
+ /**
6706
+ * Set how this relation was established.
6707
+ *
6708
+ * @param method - Establishment method
6709
+ */
6710
+ withMethod(method: RelationProperties['method']): this;
6711
+ /**
6712
+ * Add arbitrary metadata to the relation.
6713
+ *
6714
+ * @param metadata - Key-value pairs to add
6715
+ */
6716
+ withMetadata(metadata: Record<string, unknown>): this;
6717
+ /**
6718
+ * Build the final relation object.
6719
+ *
6720
+ * Automatically sets createdAt timestamp if not already set.
6721
+ *
6722
+ * @returns The constructed relation
6723
+ */
6724
+ build(): Relation;
6725
+ }
6726
+
6727
+ /**
6728
+ * Relation Validation Utilities
6729
+ *
6730
+ * Functions for validating relation properties.
6731
+ *
6732
+ * @module utils/relationValidation
6733
+ */
6734
+
6735
+ /**
6736
+ * A validation error for relation fields.
6737
+ * Named distinctly from ValidationIssue in types.ts which is for graph validation.
6738
+ */
6739
+ interface RelationValidationError {
6740
+ /** Field that has the error */
6741
+ field: string;
6742
+ /** Error message */
6743
+ message: string;
6744
+ /** The invalid value (if applicable) */
6745
+ value?: unknown;
6746
+ }
6747
+ /**
6748
+ * A validation warning for relation fields.
6749
+ * Warnings don't make a relation invalid, but may indicate potential issues.
6750
+ */
6751
+ interface RelationValidationWarning {
6752
+ /** Field that has the warning */
6753
+ field: string;
6754
+ /** Warning message */
6755
+ message: string;
6756
+ /** Suggested fix (if applicable) */
6757
+ suggestion?: string;
6758
+ }
6759
+ /**
6760
+ * Result of relation validation.
6761
+ */
6762
+ interface RelationValidationResult {
6763
+ /** Whether the relation is valid (no errors) */
6764
+ isValid: boolean;
6765
+ /** List of validation errors */
6766
+ errors: RelationValidationError[];
6767
+ /** List of validation warnings */
6768
+ warnings: RelationValidationWarning[];
6769
+ }
6770
+ /**
6771
+ * Validate relation properties.
6772
+ *
6773
+ * Checks:
6774
+ * - Required fields (from, to, relationType)
6775
+ * - Weight range (0-1) if present
6776
+ * - Confidence range (0-1) if present
6777
+ * - Temporal consistency (validFrom <= validUntil) if both present
6778
+ * - Self-referential relations (warning)
6779
+ *
6780
+ * @param relation - The relation to validate
6781
+ * @returns Validation result with errors and warnings
6782
+ *
6783
+ * @example
6784
+ * ```typescript
6785
+ * const result = validateRelationMetadata({
6786
+ * from: 'Alice',
6787
+ * to: 'Bob',
6788
+ * relationType: 'knows',
6789
+ * weight: 1.5, // Invalid - out of range
6790
+ * });
6791
+ *
6792
+ * if (!result.isValid) {
6793
+ * console.log('Errors:', result.errors);
6794
+ * }
6795
+ * ```
6796
+ */
6797
+ declare function validateRelationMetadata(relation: Relation): RelationValidationResult;
6798
+ /**
6799
+ * Validate multiple relations at once.
6800
+ *
6801
+ * @param relations - Array of relations to validate
6802
+ * @returns Array of validation results (same order as input)
6803
+ */
6804
+ declare function validateRelationsMetadata(relations: Relation[]): RelationValidationResult[];
6805
+ /**
6806
+ * Check if all relations are valid.
6807
+ *
6808
+ * @param relations - Array of relations to check
6809
+ * @returns True if all relations are valid
6810
+ */
6811
+ declare function allRelationsValidMetadata(relations: Relation[]): boolean;
6812
+
6813
+ /**
6814
+ * Entity Validator
6815
+ *
6816
+ * Validates entities against configurable rules.
6817
+ * Types are embedded to avoid collision with ValidationIssue in types.ts
6818
+ * Phase 1 Sprint 9: Entity Validation Helpers.
6819
+ *
6820
+ * @module utils/EntityValidator
6821
+ */
6822
+
6823
+ /**
6824
+ * A validation rule for entities.
6825
+ */
6826
+ interface EntityValidationRule {
6827
+ /** Name of this rule for identification */
6828
+ name: string;
6829
+ /** Field path to validate (e.g., 'name', 'observations.0') */
6830
+ field: string;
6831
+ /** Validation function */
6832
+ validate: (entity: Entity) => EntityRuleResult | Promise<EntityRuleResult>;
6833
+ /** Error message if validation fails */
6834
+ message: string;
6835
+ /** Severity level */
6836
+ severity?: 'error' | 'warning';
6837
+ }
6838
+ /**
6839
+ * Result of a single rule validation.
6840
+ */
6841
+ interface EntityRuleResult {
6842
+ /** Whether validation passed */
6843
+ valid: boolean;
6844
+ /** Optional custom message override */
6845
+ message?: string;
6846
+ }
6847
+ /**
6848
+ * A validation issue found during entity validation.
6849
+ * Named distinctly from ValidationIssue in types.ts (which is for graph validation).
6850
+ */
6851
+ interface EntityValidationIssue {
6852
+ /** Field that failed validation */
6853
+ field: string;
6854
+ /** Error/warning message */
6855
+ message: string;
6856
+ /** Severity level */
6857
+ severity: 'error' | 'warning';
6858
+ /** Current value of the field */
6859
+ value?: unknown;
6860
+ /** Name of the rule that failed */
6861
+ rule?: string;
6862
+ /** Suggestion for fixing the issue */
6863
+ suggestion?: string;
6864
+ }
6865
+ /**
6866
+ * Complete validation result for an entity.
6867
+ */
6868
+ interface EntityValidationResult {
6869
+ /** Whether entity is valid */
6870
+ isValid: boolean;
6871
+ /** Validation errors */
6872
+ errors: EntityValidationIssue[];
6873
+ /** Validation warnings */
6874
+ warnings: EntityValidationIssue[];
6875
+ /** The entity that was validated */
6876
+ entity: Entity;
6877
+ }
6878
+ interface EntityValidatorConfig {
6879
+ /** Rules to apply */
6880
+ rules?: EntityValidationRule[];
6881
+ /** Stop on first error */
6882
+ failFast?: boolean;
6883
+ /** Treat warnings as errors */
6884
+ strict?: boolean;
6885
+ }
6886
+ /**
6887
+ * Validates entities against configurable rules.
6888
+ *
6889
+ * @example
6890
+ * ```typescript
6891
+ * import { EntityValidator, required, minLength, pattern } from './EntityValidator.js';
6892
+ *
6893
+ * const validator = new EntityValidator({
6894
+ * rules: [
6895
+ * required('name'),
6896
+ * minLength('name', 3),
6897
+ * pattern('name', /^[a-zA-Z]/),
6898
+ * ],
6899
+ * });
6900
+ *
6901
+ * const result = await validator.validate(entity);
6902
+ * if (!result.isValid) {
6903
+ * console.error(result.errors);
6904
+ * }
6905
+ * ```
6906
+ */
6907
+ declare class EntityValidator {
6908
+ private readonly config;
6909
+ constructor(config?: EntityValidatorConfig);
6910
+ /**
6911
+ * Add a validation rule.
6912
+ */
6913
+ addRule(rule: EntityValidationRule): this;
6914
+ /**
6915
+ * Add multiple validation rules.
6916
+ */
6917
+ addRules(rules: EntityValidationRule[]): this;
6918
+ /**
6919
+ * Get all registered rules.
6920
+ */
6921
+ getRules(): EntityValidationRule[];
6922
+ /**
6923
+ * Clear all rules.
6924
+ */
6925
+ clearRules(): this;
6926
+ /**
6927
+ * Validate an entity against all rules.
6928
+ */
6929
+ validate(entity: Entity): Promise<EntityValidationResult>;
6930
+ /**
6931
+ * Validate multiple entities.
6932
+ */
6933
+ validateAll(entities: Entity[]): Promise<Map<string, EntityValidationResult>>;
6934
+ /**
6935
+ * Validate an entity synchronously (only works if all rules are sync).
6936
+ */
6937
+ validateSync(entity: Entity): EntityValidationResult;
6938
+ /**
6939
+ * Get a field value from entity using dot notation path.
6940
+ */
6941
+ private getFieldValue;
6942
+ }
6943
+
6944
+ /**
6945
+ * Built-in Validators
6946
+ *
6947
+ * Factory functions for common validation rules.
6948
+ * Phase 1 Sprint 9: Entity Validation Helpers.
6949
+ *
6950
+ * @module utils/validators
6951
+ */
6952
+
6953
+ /**
6954
+ * Require a field to have a value.
6955
+ */
6956
+ declare function required(field: string, message?: string): EntityValidationRule;
6957
+ /**
6958
+ * Require a string field to have minimum length.
6959
+ */
6960
+ declare function minLength(field: string, min: number, message?: string): EntityValidationRule;
6961
+ /**
6962
+ * Require a string field to have maximum length.
6963
+ */
6964
+ declare function maxLength(field: string, max: number, message?: string): EntityValidationRule;
6965
+ /**
6966
+ * Require a string field to match a pattern.
6967
+ */
6968
+ declare function pattern(field: string, regex: RegExp, description?: string, message?: string): EntityValidationRule;
6969
+ /**
6970
+ * Require a numeric field to be within range.
6971
+ */
6972
+ declare function range(field: string, min: number, max: number, message?: string): EntityValidationRule;
6973
+ /**
6974
+ * Require a numeric field to be at least a minimum value.
6975
+ */
6976
+ declare function min(field: string, minValue: number, message?: string): EntityValidationRule;
6977
+ /**
6978
+ * Require a numeric field to be at most a maximum value.
6979
+ */
6980
+ declare function max(field: string, maxValue: number, message?: string): EntityValidationRule;
6981
+ /**
6982
+ * Require a field to be one of specified values.
6983
+ */
6984
+ declare function oneOf<T>(field: string, values: T[], message?: string): EntityValidationRule;
6985
+ /**
6986
+ * Require array field to have minimum items.
6987
+ */
6988
+ declare function minItems(field: string, minCount: number, message?: string): EntityValidationRule;
6989
+ /**
6990
+ * Require array field to have maximum items.
6991
+ */
6992
+ declare function maxItems(field: string, maxCount: number, message?: string): EntityValidationRule;
6993
+ /**
6994
+ * Require a field to be a valid email address.
6995
+ */
6996
+ declare function email(field: string, message?: string): EntityValidationRule;
6997
+ /**
6998
+ * Require a field to be a valid URL.
6999
+ */
7000
+ declare function url(field: string, message?: string): EntityValidationRule;
7001
+ /**
7002
+ * Require a field to be a valid ISO 8601 date string.
7003
+ */
7004
+ declare function isoDate(field: string, message?: string): EntityValidationRule;
7005
+ /**
7006
+ * Require a field to be of a specific type.
7007
+ */
7008
+ declare function typeOf(field: string, expectedType: 'string' | 'number' | 'boolean' | 'object' | 'array', message?: string): EntityValidationRule;
7009
+ /**
7010
+ * Custom validator with user-provided function.
5972
7011
  */
7012
+ declare function custom(field: string, validator: (value: unknown, entity: Entity) => boolean | Promise<boolean>, message: string): EntityValidationRule;
5973
7013
  /**
5974
- * Memory usage for a single component.
7014
+ * Synchronous custom validator.
5975
7015
  */
5976
- interface ComponentMemoryUsage {
5977
- /** Component name */
5978
- name: string;
5979
- /** Estimated memory usage in bytes */
5980
- bytes: number;
5981
- /** Item count (if applicable) */
5982
- itemCount?: number;
5983
- /** Average bytes per item */
5984
- bytesPerItem?: number;
5985
- }
7016
+ declare function customSync(field: string, validator: (value: unknown, entity: Entity) => boolean, message: string): EntityValidationRule;
5986
7017
  /**
5987
- * Aggregate memory usage statistics.
7018
+ * Create a warning (non-blocking) version of a rule.
5988
7019
  */
5989
- interface MemoryUsageStats {
5990
- /** Total memory usage in bytes */
5991
- totalBytes: number;
5992
- /** Formatted total memory */
5993
- totalFormatted: string;
5994
- /** Per-component breakdown */
5995
- components: ComponentMemoryUsage[];
5996
- /** Timestamp of measurement */
5997
- timestamp: Date;
5998
- /** Node.js heap stats (if available) */
5999
- heapStats?: {
6000
- heapUsed: number;
6001
- heapTotal: number;
6002
- external: number;
6003
- rss: number;
6004
- };
6005
- }
7020
+ declare function asWarning(rule: EntityValidationRule): EntityValidationRule;
6006
7021
  /**
6007
- * Memory threshold configuration.
7022
+ * Combine multiple rules for the same field.
6008
7023
  */
6009
- interface MemoryThresholds {
6010
- /** Warning threshold in bytes */
6011
- warning: number;
6012
- /** Critical threshold in bytes */
6013
- critical: number;
6014
- }
7024
+ declare function all(...rules: EntityValidationRule[]): EntityValidationRule[];
6015
7025
  /**
6016
- * Memory alert.
7026
+ * Conditionally apply a rule based on a predicate.
6017
7027
  */
6018
- interface MemoryAlert {
6019
- /** Alert level */
6020
- level: 'warning' | 'critical';
6021
- /** Component that triggered the alert */
6022
- component: string;
6023
- /** Current usage */
6024
- currentBytes: number;
6025
- /** Threshold exceeded */
6026
- threshold: number;
6027
- /** Message */
6028
- message: string;
6029
- }
7028
+ declare function when(predicate: (entity: Entity) => boolean, rule: EntityValidationRule): EntityValidationRule;
7029
+
6030
7030
  /**
6031
- * Callback for memory change events.
7031
+ * Schema Validator
7032
+ *
7033
+ * JSON Schema validation for entities using ajv.
7034
+ * Phase 1 Sprint 9: Entity Validation Helpers.
7035
+ *
7036
+ * @module utils/SchemaValidator
6032
7037
  */
6033
- type MemoryChangeCallback = (usage: MemoryUsageStats) => void;
7038
+
6034
7039
  /**
6035
- * Memory Monitor for tracking usage across components.
7040
+ * JSON Schema type definition (simplified).
7041
+ */
7042
+ interface JsonSchema {
7043
+ type?: string | string[];
7044
+ properties?: Record<string, JsonSchema>;
7045
+ required?: string[];
7046
+ additionalProperties?: boolean;
7047
+ minLength?: number;
7048
+ maxLength?: number;
7049
+ minimum?: number;
7050
+ maximum?: number;
7051
+ pattern?: string;
7052
+ enum?: unknown[];
7053
+ items?: JsonSchema;
7054
+ minItems?: number;
7055
+ maxItems?: number;
7056
+ format?: string;
7057
+ default?: unknown;
7058
+ description?: string;
7059
+ $ref?: string;
7060
+ allOf?: JsonSchema[];
7061
+ anyOf?: JsonSchema[];
7062
+ oneOf?: JsonSchema[];
7063
+ not?: JsonSchema;
7064
+ if?: JsonSchema;
7065
+ then?: JsonSchema;
7066
+ else?: JsonSchema;
7067
+ [key: string]: unknown;
7068
+ }
7069
+ /**
7070
+ * Validates entities against JSON Schemas.
7071
+ * Requires ajv to be installed as optional peer dependency.
6036
7072
  *
6037
7073
  * @example
6038
7074
  * ```typescript
6039
- * const monitor = new MemoryMonitor();
6040
- *
6041
- * // Register components
6042
- * monitor.registerComponent('entities', () => entities.length * 500);
6043
- * monitor.registerComponent('vectors', () => vectors.size * dimension * 4);
6044
- *
6045
- * // Get usage stats
6046
- * const stats = monitor.getUsage();
6047
- * console.log(`Total memory: ${stats.totalFormatted}`);
7075
+ * const validator = new SchemaValidator();
7076
+ * await validator.initialize(); // Load ajv dynamically
7077
+ *
7078
+ * validator.registerSchema('person', {
7079
+ * type: 'object',
7080
+ * required: ['name', 'entityType'],
7081
+ * properties: {
7082
+ * name: { type: 'string', minLength: 1 },
7083
+ * entityType: { type: 'string', enum: ['person'] },
7084
+ * },
7085
+ * });
6048
7086
  *
6049
- * // Check for alerts
6050
- * const alerts = monitor.checkThresholds();
7087
+ * const result = validator.validate(entity);
6051
7088
  * ```
6052
7089
  */
6053
- declare class MemoryMonitor {
6054
- private componentEstimators;
6055
- private itemCounters;
6056
- private thresholds;
6057
- private listeners;
6058
- private lastUsage;
6059
- constructor(thresholds?: Partial<MemoryThresholds>);
7090
+ declare class SchemaValidator {
7091
+ private schemas;
7092
+ private ajv;
7093
+ private validators;
7094
+ private initialized;
6060
7095
  /**
6061
- * Register a component for memory tracking.
6062
- *
6063
- * @param name - Component name
6064
- * @param estimator - Function that returns estimated bytes
6065
- * @param itemCounter - Optional function that returns item count
7096
+ * Initialize the validator by loading ajv dynamically.
7097
+ * Call this before using validate() if you want schema validation.
6066
7098
  */
6067
- registerComponent(name: string, estimator: () => number, itemCounter?: () => number): void;
7099
+ initialize(): Promise<boolean>;
6068
7100
  /**
6069
- * Unregister a component.
6070
- *
6071
- * @param name - Component name
7101
+ * Check if schema validation is available.
6072
7102
  */
6073
- unregisterComponent(name: string): void;
7103
+ isAvailable(): boolean;
6074
7104
  /**
6075
- * Get current memory usage statistics.
7105
+ * Check if initialized.
6076
7106
  */
6077
- getUsage(): MemoryUsageStats;
7107
+ isInitialized(): boolean;
6078
7108
  /**
6079
- * Get memory usage for a specific component.
6080
- *
6081
- * @param name - Component name
7109
+ * Register a schema for an entity type.
6082
7110
  */
6083
- getComponentUsage(name: string): ComponentMemoryUsage | undefined;
7111
+ registerSchema(entityType: string, schema: JsonSchema): void;
6084
7112
  /**
6085
- * Check memory thresholds and return alerts.
7113
+ * Compile a schema using ajv.
6086
7114
  */
6087
- checkThresholds(): MemoryAlert[];
7115
+ private compileSchema;
6088
7116
  /**
6089
- * Set memory thresholds.
6090
- *
6091
- * @param thresholds - New threshold values
7117
+ * Unregister a schema.
6092
7118
  */
6093
- setThresholds(thresholds: Partial<MemoryThresholds>): void;
7119
+ unregisterSchema(entityType: string): void;
6094
7120
  /**
6095
- * Get current thresholds.
7121
+ * Validate an entity against its type's schema.
6096
7122
  */
6097
- getThresholds(): MemoryThresholds;
7123
+ validate(entity: Entity): EntityValidationResult;
6098
7124
  /**
6099
- * Add a listener for memory changes.
6100
- *
6101
- * @param callback - Callback to invoke on memory changes
7125
+ * Validate multiple entities.
6102
7126
  */
6103
- addListener(callback: MemoryChangeCallback): void;
7127
+ validateAll(entities: Entity[]): Map<string, EntityValidationResult>;
6104
7128
  /**
6105
- * Remove a listener.
6106
- *
6107
- * @param callback - Callback to remove
7129
+ * Get field path from AJV error.
6108
7130
  */
6109
- removeListener(callback: MemoryChangeCallback): void;
7131
+ private getFieldPath;
6110
7132
  /**
6111
- * Get a human-readable summary of memory usage.
7133
+ * Get human-readable error message.
6112
7134
  */
6113
- getSummary(): string;
7135
+ private getErrorMessage;
6114
7136
  /**
6115
- * Get the last recorded usage without triggering a new measurement.
7137
+ * Get suggestion for fixing the error.
6116
7138
  */
6117
- getLastUsage(): MemoryUsageStats | null;
7139
+ private getSuggestion;
6118
7140
  /**
6119
- * Format bytes as human-readable string.
6120
- *
6121
- * @param bytes - Number of bytes
7141
+ * Get registered schema for entity type.
6122
7142
  */
6123
- formatBytes(bytes: number): string;
7143
+ getSchema(entityType: string): JsonSchema | undefined;
6124
7144
  /**
6125
- * Parse a formatted byte string back to number.
6126
- *
6127
- * @param formatted - Formatted string like "10 MB"
7145
+ * Get all registered entity types.
6128
7146
  */
6129
- parseBytes(formatted: string): number;
7147
+ getRegisteredTypes(): string[];
6130
7148
  /**
6131
- * Clear all registered components.
7149
+ * Check if a schema is registered for an entity type.
6132
7150
  */
6133
- clear(): void;
6134
- private notifyListeners;
7151
+ hasSchema(entityType: string): boolean;
6135
7152
  }
6136
- /**
6137
- * Singleton instance for global memory monitoring.
6138
- */
6139
- declare const globalMemoryMonitor: MemoryMonitor;
6140
7153
 
6141
7154
  /**
6142
7155
  * Transaction Manager
@@ -7297,6 +8310,11 @@ declare class SQLiteStorage implements IGraphStorage {
7297
8310
  * Create database tables, indexes, and FTS5 virtual table.
7298
8311
  */
7299
8312
  private createTables;
8313
+ /**
8314
+ * Phase 1 Sprint 5: Migrate relations table to add metadata columns.
8315
+ * Checks if columns exist and adds them if not for backward compatibility.
8316
+ */
8317
+ private migrateRelationsTable;
7300
8318
  /**
7301
8319
  * Load all data from SQLite into memory cache.
7302
8320
  */
@@ -7307,6 +8325,7 @@ declare class SQLiteStorage implements IGraphStorage {
7307
8325
  private rowToEntity;
7308
8326
  /**
7309
8327
  * Convert a database row to a Relation object.
8328
+ * Phase 1 Sprint 5: Includes metadata fields.
7310
8329
  */
7311
8330
  private rowToRelation;
7312
8331
  /**
@@ -12479,6 +13498,244 @@ declare class QuantizedVectorStore {
12479
13498
  private computeError;
12480
13499
  }
12481
13500
 
13501
+ /**
13502
+ * Query Logger
13503
+ *
13504
+ * Provides structured logging for search operations.
13505
+ * Supports console, file, and callback outputs.
13506
+ * Phase 1 Sprint 6: Query Logging and Tracing.
13507
+ *
13508
+ * @module search/QueryLogger
13509
+ */
13510
+
13511
+ /**
13512
+ * Configuration for QueryLogger.
13513
+ */
13514
+ interface QueryLoggerConfig {
13515
+ /** Minimum log level to output */
13516
+ level?: LogLevel;
13517
+ /** Log to console */
13518
+ console?: boolean;
13519
+ /** Log to file path */
13520
+ filePath?: string;
13521
+ /** Custom callback for log entries */
13522
+ callback?: (entry: QueryLogEntry) => void;
13523
+ /** Include timestamps in console output */
13524
+ timestamps?: boolean;
13525
+ }
13526
+ /**
13527
+ * Query logger for search operations.
13528
+ *
13529
+ * @example
13530
+ * ```typescript
13531
+ * const logger = new QueryLogger({ level: 'debug', console: true });
13532
+ * logger.logQueryStart('q123', 'hello world', 'ranked');
13533
+ * // ... search executes ...
13534
+ * logger.logQueryEnd('q123', 150, 10);
13535
+ * ```
13536
+ */
13537
+ declare class QueryLogger {
13538
+ private readonly config;
13539
+ constructor(config?: QueryLoggerConfig);
13540
+ /**
13541
+ * Check if logging is enabled (any output configured).
13542
+ */
13543
+ isEnabled(): boolean;
13544
+ /**
13545
+ * Log the start of a query.
13546
+ */
13547
+ logQueryStart(queryId: string, queryText: string, queryType: string): void;
13548
+ /**
13549
+ * Log the end of a query.
13550
+ */
13551
+ logQueryEnd(queryId: string, durationMs: number, resultCount: number): void;
13552
+ /**
13553
+ * Log a query stage.
13554
+ */
13555
+ logStage(queryId: string, stage: string, durationMs: number, metadata?: Record<string, unknown>): void;
13556
+ /**
13557
+ * Log a debug message.
13558
+ */
13559
+ debug(queryId: string, message: string, metadata?: Record<string, unknown>): void;
13560
+ /**
13561
+ * Log an info message.
13562
+ */
13563
+ info(queryId: string, message: string, metadata?: Record<string, unknown>): void;
13564
+ /**
13565
+ * Log a warning.
13566
+ */
13567
+ warn(queryId: string, message: string, metadata?: Record<string, unknown>): void;
13568
+ /**
13569
+ * Log an error.
13570
+ */
13571
+ error(queryId: string, message: string, error?: Error): void;
13572
+ private log;
13573
+ /**
13574
+ * Format data for console output (remove undefined values).
13575
+ */
13576
+ private formatConsoleData;
13577
+ /**
13578
+ * Generate a unique query ID.
13579
+ */
13580
+ static generateQueryId(): string;
13581
+ }
13582
+
13583
+ /**
13584
+ * Query Parser
13585
+ *
13586
+ * Parses search query strings into structured query objects.
13587
+ * Supports: phrases ("..."), wildcards (*?), proximity (~N), fields (field:).
13588
+ * Phase 1 Sprint 8: Full-Text Search Operators.
13589
+ *
13590
+ * @module search/QueryParser
13591
+ */
13592
+
13593
+ /**
13594
+ * Query parser for advanced search syntax.
13595
+ *
13596
+ * @example
13597
+ * ```typescript
13598
+ * const parser = new QueryParser();
13599
+ *
13600
+ * // Phrase search
13601
+ * parser.parse('"machine learning"');
13602
+ *
13603
+ * // Wildcard search
13604
+ * parser.parse('data*');
13605
+ *
13606
+ * // Proximity search
13607
+ * parser.parse('"machine learning"~3');
13608
+ *
13609
+ * // Field-specific search
13610
+ * parser.parse('name:Alice');
13611
+ *
13612
+ * // Combined
13613
+ * parser.parse('name:"John Doe" AND type:person');
13614
+ * ```
13615
+ */
13616
+ declare class QueryParser {
13617
+ /**
13618
+ * Parse a query string into a QueryNode tree.
13619
+ */
13620
+ parse(query: string): QueryNode;
13621
+ /**
13622
+ * Check if a query uses advanced operators.
13623
+ */
13624
+ hasAdvancedOperators(query: string): boolean;
13625
+ /**
13626
+ * Parse boolean expressions (AND, OR, NOT).
13627
+ */
13628
+ private parseBooleanExpression;
13629
+ /**
13630
+ * Split query by operator, respecting quotes.
13631
+ */
13632
+ private splitByOperator;
13633
+ /**
13634
+ * Tokenize query string, handling quotes.
13635
+ */
13636
+ private tokenize;
13637
+ /**
13638
+ * Parse tokenized query.
13639
+ */
13640
+ private parseTokens;
13641
+ /**
13642
+ * Parse a single token into a QueryNode.
13643
+ */
13644
+ private parseToken;
13645
+ /**
13646
+ * Convert wildcard pattern to regex.
13647
+ */
13648
+ private wildcardToRegex;
13649
+ }
13650
+ /**
13651
+ * Check if text contains the phrase (terms in order).
13652
+ */
13653
+ declare function matchesPhrase(text: string, terms: string[]): boolean;
13654
+ /**
13655
+ * Check if pattern is a simple prefix (e.g., 'foo*').
13656
+ */
13657
+ declare function isPrefixPattern(pattern: string): boolean;
13658
+ /**
13659
+ * Match text against prefix pattern.
13660
+ */
13661
+ declare function matchesPrefix(text: string, pattern: string): boolean;
13662
+
13663
+ /**
13664
+ * Proximity Search
13665
+ *
13666
+ * Finds entities where terms appear within a specified distance.
13667
+ * Phase 1 Sprint 8: Full-Text Search Operators.
13668
+ *
13669
+ * @module search/ProximitySearch
13670
+ */
13671
+
13672
+ /**
13673
+ * Result of a proximity match.
13674
+ */
13675
+ interface ProximityMatch {
13676
+ /** The matched entity */
13677
+ entity: Entity;
13678
+ /** Score based on proximity (closer = higher) */
13679
+ score: number;
13680
+ /** Minimum distance found between terms */
13681
+ minDistance: number;
13682
+ /** Detailed match locations */
13683
+ matches: ProximityMatchLocation[];
13684
+ }
13685
+ /**
13686
+ * Location where proximity match was found.
13687
+ */
13688
+ interface ProximityMatchLocation {
13689
+ /** Field where match was found */
13690
+ field: string;
13691
+ /** Term positions in the text */
13692
+ positions: Map<string, number[]>;
13693
+ /** Distance between terms */
13694
+ distance: number;
13695
+ }
13696
+ /**
13697
+ * Proximity search implementation.
13698
+ *
13699
+ * @example
13700
+ * ```typescript
13701
+ * const search = new ProximitySearch();
13702
+ *
13703
+ * // Find entities where "machine" and "learning" appear within 3 words
13704
+ * const results = search.search(entities, {
13705
+ * type: 'proximity',
13706
+ * terms: ['machine', 'learning'],
13707
+ * distance: 3
13708
+ * });
13709
+ * ```
13710
+ */
13711
+ declare class ProximitySearch {
13712
+ /**
13713
+ * Search for entities where terms appear within distance.
13714
+ */
13715
+ search(entities: Entity[], node: ProximityNode): ProximityMatch[];
13716
+ /**
13717
+ * Check if entity matches the proximity query.
13718
+ */
13719
+ private matchEntity;
13720
+ /**
13721
+ * Find minimum distance between all terms in text.
13722
+ * Returns null if any term is not found.
13723
+ */
13724
+ private findProximity;
13725
+ /**
13726
+ * Find minimum span containing all terms.
13727
+ */
13728
+ private findMinSpan;
13729
+ /**
13730
+ * Get positions of all terms in text.
13731
+ */
13732
+ private getPositions;
13733
+ /**
13734
+ * Calculate proximity score between two specific terms.
13735
+ */
13736
+ static calculateProximityScore(text: string, term1: string, term2: string, maxDistance: number): number | null;
13737
+ }
13738
+
12482
13739
  /**
12483
13740
  * IO Manager
12484
13741
  *
@@ -16966,4 +18223,4 @@ declare class KeywordExtractor {
16966
18223
  getDomainBoosts(): Map<string, number>;
16967
18224
  }
16968
18225
 
16969
- export { type AccessContext, AccessContextBuilder, type AccessPattern, type AdaptiveDepthConfig, type AddObservationInput, AddObservationInputSchema, AddObservationsInputSchema, type AdequacyCheck, type AgentEntity, type AgentObservation, AnalyticsManager, type ArchiveCriteria, type ArchiveCriteriaInput, ArchiveCriteriaSchema, ArchiveManager, type ArchiveOptions, type ArchiveResult, type ArchiveResultExtended, type AutoSearchResult, type BM25Config, type BM25DocumentEntry, type BM25Index, BM25Search, type BackupInfo, type BackupInfoExtended, type BackupMetadata, type BackupMetadataExtended, type BackupOptions, type BackupResult, BasicSearch, BatchCreateEntitiesSchema, BatchCreateRelationsSchema, type BatchItemResult, type BatchOperation, type BatchOperationType, type BatchOptions, type BatchProcessResult, BatchProcessor, type BatchProcessorOptions, type BatchProgress, type BatchProgressCallback, type BatchResult, BatchTransaction, type BooleanCacheEntry, type BooleanQueryNode, BooleanSearch, COMPRESSION_CONFIG, type CacheCompressionStats, type CacheStats, type CachedQueryEntry, type CentralityResult, type CommonSearchFilters, type ComponentMemoryUsage, CompressedCache, type CompressedCacheOptions, type CompressedCacheStats, CompressionManager, type CompressionMetadata, type CompressionOptions, type CompressionQuality, type CompressionResult, type ConnectedComponentsResult, type ConsolidateOptions, type ConsolidationAction, type ConsolidationResult, type ConsolidationRule, type ConsolidationTrigger, type ContextPackage, type ContextRetrievalOptions, type CreateEntityInput, CreateEntitySchema, type CreateRelationInput, CreateRelationSchema, CycleDetectedError, DEFAULT_BASE_DIR, DEFAULT_BM25_CONFIG, DEFAULT_DUPLICATE_THRESHOLD, DEFAULT_EMBEDDING_CACHE_OPTIONS, DEFAULT_FILE_NAMES, DEFAULT_HYBRID_WEIGHTS, DEFAULT_INDEXER_OPTIONS, DEFAULT_SCORER_WEIGHTS, DOCUMENT_PREFIX, type DateRange, DateRangeSchema, type DecayOptions, type DecayResult, type DeleteObservationInput, DeleteObservationInputSchema, DeleteObservationsInputSchema, DeleteRelationsSchema, type DocumentVector, DuplicateEntityError, type DuplicatePair, ENV_VARS, EarlyTerminationManager, type EarlyTerminationOptions, type EarlyTerminationResult, EmbeddingCache, type EmbeddingCacheOptions, type EmbeddingCacheStats, type EmbeddingConfig, type EmbeddingMode, type EmbeddingProgressCallback, type EmbeddingService, type Entity, type EntityCreatedEvent, type EntityDeletedEvent, type EntityInput, EntityManager, EntityNamesSchema, EntityNotFoundError, EntitySchema, type EntityUpdatedEvent, type EpisodicMemoryEntity, type ExcludedEntity, ExportError, type ExportFilter, type ExportFilterInput, ExportFilterSchema, type ExportFormat, ExportFormatSchema, type ExportOptions, type ExportResult, type ExtendedExportFormatInput, ExtendedExportFormatSchema, type ExtendedPoolStats, type ExtendedQueryCostEstimate, type ExtractedEntity, FILE_EXTENSIONS, FILE_SUFFIXES, FileOperationError, type FlushResult, type ForgetOptions, type ForgetResult, type FuzzyCacheKey, FuzzySearch, type FuzzySearchOptions, GRAPH_LIMITS, type GraphCompressionResult, type GraphEvent, type GraphEventBase, GraphEventEmitter, type GraphEventListener, type GraphEventMap, type GraphEventType, type GraphLoadedEvent, type GraphSavedEvent, type GraphStats, GraphStorage, GraphTraversal, HierarchyManager, HybridScorer, type HybridScorerOptions, HybridSearchManager, type HybridSearchOptions, type HybridSearchResult, type HybridWeights, type IGraphStorage, IMPORTANCE_RANGE, IOManager, type IVectorStore, ImportError, type ImportFormat, type ImportFormatInput, ImportFormatSchema, type ImportResult, InMemoryVectorStore, IncrementalIndexer, type IncrementalIndexerOptions, type IndexMemoryUsage, type IndexOperation, type IndexOperationType, InsufficientEntitiesError, InvalidImportanceError, KeywordExtractor, type KnowledgeGraph, KnowledgeGraphError, ManagerContext as KnowledgeGraphManager, LOG_PREFIXES, type LayerRecommendationOptions, type LayerTiming, type LexicalSearchResult, LocalEmbeddingService, type LongRunningOperationOptions, LowercaseCache, type LowercaseData, ManagerContext, type MemoryAcquisitionMethod, type MemoryAlert, type MemoryChangeCallback, type MemoryMergeStrategy, MemoryMonitor, type MemorySource, type MemoryThresholds, type MemoryType, type MemoryUsageStats, type MemoryVisibility, type MergeResult, type MergeStrategy, type MergeStrategyInput, MergeStrategySchema, MockEmbeddingService, NameIndex, type NormalizationOptions, type NormalizationResult, type ObservationAddedEvent, type ObservationDeletedEvent, ObservationManager, ObservationNormalizer, type ObservationSource, OpenAIEmbeddingService, OperationCancelledError, OperationType, OptimizedInvertedIndex, OptionalEntityNamesSchema, OptionalTagsSchema, type PaginatedCacheEntry, ParallelSearchExecutor, type ParallelSearchOptions, type ParallelSearchResult, type PathResult, type PatternResult, type PhaseDefinition, type PoolEventCallback, type PostingListResult, type PreparedEntity, type ProceduralMemoryEntity, type ProgressCallback, QUERY_LIMITS, QUERY_PREFIX, type QuantizationParams, type QuantizedSearchResult, QuantizedVectorStore, type QuantizedVectorStoreOptions, type QuantizedVectorStoreStats, type QueryAnalysis, QueryAnalyzer, type QueryCostEstimate, QueryCostEstimator, type QueryCostEstimatorOptions, type QueryPlan, QueryPlanCache, type QueryPlanCacheOptions, type QueryPlanCacheStats, QueryPlanner, type QueueStats, RankedSearch, type ReadonlyKnowledgeGraph, type RefinementHistoryEntry, ReflectionManager, type ReflectionOptions, type ReflectionResult, type Relation, type RelationCreatedEvent, type RelationDeletedEvent, RelationIndex, type RelationInput, RelationManager, RelationNotFoundError, RelationSchema, type RestoreResult, type RuleConditions, type RuleEvaluationResult, SEARCH_LIMITS, SIMILARITY_WEIGHTS, SQLiteStorage, type SQLiteStorageWithEmbeddings, SQLiteVectorStore, STOPWORDS, STREAMING_CONFIG, type SalienceComponents, type SalienceContext, type SalienceWeights, type SavedSearch, type SavedSearchInput, SavedSearchInputSchema, SavedSearchManager, type SavedSearchUpdateInput, SavedSearchUpdateSchema, type ScoredEntity, type ScoredKeyword, type ScoredResult, SearchCache, SearchFilterChain, type SearchFilters, type SearchLayer, SearchManager, type SearchMethod, type SearchQuery, SearchQuerySchema, type SearchResult, SearchSuggestions, type SemanticIndexOptions, type SemanticLayerResult, type SemanticMemoryEntity, SemanticSearch, type SemanticSearchResult, type SessionEntity, type SessionStatus, type StorageConfig, type StreamResult, StreamingExporter, type SubQuery, type SummarizationResult, type SymbolicFilters, type SymbolicResult, SymbolicSearch, type SymbolicSearchResult, TFIDFEventSync, type TFIDFIndex, TFIDFIndexManager, type TagAlias, type TagAliasInput, TagAliasSchema, TagManager, type Task, type TaskBatchOptions, TaskPriority, TaskQueue, type TaskResult, TaskStatus, type TemporalFocus, type TemporalRange, type TokenBreakdown, type TokenEstimationOptions, type TokenizedEntity, type ToolResponse, TransactionManager, type TransactionOperation, type TransactionResult, type TraversalOptions, type TraversalResult, TypeIndex, type UpdateEntityInput, UpdateEntitySchema, type ValidatedPagination, ValidationError, type ValidationIssue, type ValidationReport, type ValidationResult, type ValidationWarning, type VectorSearchResult, type WeightedRelation, type WorkerPoolConfig, WorkerPoolManager, type WorkingMemoryEntity, type WorkingMemoryOptions, addUniqueTags, applyPagination, batchProcess, calculateIDF, calculateIDFFromTokenSets, calculateTF, calculateTFIDF, checkCancellation, chunkArray, cleanupAllCaches, clearAllSearchCaches, compress, compressFile, compressToBase64, cosineSimilarity, createEmbeddingService, createMetadata, createProgress, createProgressReporter, createStorage, createStorageFromPath, createUncompressedMetadata, createVectorStore, debounce, decompress, decompressFile, decompressFromBase64, defaultMemoryPath, ensureMemoryFilePath, entityExists, entityPassesFilters, entityToText, escapeCsvFormula, executeWithPhases, filterByCreatedDate, filterByEntityType, filterByImportance, filterByModifiedDate, filterByTags, filterParallel, findEntitiesByNames, findEntityByName, fnv1aHash, formatErrorResponse, formatRawResponse, formatTextResponse, formatToolResponse, formatZodErrors, getAllCacheStats, getCompressionRatio, getCurrentTimestamp, getEntityIndex, getEntityNameSet, getPaginationMeta, getPoolStats, getWorkerPoolManager, globalMemoryMonitor, groupEntitiesByType, hasAllTags, hasBrotliExtension, hasMatchingTag, isAgentEntity, isEpisodicMemory, isProceduralMemory, isSemanticMemory, isSessionEntity, isValidISODate, isWithinDateRange, isWithinImportanceRange, isWorkingMemory, l2Normalize, levenshteinDistance, logger, mapParallel, normalizeTag, normalizeTags, paginateArray, parallelFilter, parallelLimit, parallelMap, parseDateRange, processBatch, processBatchesWithProgress, processWithRetry, rateLimitedProcess, removeEntityByName, removeTags, sanitizeObject, searchCaches, shutdownParallelUtils, throttle, tokenize, touchEntity, validateArrayWithSchema, validateEntity, validateFilePath, validateImportance, validatePagination, validateRelation, validateSafe, validateTags, validateWithSchema, withRetry };
18226
+ export { type AccessContext, AccessContextBuilder, type AccessPattern, type AdaptiveDepthConfig, type AddObservationInput, AddObservationInputSchema, AddObservationsInputSchema, type AdequacyCheck, type AgentEntity, type AgentObservation, AnalyticsManager, type ArchiveCriteria, type ArchiveCriteriaInput, ArchiveCriteriaSchema, ArchiveManager, type ArchiveOptions, type ArchiveResult, type ArchiveResultExtended, type AutoSearchResult, type BM25Config, type BM25DocumentEntry, type BM25Index, BM25Search, type BackupInfo, type BackupInfoExtended, type BackupMetadata, type BackupMetadataExtended, type BackupOptions, type BackupResult, BasicSearch, BatchCreateEntitiesSchema, BatchCreateRelationsSchema, type BatchItemResult, type BatchOperation, type BatchOperationType, type BatchOptions, type BatchProcessResult, BatchProcessor, type BatchProcessorOptions, type BatchProgress, type BatchProgressCallback, type BatchResult, BatchTransaction, type BidirectionalRelation, type BooleanCacheEntry, type BooleanOpNode, type BooleanQueryNode, BooleanSearch, COMPRESSION_CONFIG, type CacheCompressionStats, type CacheStats, type CachedQueryEntry, type CentralityResult, type CommonSearchFilters, type ComponentMemoryUsage, CompressedCache, type CompressedCacheOptions, type CompressedCacheStats, CompressionManager, type CompressionMetadata, type CompressionOptions, type CompressionQuality, type CompressionResult, type ConnectedComponentsResult, type ConsolidateOptions, type ConsolidationAction, type ConsolidationResult, type ConsolidationRule, type ConsolidationTrigger, type ContextPackage, type ContextRetrievalOptions, type CreateEntityInput, CreateEntitySchema, type CreateRelationInput, CreateRelationSchema, CycleDetectedError, DEFAULT_BASE_DIR, DEFAULT_BM25_CONFIG, DEFAULT_DUPLICATE_THRESHOLD, DEFAULT_EMBEDDING_CACHE_OPTIONS, DEFAULT_FILE_NAMES, DEFAULT_HYBRID_WEIGHTS, DEFAULT_INDEXER_OPTIONS, DEFAULT_SCORER_WEIGHTS, DOCUMENT_PREFIX, type DateRange, DateRangeSchema, type DecayOptions, type DecayResult, type DeleteObservationInput, DeleteObservationInputSchema, DeleteObservationsInputSchema, DeleteRelationsSchema, type DocumentVector, DuplicateEntityError, type DuplicatePair, ENV_VARS, EarlyTerminationManager, type EarlyTerminationOptions, type EarlyTerminationResult, EmbeddingCache, type EmbeddingCacheOptions, type EmbeddingCacheStats, type EmbeddingConfig, type EmbeddingMode, type EmbeddingProgressCallback, type EmbeddingService, type Entity, type EntityCreatedEvent, type EntityDeletedEvent, type EntityInput, EntityManager, EntityNamesSchema, EntityNotFoundError, type EntityRuleResult, EntitySchema, type EntityUpdatedEvent, type EntityValidationIssue, type EntityValidationResult, type EntityValidationRule, EntityValidator, type EntityValidatorConfig, type EpisodicMemoryEntity, ErrorCode, type ErrorOptions, type ExcludedEntity, type ExplainedSearchResult, ExportError, type ExportFilter, type ExportFilterInput, ExportFilterSchema, type ExportFormat, ExportFormatSchema, type ExportOptions, type ExportResult, type ExtendedExportFormatInput, ExtendedExportFormatSchema, type ExtendedPoolStats, type ExtendedQueryCostEstimate, type ExtractedEntity, FILE_EXTENSIONS, FILE_SUFFIXES, type FieldNode, FileOperationError, type FlushResult, type ForgetOptions, type ForgetResult, type FuzzyCacheKey, FuzzySearch, type FuzzySearchOptions, GRAPH_LIMITS, type GraphCompressionResult, type GraphEvent, type GraphEventBase, GraphEventEmitter, type GraphEventListener, type GraphEventMap, type GraphEventType, type GraphLoadedEvent, type GraphSavedEvent, type GraphStats, GraphStorage, GraphTraversal, HierarchyManager, HybridScorer, type HybridScorerOptions, HybridSearchManager, type HybridSearchOptions, type HybridSearchResult, type HybridWeights, type IGraphStorage, IMPORTANCE_RANGE, IOManager, type IVectorStore, ImportError, type ImportFormat, type ImportFormatInput, ImportFormatSchema, type ImportResult, InMemoryVectorStore, IncrementalIndexer, type IncrementalIndexerOptions, type IndexMemoryUsage, type IndexOperation, type IndexOperationType, InsufficientEntitiesError, InvalidImportanceError, type JsonSchema, KeywordExtractor, type KnowledgeGraph, KnowledgeGraphError, ManagerContext as KnowledgeGraphManager, LOG_PREFIXES, type LayerRecommendationOptions, type LayerTiming, type LexicalSearchResult, LocalEmbeddingService, type LogLevel, type LongRunningOperationOptions, LowercaseCache, type LowercaseData, ManagerContext, type MatchedTerm, type MemoryAcquisitionMethod, type MemoryAlert, type MemoryChangeCallback, type MemoryMergeStrategy, MemoryMonitor, type MemorySource, type MemoryThresholds, type MemoryType, type MemoryUsageStats, type MemoryVisibility, type MergeResult, type MergeStrategy, type MergeStrategyInput, MergeStrategySchema, MockEmbeddingService, NameIndex, type NormalizationOptions, type NormalizationResult, type ObservationAddedEvent, type ObservationDeletedEvent, ObservationManager, ObservationNormalizer, type ObservationSource, OpenAIEmbeddingService, OperationCancelledError, OperationType, OptimizedInvertedIndex, OptionalEntityNamesSchema, OptionalTagsSchema, type PaginatedCacheEntry, ParallelSearchExecutor, type ParallelSearchOptions, type ParallelSearchResult, type PathResult, type PatternResult, type PhaseDefinition, type PhraseNode, type PoolEventCallback, type PostingListResult, type PreparedEntity, type ProceduralMemoryEntity, type ProgressCallback, type ProgressInfo, type ProgressInfoCallback, type ProgressOptions, type ProximityMatch, type ProximityMatchLocation, type ProximityNode, ProximitySearch, QUERY_LIMITS, QUERY_PREFIX, type QuantizationParams, type QuantizedSearchResult, QuantizedVectorStore, type QuantizedVectorStoreOptions, type QuantizedVectorStoreStats, type QueryAnalysis, QueryAnalyzer, type QueryCostEstimate, QueryCostEstimator, type QueryCostEstimatorOptions, type QueryLogEntry, QueryLogger, type QueryLoggerConfig, type QueryNode, QueryParser, type QueryPlan, QueryPlanCache, type QueryPlanCacheOptions, type QueryPlanCacheStats, QueryPlanner, type QueryStage, type QueryTrace, QueryTraceBuilder, type QueueStats, RankedSearch, type ReadonlyKnowledgeGraph, type RefinementHistoryEntry, ReflectionManager, type ReflectionOptions, type ReflectionResult, type Relation, RelationBuilder, type RelationCreatedEvent, type RelationDeletedEvent, RelationIndex, type RelationInput, RelationManager, RelationNotFoundError, type RelationProperties, RelationSchema, type RelationValidationError, type RelationValidationResult, type RelationValidationWarning, type RestoreResult, type RuleConditions, type RuleEvaluationResult, SEARCH_LIMITS, SIMILARITY_WEIGHTS, SQLiteStorage, type SQLiteStorageWithEmbeddings, SQLiteVectorStore, STOPWORDS, STREAMING_CONFIG, type SalienceComponents, type SalienceContext, type SalienceWeights, type SavedSearch, type SavedSearchInput, SavedSearchInputSchema, SavedSearchManager, type SavedSearchUpdateInput, SavedSearchUpdateSchema, SchemaValidator, type ScoreBoost, type ScoredEntity, type ScoredKeyword, type ScoredResult, type ScoringSignal, SearchCache, type SearchExplanation, SearchFilterChain, type SearchFilters, type SearchLayer, SearchManager, type SearchMethod, type SearchQuery, SearchQuerySchema, type SearchResult, SearchSuggestions, type SemanticIndexOptions, type SemanticLayerResult, type SemanticMemoryEntity, SemanticSearch, type SemanticSearchResult, type SessionEntity, type SessionStatus, type StorageConfig, type StreamResult, StreamingExporter, type SubQuery, type SummarizationResult, type SymbolicFilters, type SymbolicResult, SymbolicSearch, type SymbolicSearchResult, TFIDFEventSync, type TFIDFIndex, TFIDFIndexManager, type TagAlias, type TagAliasInput, TagAliasSchema, TagManager, type Task, type TaskBatchOptions, TaskPriority, TaskQueue, type TaskResult, TaskStatus, type TemporalFocus, type TemporalRange, type TemporalRelation, type TermNode, type TokenBreakdown, type TokenEstimationOptions, type TokenizedEntity, type ToolResponse, TransactionManager, type TransactionOperation, type TransactionResult, type TraversalOptions, type TraversalResult, TypeIndex, type UpdateEntityInput, UpdateEntitySchema, type ValidatedPagination, ValidationError, type ValidationIssue, type ValidationReport, type ValidationResult, type ValidationWarning, type VectorSearchResult, type WeightedRelation, type WildcardNode, type WorkerPoolConfig, WorkerPoolManager, type WorkingMemoryEntity, type WorkingMemoryOptions, addUniqueTags, all, allRelationsValidMetadata, applyPagination, asWarning, batchProcess, calculateIDF, calculateIDFFromTokenSets, calculateTF, calculateTFIDF, checkCancellation, chunkArray, cleanupAllCaches, clearAllSearchCaches, compress, compressFile, compressToBase64, cosineSimilarity, createDetailedProgressReporter, createEmbeddingService, createMetadata, createProgress, createProgressInfo, createProgressReporter, createStorage, createStorageFromPath, createThrottledProgress, createUncompressedMetadata, createVectorStore, custom, customSync, debounce, decompress, decompressFile, decompressFromBase64, defaultMemoryPath, email, ensureMemoryFilePath, entityExists, entityPassesFilters, entityToText, escapeCsvFormula, executeWithPhases, filterByCreatedDate, filterByEntityType, filterByImportance, filterByModifiedDate, filterByTags, filterParallel, findEntitiesByNames, findEntityByName, fnv1aHash, formatErrorResponse, formatRawResponse, formatTextResponse, formatToolResponse, formatZodErrors, generateSuggestions, getAllCacheStats, getCompressionRatio, getCurrentTimestamp, getEntityIndex, getEntityNameSet, getPaginationMeta, getPoolStats, getQuickHint, getWorkerPoolManager, globalMemoryMonitor, groupEntitiesByType, hasAllTags, hasBrotliExtension, hasConfidence, hasMatchingTag, isAgentEntity, isBidirectionalRelation, isCurrentlyValid, isEpisodicMemory, isPrefixPattern, isProceduralMemory, isSemanticMemory, isSessionEntity, isTemporalRelation, isValidISODate, isWeightedRelation, isWithinDateRange, isWithinImportanceRange, isWorkingMemory, isoDate, l2Normalize, levenshteinDistance, logger, mapParallel, matchesPhrase, matchesPrefix, max, maxItems, maxLength, min, minItems, minLength, normalizeTag, normalizeTags, oneOf, paginateArray, parallelFilter, parallelLimit, parallelMap, parseDateRange, pattern, processBatch, processBatchesWithProgress, processWithRetry, range, rateLimitedProcess, removeEntityByName, removeTags, required, sanitizeObject, searchCaches, shutdownParallelUtils, throttle, tokenize, touchEntity, typeOf, url, validateArrayWithSchema, validateEntity, validateFilePath, validateImportance, validatePagination, validateRelation, validateRelationMetadata, validateRelationsMetadata, validateSafe, validateTags, validateWithSchema, when, withRetry };