l9-graphite-memory 2.3.1__py3-none-any.whl

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.
Files changed (136) hide show
  1. l9_graphite_memory/__init__.py +37 -0
  2. l9_graphite_memory/__main__.py +15 -0
  3. l9_graphite_memory/active/__init__.py +98 -0
  4. l9_graphite_memory/active/client.py +448 -0
  5. l9_graphite_memory/active/credentials.py +253 -0
  6. l9_graphite_memory/active/deployment.py +163 -0
  7. l9_graphite_memory/active/errors.py +81 -0
  8. l9_graphite_memory/active/inmemory.py +406 -0
  9. l9_graphite_memory/active/lifecycle.py +120 -0
  10. l9_graphite_memory/active/models.py +408 -0
  11. l9_graphite_memory/active/null_adapters.py +118 -0
  12. l9_graphite_memory/active/ports.py +170 -0
  13. l9_graphite_memory/active/redis_adapters.py +510 -0
  14. l9_graphite_memory/adapters/__init__.py +42 -0
  15. l9_graphite_memory/adapters/factory.py +81 -0
  16. l9_graphite_memory/adapters/graphiti_projection.py +267 -0
  17. l9_graphite_memory/adapters/in_memory_store.py +548 -0
  18. l9_graphite_memory/adapters/null_projection.py +82 -0
  19. l9_graphite_memory/adapters/postgres_store.py +1359 -0
  20. l9_graphite_memory/adapters/sqlite_store.py +1278 -0
  21. l9_graphite_memory/admission/__init__.py +22 -0
  22. l9_graphite_memory/admission/engine.py +126 -0
  23. l9_graphite_memory/admission/normalization.py +110 -0
  24. l9_graphite_memory/admission/policy.py +32 -0
  25. l9_graphite_memory/authz/__init__.py +16 -0
  26. l9_graphite_memory/authz/authenticator.py +84 -0
  27. l9_graphite_memory/authz/policy.py +87 -0
  28. l9_graphite_memory/circuit_breaker.py +92 -0
  29. l9_graphite_memory/cli.py +1283 -0
  30. l9_graphite_memory/client_config/__init__.py +55 -0
  31. l9_graphite_memory/client_config/contracts.py +141 -0
  32. l9_graphite_memory/client_config/cursor.py +422 -0
  33. l9_graphite_memory/client_config/mcp_probe.py +358 -0
  34. l9_graphite_memory/config/__init__.py +16 -0
  35. l9_graphite_memory/config/loader.py +183 -0
  36. l9_graphite_memory/config/models.py +139 -0
  37. l9_graphite_memory/contracts/__init__.py +204 -0
  38. l9_graphite_memory/contracts/capabilities.py +179 -0
  39. l9_graphite_memory/contracts/enums.py +139 -0
  40. l9_graphite_memory/contracts/evidence.py +258 -0
  41. l9_graphite_memory/contracts/generated_data.py +269 -0
  42. l9_graphite_memory/contracts/identity.py +55 -0
  43. l9_graphite_memory/contracts/maintenance.py +118 -0
  44. l9_graphite_memory/contracts/memory.py +104 -0
  45. l9_graphite_memory/contracts/privacy.py +64 -0
  46. l9_graphite_memory/contracts/profiles.py +96 -0
  47. l9_graphite_memory/contracts/projection.py +122 -0
  48. l9_graphite_memory/contracts/receipts.py +383 -0
  49. l9_graphite_memory/contracts/requests.py +184 -0
  50. l9_graphite_memory/contracts/review.py +101 -0
  51. l9_graphite_memory/contracts/temporal.py +91 -0
  52. l9_graphite_memory/curation/__init__.py +35 -0
  53. l9_graphite_memory/curation/procedural.py +173 -0
  54. l9_graphite_memory/curation/promotion.py +59 -0
  55. l9_graphite_memory/curation/quarantine.py +265 -0
  56. l9_graphite_memory/curation/retention.py +109 -0
  57. l9_graphite_memory/episode_contract.py +68 -0
  58. l9_graphite_memory/errors.py +102 -0
  59. l9_graphite_memory/extraction/__init__.py +30 -0
  60. l9_graphite_memory/extraction/atomic.py +218 -0
  61. l9_graphite_memory/extraction/distiller.py +141 -0
  62. l9_graphite_memory/graphiti_gate_lib.py +67 -0
  63. l9_graphite_memory/graphiti_memory_client.py +21 -0
  64. l9_graphite_memory/group_resolver.py +155 -0
  65. l9_graphite_memory/ingestion/__init__.py +50 -0
  66. l9_graphite_memory/ingestion/document.py +140 -0
  67. l9_graphite_memory/ingestion/profiles.py +187 -0
  68. l9_graphite_memory/ingestion/publication_identity.py +460 -0
  69. l9_graphite_memory/ingestion/repository.py +85 -0
  70. l9_graphite_memory/ingestion/topology_publication.py +623 -0
  71. l9_graphite_memory/integrations/__init__.py +47 -0
  72. l9_graphite_memory/integrations/constellation.py +134 -0
  73. l9_graphite_memory/integrations/gate_client.py +251 -0
  74. l9_graphite_memory/integrations/session.py +126 -0
  75. l9_graphite_memory/integrations/transport_packet.py +201 -0
  76. l9_graphite_memory/integrity/__init__.py +15 -0
  77. l9_graphite_memory/integrity/checkpoint.py +98 -0
  78. l9_graphite_memory/lineage/__init__.py +15 -0
  79. l9_graphite_memory/lineage/replay.py +123 -0
  80. l9_graphite_memory/maintenance/__init__.py +21 -0
  81. l9_graphite_memory/maintenance/planner.py +562 -0
  82. l9_graphite_memory/maintenance/service.py +542 -0
  83. l9_graphite_memory/mcp_tools.py +760 -0
  84. l9_graphite_memory/memory_guard.py +248 -0
  85. l9_graphite_memory/migration/__init__.py +35 -0
  86. l9_graphite_memory/migration/backend_transition.py +173 -0
  87. l9_graphite_memory/migration/legacy_write_queue.py +209 -0
  88. l9_graphite_memory/observability/__init__.py +15 -0
  89. l9_graphite_memory/observability/logging.py +81 -0
  90. l9_graphite_memory/ports/__init__.py +49 -0
  91. l9_graphite_memory/ports/clock.py +25 -0
  92. l9_graphite_memory/ports/constellation.py +66 -0
  93. l9_graphite_memory/ports/phase_lock.py +73 -0
  94. l9_graphite_memory/ports/projection.py +92 -0
  95. l9_graphite_memory/ports/record_store.py +285 -0
  96. l9_graphite_memory/ports/review.py +34 -0
  97. l9_graphite_memory/ports/service_capability.py +74 -0
  98. l9_graphite_memory/ports/synthesis.py +34 -0
  99. l9_graphite_memory/projections/__init__.py +43 -0
  100. l9_graphite_memory/projections/compiler.py +117 -0
  101. l9_graphite_memory/projections/contracts.py +292 -0
  102. l9_graphite_memory/projections/manifest.py +55 -0
  103. l9_graphite_memory/projections/render.py +110 -0
  104. l9_graphite_memory/prune.py +42 -0
  105. l9_graphite_memory/rate_limiter.py +79 -0
  106. l9_graphite_memory/resources/active_memory_redis_capabilities.yaml +34 -0
  107. l9_graphite_memory/resources/defaults.yaml +24 -0
  108. l9_graphite_memory/resources/group_registry.yaml +37 -0
  109. l9_graphite_memory/resources/memory_contract.yaml +48 -0
  110. l9_graphite_memory/resources/projections/schema.json +408 -0
  111. l9_graphite_memory/retrieval/__init__.py +24 -0
  112. l9_graphite_memory/retrieval/budget.py +100 -0
  113. l9_graphite_memory/retrieval/planner.py +265 -0
  114. l9_graphite_memory/retrieval/query_classifier.py +89 -0
  115. l9_graphite_memory/retrieval/ranking.py +161 -0
  116. l9_graphite_memory/runtime.py +116 -0
  117. l9_graphite_memory/schema/__init__.py +17 -0
  118. l9_graphite_memory/schema/registry.py +88 -0
  119. l9_graphite_memory/schema/upcasters.py +184 -0
  120. l9_graphite_memory/sdk.py +88 -0
  121. l9_graphite_memory/secrets.py +189 -0
  122. l9_graphite_memory/server.py +285 -0
  123. l9_graphite_memory/services/__init__.py +17 -0
  124. l9_graphite_memory/services/generated_data.py +350 -0
  125. l9_graphite_memory/services/memory_service.py +1346 -0
  126. l9_graphite_memory/services/outbox_worker.py +356 -0
  127. l9_graphite_memory/transport.py +343 -0
  128. l9_graphite_memory/trust_boundary.py +78 -0
  129. l9_graphite_memory/version.py +32 -0
  130. l9_graphite_memory/zep_transport.py +225 -0
  131. l9_graphite_memory-2.3.1.dist-info/METADATA +213 -0
  132. l9_graphite_memory-2.3.1.dist-info/RECORD +136 -0
  133. l9_graphite_memory-2.3.1.dist-info/WHEEL +5 -0
  134. l9_graphite_memory-2.3.1.dist-info/entry_points.txt +4 -0
  135. l9_graphite_memory-2.3.1.dist-info/licenses/LICENSE +104 -0
  136. l9_graphite_memory-2.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,253 @@
1
+ # L9_META
2
+ # l9_schema: 1
3
+ # repo: Quantum-L9/l9-graphiti-memory
4
+ # path: src/l9_graphite_memory/active/credentials.py
5
+ # layer: package
6
+ # owner: memory-control-plane
7
+ # status: active
8
+ # version: 2.2.0
9
+ # updated: 2026-07-22
10
+
11
+ """Secret-file and structured credential resolution for Redis backends.
12
+
13
+ Implements ADR-066. Supports, in strict precedence order:
14
+
15
+ 1. `url_file` — a mounted secret file containing a full
16
+ Redis connection URL.
17
+ 2. host/port + password_file — structured connection fields with a
18
+ mounted password secret file.
19
+ 3. `secret_provider_reference` — an opaque reference resolved by a
20
+ consumer-supplied secret provider
21
+ callback (e.g. Docker secrets, Vault,
22
+ a cloud secret manager). This module
23
+ does not implement any specific provider;
24
+ it only defines the resolution contract.
25
+ 4. `url_env` — an environment variable containing a
26
+ full Redis connection URL. Lowest
27
+ precedence; intended for local
28
+ development only.
29
+
30
+ Exactly one credential source may be configured. Configuring more than
31
+ one non-null source is a hard configuration error (ambiguous
32
+ precedence is never silently resolved).
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import os
38
+ import stat
39
+ from collections.abc import Callable
40
+ from dataclasses import dataclass
41
+ from pathlib import Path
42
+ from urllib.parse import urlsplit, urlunsplit
43
+
44
+ MAX_SECRET_FILE_BYTES = 16384
45
+
46
+
47
+ class CredentialResolutionError(ValueError):
48
+ """Raised when a Redis credential cannot be resolved or is invalid."""
49
+
50
+
51
+ class AmbiguousCredentialSourceError(CredentialResolutionError):
52
+ """Raised when more than one credential source is configured."""
53
+
54
+
55
+ @dataclass(frozen=True, slots=True)
56
+ class RedisCredentialSettings:
57
+ """Declarative configuration for exactly one credential source.
58
+
59
+ Attributes:
60
+ username: Optional Redis ACL username (not a secret by itself).
61
+ password_file: Path to a mounted file containing the password.
62
+ url_file: Path to a mounted file containing a full Redis URL.
63
+ url_env: Name of an environment variable containing a full
64
+ Redis URL. Lowest-precedence, development-oriented source.
65
+ secret_provider_reference: Opaque reference string resolved via
66
+ a caller-supplied `secret_provider` callback.
67
+ host: Redis host, used only with `password_file`.
68
+ port: Redis port, used only with `password_file`.
69
+ database: Redis logical database index, used only with
70
+ `password_file`.
71
+ tls: Whether to require TLS, used only with `password_file`.
72
+ """
73
+
74
+ username: str | None = None
75
+ password_file: Path | None = None
76
+ url_file: Path | None = None
77
+ url_env: str | None = None
78
+ secret_provider_reference: str | None = None
79
+ host: str | None = None
80
+ port: int = 6379
81
+ database: int = 0
82
+ tls: bool = True
83
+
84
+
85
+ @dataclass(frozen=True, slots=True)
86
+ class ResolvedRedisCredential:
87
+ """Fully resolved, ready-to-use Redis connection parameters.
88
+
89
+ `redis_url` is the sole connection string handed to the Redis
90
+ client constructor. It is never logged; callers MUST redact it in
91
+ any diagnostic output (see `redacted_summary()`).
92
+ """
93
+
94
+ redis_url: str
95
+ credential_source: str
96
+
97
+ def redacted_summary(self) -> dict[str, object]:
98
+ """Return a safe-to-log summary with no credential material."""
99
+ parts = urlsplit(self.redis_url)
100
+ return {
101
+ "credential_source": self.credential_source,
102
+ "scheme": parts.scheme,
103
+ "host": parts.hostname,
104
+ "port": parts.port,
105
+ "username_configured": bool(parts.username),
106
+ }
107
+
108
+
109
+ def _read_secret_file(path: Path, *, field_name: str) -> str:
110
+ if not path.is_absolute():
111
+ raise CredentialResolutionError(f"{field_name} must be an absolute path: {path}")
112
+ if path.is_symlink():
113
+ raise CredentialResolutionError(f"{field_name} must not be a symlink: {path}")
114
+ if not path.exists():
115
+ raise CredentialResolutionError(f"{field_name} does not exist: {path}")
116
+ file_stat = path.stat()
117
+ if not stat.S_ISREG(file_stat.st_mode):
118
+ raise CredentialResolutionError(f"{field_name} must be a regular file: {path}")
119
+ if file_stat.st_size > MAX_SECRET_FILE_BYTES:
120
+ raise CredentialResolutionError(
121
+ f"{field_name} exceeds maximum size of {MAX_SECRET_FILE_BYTES} bytes: {path}"
122
+ )
123
+ raw = path.read_bytes()
124
+ if b"\x00" in raw:
125
+ raise CredentialResolutionError(f"{field_name} must not contain NUL bytes: {path}")
126
+ text = raw.decode("utf-8")
127
+ text = text.removesuffix("\n")
128
+ if not text:
129
+ raise CredentialResolutionError(f"{field_name} must not be empty: {path}")
130
+ return text
131
+
132
+
133
+ def _resolve_url_file(settings: RedisCredentialSettings) -> ResolvedRedisCredential:
134
+ assert settings.url_file is not None
135
+ url = _read_secret_file(settings.url_file, field_name="url_file")
136
+ _validate_redis_url(url)
137
+ return ResolvedRedisCredential(redis_url=url, credential_source="url_file")
138
+
139
+
140
+ def _resolve_password_file(settings: RedisCredentialSettings) -> ResolvedRedisCredential:
141
+ assert settings.password_file is not None
142
+ if not settings.host:
143
+ raise CredentialResolutionError("host is required when password_file is configured")
144
+ password = _read_secret_file(settings.password_file, field_name="password_file")
145
+ scheme = "rediss" if settings.tls else "redis"
146
+ userinfo = f"{settings.username}:{password}" if settings.username else f":{password}"
147
+ netloc = f"{userinfo}@{settings.host}:{settings.port}"
148
+ url = urlunsplit((scheme, netloc, f"/{settings.database}", "", ""))
149
+ return ResolvedRedisCredential(redis_url=url, credential_source="password_file")
150
+
151
+
152
+ def _resolve_secret_provider_reference(
153
+ settings: RedisCredentialSettings, secret_provider: Callable[[str], str] | None
154
+ ) -> ResolvedRedisCredential:
155
+ assert settings.secret_provider_reference is not None
156
+ if secret_provider is None:
157
+ raise CredentialResolutionError(
158
+ "secret_provider_reference is configured but no secret_provider callback was supplied"
159
+ )
160
+ url = secret_provider(settings.secret_provider_reference)
161
+ if not url:
162
+ raise CredentialResolutionError("secret_provider callback returned an empty value")
163
+ _validate_redis_url(url)
164
+ return ResolvedRedisCredential(redis_url=url, credential_source="secret_provider_reference")
165
+
166
+
167
+ def _resolve_url_env(
168
+ settings: RedisCredentialSettings, environ: dict[str, str]
169
+ ) -> ResolvedRedisCredential:
170
+ assert settings.url_env is not None
171
+ env_url = environ.get(settings.url_env)
172
+ if not env_url:
173
+ raise CredentialResolutionError(
174
+ f"environment variable {settings.url_env!r} is not set or empty"
175
+ )
176
+ _validate_redis_url(env_url)
177
+ return ResolvedRedisCredential(redis_url=env_url, credential_source="url_env")
178
+
179
+
180
+ def _configured_sources(settings: RedisCredentialSettings) -> list[str]:
181
+ return [
182
+ name
183
+ for name, value in (
184
+ ("url_file", settings.url_file),
185
+ ("password_file", settings.password_file),
186
+ ("secret_provider_reference", settings.secret_provider_reference),
187
+ ("url_env", settings.url_env),
188
+ )
189
+ if value
190
+ ]
191
+
192
+
193
+ def resolve_redis_credential(
194
+ settings: RedisCredentialSettings,
195
+ *,
196
+ secret_provider: Callable[[str], str] | None = None,
197
+ environ: dict[str, str] | None = None,
198
+ ) -> ResolvedRedisCredential:
199
+ """Resolve exactly one configured credential source into a Redis URL.
200
+
201
+ Args:
202
+ settings: The declarative credential configuration.
203
+ secret_provider: Required only if `secret_provider_reference` is
204
+ set. Called with the reference string and must return the
205
+ resolved secret value (a full Redis URL or password,
206
+ depending on the provider's contract — this function treats
207
+ the returned value as a full Redis URL).
208
+ environ: Optional environment mapping override, primarily for
209
+ testing. Defaults to `os.environ`.
210
+
211
+ Returns:
212
+ A `ResolvedRedisCredential` with a ready-to-use `redis_url`.
213
+
214
+ Raises:
215
+ AmbiguousCredentialSourceError: if more than one source is
216
+ configured.
217
+ CredentialResolutionError: if the configured source is missing,
218
+ unreadable, malformed, or if no source is configured.
219
+ """
220
+ resolved_environ = environ if environ is not None else dict(os.environ)
221
+ configured_sources = _configured_sources(settings)
222
+
223
+ if len(configured_sources) == 0:
224
+ raise CredentialResolutionError(
225
+ "no Redis credential source configured; exactly one of "
226
+ "url_file, password_file (with host), secret_provider_reference, "
227
+ "or url_env is required"
228
+ )
229
+ if len(configured_sources) > 1:
230
+ raise AmbiguousCredentialSourceError(
231
+ f"multiple Redis credential sources configured: {configured_sources}; "
232
+ "exactly one must be set"
233
+ )
234
+
235
+ source = configured_sources[0]
236
+ if source == "url_file":
237
+ return _resolve_url_file(settings)
238
+ if source == "password_file":
239
+ return _resolve_password_file(settings)
240
+ if source == "secret_provider_reference":
241
+ return _resolve_secret_provider_reference(settings, secret_provider)
242
+ assert source == "url_env"
243
+ return _resolve_url_env(settings, resolved_environ)
244
+
245
+
246
+ def _validate_redis_url(url: str) -> None:
247
+ parts = urlsplit(url)
248
+ if parts.scheme not in ("redis", "rediss"):
249
+ raise CredentialResolutionError(
250
+ f"Redis URL must use redis:// or rediss:// scheme, got: {parts.scheme!r}"
251
+ )
252
+ if not parts.hostname:
253
+ raise CredentialResolutionError("Redis URL must include a hostname")
@@ -0,0 +1,163 @@
1
+ # L9_META
2
+ # l9_schema: 1
3
+ # repo: Quantum-L9/l9-graphiti-memory
4
+ # path: src/l9_graphite_memory/active/deployment.py
5
+ # layer: package
6
+ # owner: memory-control-plane
7
+ # status: active
8
+ # version: 2.2.0
9
+ # updated: 2026-07-22
10
+
11
+ """Deployment identity contracts for the active-memory subsystem.
12
+
13
+ Implements ADR-065. A deployment identity binds one configured
14
+ active-memory runtime (one backend, one set of Redis credentials) to a
15
+ stable logical identifier and authorization/provenance boundary
16
+ (`trust_domain`). Deployment identity is immutable for the lifetime of a
17
+ running process and is injected server-side; it MUST NOT be accepted
18
+ from request payloads.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ import re
25
+ from dataclasses import dataclass
26
+ from enum import Enum
27
+
28
+ _IDENTIFIER_PATTERN = re.compile(r"^[a-z0-9._:-]{1,128}$")
29
+ _HASH_ALGORITHM_VERSION = "v1"
30
+
31
+
32
+ class DeploymentIdentityError(ValueError):
33
+ """Raised when a deployment identifier or environment is invalid."""
34
+
35
+
36
+ class DeploymentEnvironment(str, Enum):
37
+ """Deployment stage used for isolation, diagnostics, and policy.
38
+
39
+ This enumeration is domain-agnostic. Consumer applications map their
40
+ own environment names (e.g. a self-hosted VPS production stage) onto
41
+ one of these values; this package does not encode any consumer's
42
+ infrastructure naming.
43
+ """
44
+
45
+ DEVELOPMENT = "development"
46
+ TEST = "test"
47
+ STAGING = "staging"
48
+ PRODUCTION = "production"
49
+
50
+
51
+ def validate_identifier(value: str, *, field_name: str) -> str:
52
+ """Validate a deployment_id, trust_domain, or similar identifier.
53
+
54
+ Rules (per ADR-065):
55
+ - length 1-128 characters
56
+ - lowercase ascii letters, digits, '.', '_', '-', ':' only
57
+ - no whitespace, wildcards, path separators, or control characters
58
+
59
+ Raises:
60
+ DeploymentIdentityError: if the value violates the above rules.
61
+ """
62
+ if not isinstance(value, str) or not value:
63
+ raise DeploymentIdentityError(f"{field_name} must be a non-empty string")
64
+ if not _IDENTIFIER_PATTERN.match(value):
65
+ raise DeploymentIdentityError(
66
+ f"{field_name}={value!r} is invalid; must match "
67
+ f"{_IDENTIFIER_PATTERN.pattern} (1-128 chars, lowercase "
68
+ "alnum plus '.', '_', '-', ':')"
69
+ )
70
+ if any(ch.isspace() for ch in value):
71
+ raise DeploymentIdentityError(f"{field_name} must not contain whitespace")
72
+ if "*" in value or "?" in value or "[" in value or "]" in value:
73
+ raise DeploymentIdentityError(
74
+ f"{field_name} must not contain Redis glob wildcard characters"
75
+ )
76
+ if "/" in value or "\\" in value:
77
+ raise DeploymentIdentityError(f"{field_name} must not contain path separators")
78
+ return value
79
+
80
+
81
+ _PRODUCTION_PLACEHOLDER_VALUES = frozenset(
82
+ {
83
+ "example",
84
+ "example-production",
85
+ "changeme",
86
+ "change-me",
87
+ "placeholder",
88
+ "test",
89
+ "unset",
90
+ "unknown",
91
+ "",
92
+ }
93
+ )
94
+
95
+
96
+ @dataclass(frozen=True, slots=True)
97
+ class ActiveDeployment:
98
+ """Immutable identity for one configured active-memory runtime.
99
+
100
+ Attributes:
101
+ deployment_id: Stable logical identifier for this runtime instance
102
+ of the active-memory subsystem (e.g. one Redis backend, one
103
+ set of credentials). Must be unique across independently
104
+ operated active-memory backends that a fleet of external
105
+ consumers might use.
106
+ trust_domain: Authorization and provenance boundary containing
107
+ this deployment. Used to scope cross-deployment isolation
108
+ checks and to tag promoted Graphiti records with their
109
+ originating trust boundary.
110
+ environment: Deployment stage (development/test/staging/
111
+ production). Used for policy decisions such as rejecting
112
+ placeholder identifiers in production.
113
+
114
+ Raises:
115
+ DeploymentIdentityError: via `validate()` if any field is invalid,
116
+ or if a production environment uses a recognized placeholder
117
+ value for deployment_id or trust_domain.
118
+ """
119
+
120
+ deployment_id: str
121
+ trust_domain: str
122
+ environment: DeploymentEnvironment
123
+
124
+ def __post_init__(self) -> None:
125
+ validate_identifier(self.deployment_id, field_name="deployment_id")
126
+ validate_identifier(self.trust_domain, field_name="trust_domain")
127
+ if not isinstance(self.environment, DeploymentEnvironment):
128
+ raise DeploymentIdentityError(
129
+ f"environment must be a DeploymentEnvironment, got {type(self.environment)!r}"
130
+ )
131
+ if self.environment is DeploymentEnvironment.PRODUCTION:
132
+ lowered_id = self.deployment_id.lower()
133
+ lowered_domain = self.trust_domain.lower()
134
+ if (
135
+ lowered_id in _PRODUCTION_PLACEHOLDER_VALUES
136
+ or lowered_domain in _PRODUCTION_PLACEHOLDER_VALUES
137
+ ):
138
+ raise DeploymentIdentityError(
139
+ "production environment must not use placeholder "
140
+ f"deployment_id/trust_domain values: "
141
+ f"deployment_id={self.deployment_id!r}, "
142
+ f"trust_domain={self.trust_domain!r}"
143
+ )
144
+
145
+ def canonical_string(self) -> str:
146
+ """Canonical representation used as input to hash derivation."""
147
+ return f"{_HASH_ALGORITHM_VERSION}|{self.trust_domain}|{self.deployment_id}"
148
+
149
+
150
+ def derive_deployment_hash(deployment: ActiveDeployment) -> str:
151
+ """Derive the deterministic, versioned key/channel hash for a deployment.
152
+
153
+ Uses SHA-256 over a canonical `{version}|{trust_domain}|{deployment_id}`
154
+ string and returns the first 16 hex characters (64 bits) as the
155
+ namespace component embedded in Redis keys and Pub/Sub channels.
156
+
157
+ This function is deterministic and MUST remain stable for a given
158
+ deployment identity within algorithm version "v1". Changing the
159
+ algorithm requires bumping `_HASH_ALGORITHM_VERSION` and treating it
160
+ as a breaking key-space migration (see ADR-065, ADR-068).
161
+ """
162
+ digest = hashlib.sha256(deployment.canonical_string().encode("utf-8")).hexdigest()
163
+ return digest[:16]
@@ -0,0 +1,81 @@
1
+ # L9_META
2
+ # l9_schema: 1
3
+ # repo: Quantum-L9/l9-graphiti-memory
4
+ # path: src/l9_graphite_memory/active/errors.py
5
+ # layer: package
6
+ # owner: memory-control-plane
7
+ # status: active
8
+ # version: 2.2.0
9
+ # updated: 2026-07-22
10
+
11
+ """Typed error hierarchy for the active-memory subsystem.
12
+
13
+ All active-memory failures MUST raise one of these typed errors so that
14
+ external consumers (via the stable SDK) can distinguish transient
15
+ backend unavailability from contract violations, without needing to
16
+ inspect Redis-specific exception types.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+
22
+ class ActiveMemoryError(Exception):
23
+ """Base class for all active-memory subsystem errors."""
24
+
25
+
26
+ class ActiveMemoryUnavailableError(ActiveMemoryError):
27
+ """Raised when the configured active-memory backend cannot be reached.
28
+
29
+ This error MUST NOT be raised for canonical Graphiti memory
30
+ operations; it is scoped strictly to the active (Redis-backed)
31
+ layer. Per the failure/degradation policy, canonical memory
32
+ operations must remain unaffected when active memory is optional.
33
+ """
34
+
35
+
36
+ class ContextVersionConflictError(ActiveMemoryError):
37
+ """Raised when an optimistic `expected_version` check fails.
38
+
39
+ Attributes:
40
+ expected_version: The version the caller believed was current.
41
+ current_version: The version actually stored in the backend.
42
+ """
43
+
44
+ def __init__(self, expected_version: int | None, current_version: int) -> None:
45
+ self.expected_version = expected_version
46
+ self.current_version = current_version
47
+ super().__init__(
48
+ f"context version conflict: expected={expected_version!r} current={current_version!r}"
49
+ )
50
+
51
+
52
+ class LeaseExpiredError(ActiveMemoryError):
53
+ """Raised when an operation is attempted against an expired lease.
54
+
55
+ Callers must re-register (obtaining a new `instance_id`) rather than
56
+ attempt to renew an expired lease.
57
+ """
58
+
59
+ def __init__(self, agent_id: str, instance_id: str) -> None:
60
+ self.agent_id = agent_id
61
+ self.instance_id = instance_id
62
+ super().__init__(
63
+ f"lease expired for agent_id={agent_id!r} instance_id={instance_id!r}; "
64
+ "re-registration with a new instance_id is required"
65
+ )
66
+
67
+
68
+ class SchemaCompatibilityError(ActiveMemoryError):
69
+ """Raised when a record's schema_version is not supported.
70
+
71
+ Unknown additive (minor) schema versions must be tolerated by
72
+ consumers; this error is reserved for unsupported major schema
73
+ versions per the SDK compatibility policy.
74
+ """
75
+
76
+ def __init__(self, observed_version: int, supported_versions: tuple[int, ...]) -> None:
77
+ self.observed_version = observed_version
78
+ self.supported_versions = supported_versions
79
+ super().__init__(
80
+ f"unsupported schema_version={observed_version!r}; supported={supported_versions!r}"
81
+ )