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5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
"""

MnemoCore Domain-Specific Exceptions

=====================================



This module defines a hierarchy of exceptions for consistent error handling

across the MnemoCore system.



Exception Hierarchy:

    MnemoCoreError (base)

    β”œβ”€β”€ RecoverableError (transient, retry possible)

    β”‚   β”œβ”€β”€ StorageConnectionError

    β”‚   β”œβ”€β”€ StorageTimeoutError

    β”‚   └── CircuitOpenError

    β”œβ”€β”€ IrrecoverableError (permanent, requires intervention)

    β”‚   β”œβ”€β”€ ConfigurationError

    β”‚   β”œβ”€β”€ DataCorruptionError

    β”‚   β”œβ”€β”€ ValidationError

    β”‚   β”œβ”€β”€ NotFoundError

    β”‚   └── UnsupportedOperationError

    └── Domain Errors (mixed recoverability)

        β”œβ”€β”€ StorageError

        β”œβ”€β”€ VectorError

        β”‚   β”œβ”€β”€ DimensionMismatchError

        β”‚   └── VectorOperationError

        └── MemoryOperationError



Usage Guidelines:

    - Return None for "not found" scenarios (expected case, not an error)

    - Raise exceptions for actual errors (connection failures, validation, corruption)

    - Always include context in error messages

    - Use error_code for API responses

"""

from typing import Optional, Any
from enum import Enum
import os


class ErrorCategory(Enum):
    """Categories for error classification."""
    STORAGE = "STORAGE"
    VECTOR = "VECTOR"
    CONFIG = "CONFIG"
    VALIDATION = "VALIDATION"
    MEMORY = "MEMORY"
    AGENT = "AGENT"
    PROVIDER = "PROVIDER"
    SYSTEM = "SYSTEM"


class MnemoCoreError(Exception):
    """

    Base exception for all MnemoCore errors.



    Attributes:

        message: Human-readable error message

        error_code: Machine-readable error code for API responses

        context: Additional context about the error

        recoverable: Whether the error is potentially recoverable

    """

    error_code: str = "MNEMO_CORE_ERROR"
    recoverable: bool = True
    category: ErrorCategory = ErrorCategory.SYSTEM

    def __init__(

        self,

        message: str,

        context: Optional[dict] = None,

        error_code: Optional[str] = None,

        recoverable: Optional[bool] = None

    ):
        super().__init__(message)
        self.message = message
        self.context = context or {}
        if error_code is not None:
            self.error_code = error_code
        if recoverable is not None:
            self.recoverable = recoverable

    def __str__(self) -> str:
        if self.context:
            return f"{self.message} | context={self.context}"
        return self.message

    def to_dict(self, include_traceback: bool = False) -> dict:
        """

        Convert exception to dictionary for JSON response.



        Args:

            include_traceback: Whether to include stack trace (only in DEBUG mode)

        """
        result = {
            "error": self.message,
            "code": self.error_code,
            "recoverable": self.recoverable,
        }

        if include_traceback:
            import traceback
            result["traceback"] = traceback.format_exc()

        if self.context:
            result["context"] = self.context

        return result


# =============================================================================
# Base Categories: Recoverable vs Irrecoverable
# =============================================================================

class RecoverableError(MnemoCoreError):
    """

    Base class for recoverable errors.



    These are transient errors that may succeed on retry:

    - Connection failures

    - Timeouts

    - Circuit breaker open

    - Rate limiting

    """
    recoverable = True


class IrrecoverableError(MnemoCoreError):
    """

    Base class for irrecoverable errors.



    These are permanent errors that require intervention:

    - Invalid configuration

    - Data corruption

    - Validation failures

    - Resource not found

    """
    recoverable = False


# =============================================================================
# Storage Errors
# =============================================================================

class StorageError(MnemoCoreError):
    """Base exception for storage-related errors."""
    error_code = "STORAGE_ERROR"
    category = ErrorCategory.STORAGE


class StorageConnectionError(RecoverableError, StorageError):
    """Raised when connection to storage backend fails."""
    error_code = "STORAGE_CONNECTION_ERROR"

    def __init__(self, backend: str, message: str = "Connection failed", context: Optional[dict] = None):
        ctx = {"backend": backend}
        if context:
            ctx.update(context)
        super().__init__(f"[{backend}] {message}", ctx)
        self.backend = backend


class StorageTimeoutError(RecoverableError, StorageError):
    """Raised when a storage operation times out."""
    error_code = "STORAGE_TIMEOUT_ERROR"

    def __init__(self, backend: str, operation: str, timeout_ms: Optional[int] = None, context: Optional[dict] = None):
        msg = f"[{backend}] Operation '{operation}' timed out"
        ctx = {"backend": backend, "operation": operation}
        if timeout_ms is not None:
            ctx["timeout_ms"] = timeout_ms
        if context:
            ctx.update(context)
        super().__init__(msg, ctx)
        self.backend = backend
        self.operation = operation


class DataCorruptionError(IrrecoverableError, StorageError):
    """Raised when stored data is corrupt or cannot be deserialized."""
    error_code = "DATA_CORRUPTION_ERROR"

    def __init__(self, resource_id: str, reason: str = "Data corruption detected", context: Optional[dict] = None):
        ctx = {"resource_id": resource_id}
        if context:
            ctx.update(context)
        super().__init__(f"{reason} for resource '{resource_id}'", ctx)
        self.resource_id = resource_id


# =============================================================================
# Vector Errors
# =============================================================================

class VectorError(MnemoCoreError):
    """Base exception for vector/hyperdimensional operations."""
    error_code = "VECTOR_ERROR"
    category = ErrorCategory.VECTOR


class DimensionMismatchError(IrrecoverableError, VectorError):
    """Raised when vector dimensions do not match."""
    error_code = "DIMENSION_MISMATCH_ERROR"

    def __init__(self, expected: int, actual: int, operation: str = "operation", context: Optional[dict] = None):
        ctx = {"expected": expected, "actual": actual, "operation": operation}
        if context:
            ctx.update(context)
        super().__init__(
            f"Dimension mismatch in {operation}: expected {expected}, got {actual}",
            ctx
        )
        self.expected = expected
        self.actual = actual
        self.operation = operation


class VectorOperationError(IrrecoverableError, VectorError):
    """Raised when a vector operation fails."""
    error_code = "VECTOR_OPERATION_ERROR"

    def __init__(self, operation: str, reason: str, context: Optional[dict] = None):
        ctx = {"operation": operation}
        if context:
            ctx.update(context)
        super().__init__(f"Vector operation '{operation}' failed: {reason}", ctx)
        self.operation = operation


# =============================================================================
# Configuration Errors
# =============================================================================

class ConfigurationError(IrrecoverableError):
    """Raised when configuration is invalid or missing."""
    error_code = "CONFIGURATION_ERROR"
    category = ErrorCategory.CONFIG

    def __init__(self, config_key: str, reason: str, context: Optional[dict] = None):
        ctx = {"config_key": config_key}
        if context:
            ctx.update(context)
        super().__init__(f"Configuration error for '{config_key}': {reason}", ctx)
        self.config_key = config_key


# =============================================================================
# Circuit Breaker Errors
# =============================================================================

class CircuitOpenError(RecoverableError):
    """Raised when a circuit breaker is open and blocking requests."""
    error_code = "CIRCUIT_OPEN_ERROR"
    category = ErrorCategory.SYSTEM

    def __init__(self, breaker_name: str, failures: int, context: Optional[dict] = None):
        ctx = {"breaker_name": breaker_name, "failures": failures}
        if context:
            ctx.update(context)
        super().__init__(
            f"Circuit breaker '{breaker_name}' is OPEN after {failures} failures",
            ctx
        )
        self.breaker_name = breaker_name
        self.failures = failures


# =============================================================================
# Memory Operation Errors
# =============================================================================

class MemoryOperationError(MnemoCoreError):
    """Raised when a memory operation (store, retrieve, delete) fails."""
    error_code = "MEMORY_OPERATION_ERROR"
    category = ErrorCategory.MEMORY

    def __init__(self, operation: str, node_id: Optional[str], reason: str, context: Optional[dict] = None):
        ctx = {"operation": operation}
        if node_id:
            ctx["node_id"] = node_id
        if context:
            ctx.update(context)
        super().__init__(f"Memory {operation} failed for '{node_id}': {reason}", ctx)
        self.operation = operation
        self.node_id = node_id


# =============================================================================
# Validation Errors
# =============================================================================

class ValidationError(IrrecoverableError):
    """Raised when input validation fails."""
    error_code = "VALIDATION_ERROR"
    category = ErrorCategory.VALIDATION

    def __init__(self, field: str, reason: str, value: Any = None, context: Optional[dict] = None):
        ctx = {"field": field}
        if value is not None:
            # Truncate large values
            value_str = str(value)
            if len(value_str) > 100:
                value_str = value_str[:100] + "..."
            ctx["value"] = value_str
        if context:
            ctx.update(context)
        super().__init__(f"Validation error for '{field}': {reason}", ctx)
        self.field = field
        self.reason = reason


class MetadataValidationError(ValidationError):
    """Raised when metadata validation fails."""
    error_code = "METADATA_VALIDATION_ERROR"


class AttributeValidationError(ValidationError):
    """Raised when attribute validation fails."""
    error_code = "ATTRIBUTE_VALIDATION_ERROR"


# =============================================================================
# Not Found Errors
# =============================================================================

class NotFoundError(IrrecoverableError):
    """Raised when a requested resource is not found."""
    error_code = "NOT_FOUND_ERROR"
    category = ErrorCategory.SYSTEM

    def __init__(self, resource_type: str, resource_id: str, context: Optional[dict] = None):
        ctx = {"resource_type": resource_type, "resource_id": resource_id}
        if context:
            ctx.update(context)
        super().__init__(f"{resource_type} '{resource_id}' not found", ctx)
        self.resource_type = resource_type
        self.resource_id = resource_id


class AgentNotFoundError(NotFoundError):
    """Raised when an agent is not found."""
    error_code = "AGENT_NOT_FOUND_ERROR"
    category = ErrorCategory.AGENT

    def __init__(self, agent_id: str, context: Optional[dict] = None):
        super().__init__("Agent", agent_id, context)
        self.agent_id = agent_id


class MemoryNotFoundError(NotFoundError):
    """Raised when a memory is not found."""
    error_code = "MEMORY_NOT_FOUND_ERROR"
    category = ErrorCategory.MEMORY

    def __init__(self, memory_id: str, context: Optional[dict] = None):
        super().__init__("Memory", memory_id, context)
        self.memory_id = memory_id


# =============================================================================
# Provider Errors
# =============================================================================

class ProviderError(MnemoCoreError):
    """Base exception for provider-related errors."""
    error_code = "PROVIDER_ERROR"
    category = ErrorCategory.PROVIDER


class UnsupportedProviderError(IrrecoverableError, ProviderError):
    """Raised when an unsupported provider is requested."""
    error_code = "UNSUPPORTED_PROVIDER_ERROR"

    def __init__(self, provider: str, supported_providers: Optional[list] = None, context: Optional[dict] = None):
        ctx = {"provider": provider}
        if supported_providers:
            ctx["supported_providers"] = supported_providers
        if context:
            ctx.update(context)
        msg = f"Unsupported provider: {provider}"
        if supported_providers:
            msg += f". Supported: {', '.join(supported_providers)}"
        super().__init__(msg, ctx)
        self.provider = provider


class UnsupportedTransportError(IrrecoverableError, ValueError):
    """Raised when an unsupported transport is requested."""
    error_code = "UNSUPPORTED_TRANSPORT_ERROR"
    category = ErrorCategory.CONFIG

    def __init__(self, transport: str, supported_transports: Optional[list] = None, context: Optional[dict] = None):
        ctx = {"transport": transport}
        if supported_transports:
            ctx["supported_transports"] = supported_transports
        if context:
            ctx.update(context)
        msg = f"Unsupported transport: {transport}"
        if supported_transports:
            msg += f". Supported: {', '.join(supported_transports)}"
        super().__init__(msg, ctx)
        self.transport = transport


class DependencyMissingError(IrrecoverableError):
    """Raised when a required dependency is missing."""
    error_code = "DEPENDENCY_MISSING_ERROR"
    category = ErrorCategory.SYSTEM

    def __init__(self, dependency: str, message: str = "", context: Optional[dict] = None):
        ctx = {"dependency": dependency}
        if context:
            ctx.update(context)
        msg = f"Missing dependency: {dependency}"
        if message:
            msg += f". {message}"
        super().__init__(msg, ctx)
        self.dependency = dependency


# =============================================================================
# Utility Functions
# =============================================================================

def wrap_storage_exception(backend: str, operation: str, exc: Exception) -> StorageError:
    """

    Wrap a generic exception into an appropriate StorageError.



    Args:

        backend: Name of the storage backend (e.g., 'redis', 'qdrant')

        operation: Name of the operation that failed

        exc: The original exception



    Returns:

        An appropriate StorageError subclass

    """
    exc_name = type(exc).__name__
    exc_msg = str(exc)

    # Timeout detection
    if 'timeout' in exc_msg.lower() or 'Timeout' in exc_name:
        return StorageTimeoutError(backend, operation)

    # Connection error detection
    if any(x in exc_name.lower() for x in ['connection', 'connect', 'network']):
        return StorageConnectionError(backend, exc_msg)

    # Default to generic storage error
    return StorageError(
        f"[{backend}] {operation} failed: {exc_msg}",
        {"backend": backend, "operation": operation, "original_exception": exc_name}
    )


def is_debug_mode() -> bool:
    """Check if debug mode is enabled via environment variable."""
    return os.environ.get("MNEMO_DEBUG", "").lower() in ("true", "1", "yes")


# =============================================================================
# Convenience Exports
# =============================================================================

__all__ = [
    # Base
    "MnemoCoreError",
    "RecoverableError",
    "IrrecoverableError",
    "ErrorCategory",
    # Storage
    "StorageError",
    "StorageConnectionError",
    "StorageTimeoutError",
    "DataCorruptionError",
    # Vector
    "VectorError",
    "DimensionMismatchError",
    "VectorOperationError",
    # Config
    "ConfigurationError",
    # Circuit Breaker
    "CircuitOpenError",
    # Memory
    "MemoryOperationError",
    # Validation
    "ValidationError",
    "MetadataValidationError",
    "AttributeValidationError",
    # Not Found
    "NotFoundError",
    "AgentNotFoundError",
    "MemoryNotFoundError",
    # Provider
    "ProviderError",
    "UnsupportedProviderError",
    "UnsupportedTransportError",
    "DependencyMissingError",
    # Utilities
    "wrap_storage_exception",
    "is_debug_mode",
]