-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathshort_term.py
More file actions
2192 lines (1758 loc) · 70.3 KB
/
Copy pathshort_term.py
File metadata and controls
2192 lines (1758 loc) · 70.3 KB
1
2
3
4
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Redis Short-Term Memory for Empathy Framework
Per EMPATHY_PHILOSOPHY.md v1.1.0:
- Implements fast, TTL-based working memory for agent coordination
- Role-based access tiers for data integrity
- Pattern staging before validation
- Principled negotiation support
Enhanced Features (v2.0):
- Pub/Sub for real-time agent notifications
- Batch operations for high-throughput workflows
- SCAN-based pagination for large datasets
- Redis Streams for audit trails
- Connection retry with exponential backoff
- SSL/TLS support for managed Redis services
- Time-window queries with sorted sets
- Task queues with Lists
- Atomic transactions with MULTI/EXEC
- Comprehensive metrics tracking
Copyright 2025 Smart AI Memory, LLC
Licensed under Fair Source 0.9
"""
import json
import os
import threading
import time
from collections.abc import Callable
from datetime import datetime
from typing import Any
import structlog
from .security.pii_scrubber import PIIScrubber
from .security.secrets_detector import SecretsDetector
from .security.secrets_detector import Severity as SecretSeverity
# Import types from dedicated module
from .types import (
AccessTier,
AgentCredentials,
ConflictContext,
PaginatedResult,
RedisConfig,
RedisMetrics,
SecurityError,
StagedPattern,
TimeWindowQuery,
TTLStrategy,
)
logger = structlog.get_logger(__name__)
try:
import redis
from redis.exceptions import ConnectionError as RedisConnectionError
from redis.exceptions import TimeoutError as RedisTimeoutError
REDIS_AVAILABLE = True
except ImportError:
REDIS_AVAILABLE = False
RedisConnectionError = Exception # type: ignore
RedisTimeoutError = Exception # type: ignore
class RedisShortTermMemory:
"""Redis-backed short-term memory for agent coordination
Features:
- Fast read/write with automatic TTL expiration
- Role-based access control
- Pattern staging workflow
- Conflict negotiation context
- Agent working memory
Enhanced Features (v2.0):
- Pub/Sub for real-time agent notifications
- Batch operations (stash_batch, retrieve_batch)
- SCAN-based pagination for large datasets
- Redis Streams for audit trails
- Time-window queries with sorted sets
- Task queues with Lists (LPUSH/RPOP)
- Atomic transactions with MULTI/EXEC
- Connection retry with exponential backoff
- Metrics tracking for observability
Example:
>>> memory = RedisShortTermMemory()
>>> creds = AgentCredentials("agent_1", AccessTier.CONTRIBUTOR)
>>> memory.stash("analysis_results", {"issues": 3}, creds)
>>> data = memory.retrieve("analysis_results", creds)
# Pub/Sub example
>>> memory.subscribe("agent_signals", lambda msg: print(msg))
>>> memory.publish("agent_signals", {"event": "task_complete"}, creds)
# Batch operations
>>> items = [("key1", {"data": 1}), ("key2", {"data": 2})]
>>> memory.stash_batch(items, creds)
# Pagination
>>> result = memory.list_staged_patterns_paginated(creds, cursor="0", count=10)
"""
# Key prefixes for namespacing
PREFIX_WORKING = "empathy:working:"
PREFIX_STAGED = "empathy:staged:"
PREFIX_CONFLICT = "empathy:conflict:"
# PREFIX_COORDINATION removed in v5.0 - use empathy_os.telemetry.CoordinationSignals
PREFIX_SESSION = "empathy:session:"
PREFIX_PUBSUB = "empathy:pubsub:"
PREFIX_STREAM = "empathy:stream:"
PREFIX_TIMELINE = "empathy:timeline:"
PREFIX_QUEUE = "empathy:queue:"
def __init__(
self,
host: str = "localhost",
port: int = 6379,
db: int = 0,
password: str | None = None,
use_mock: bool = False,
config: RedisConfig | None = None,
):
"""Initialize Redis connection
Args:
host: Redis host
port: Redis port
db: Redis database number
password: Redis password (optional)
use_mock: Use in-memory mock for testing
config: Full RedisConfig for advanced settings (overrides other args)
"""
# Use config if provided, otherwise build from individual args
if config is not None:
self._config = config
else:
# Check environment variable for Redis enablement (default: disabled)
redis_enabled = os.getenv("REDIS_ENABLED", "false").lower() in ("true", "1", "yes")
# Use environment variables for configuration if available
env_host = os.getenv("REDIS_HOST", host)
env_port = int(os.getenv("REDIS_PORT", str(port)))
env_db = int(os.getenv("REDIS_DB", str(db)))
env_password = os.getenv("REDIS_PASSWORD", password)
# If Redis is not enabled via env var, force mock mode
if not redis_enabled and not use_mock:
use_mock = True
logger.info("redis_disabled_via_env", message="Redis not enabled in environment, using mock mode")
self._config = RedisConfig(
host=env_host,
port=env_port,
db=env_db,
password=env_password if env_password else None,
use_mock=use_mock,
)
self.use_mock = self._config.use_mock or not REDIS_AVAILABLE
# Initialize metrics
self._metrics = RedisMetrics()
# Pub/Sub state
self._pubsub: Any | None = None
self._pubsub_thread: threading.Thread | None = None
self._subscriptions: dict[str, list[Callable[[dict], None]]] = {}
self._pubsub_running = False
# Mock storage for testing
self._mock_storage: dict[str, tuple[Any, float | None]] = {}
self._mock_lists: dict[str, list[str]] = {}
self._mock_sorted_sets: dict[str, list[tuple[float, str]]] = {}
self._mock_streams: dict[str, list[tuple[str, dict]]] = {}
self._mock_pubsub_handlers: dict[str, list[Callable[[dict], None]]] = {}
# Local LRU cache for two-tier caching (memory + Redis)
# Reduces network I/O from 37ms to <0.001ms for frequently accessed keys
self._local_cache_enabled = self._config.local_cache_enabled
self._local_cache_max_size = self._config.local_cache_size
self._local_cache: dict[str, tuple[str, float, float]] = {} # key -> (value, timestamp, last_access)
self._local_cache_hits = 0
self._local_cache_misses = 0
# Security: Initialize PII scrubber and secrets detector
self._pii_scrubber: PIIScrubber | None = None
self._secrets_detector: SecretsDetector | None = None
if self._config.pii_scrub_enabled:
self._pii_scrubber = PIIScrubber(enable_name_detection=False)
logger.debug(
"pii_scrubber_enabled", message="PII scrubbing active for short-term memory"
)
if self._config.secrets_detection_enabled:
self._secrets_detector = SecretsDetector()
logger.debug(
"secrets_detector_enabled", message="Secrets detection active for short-term memory"
)
if self.use_mock:
self._client = None
else:
self._client = self._create_client_with_retry()
@property
def client(self) -> Any:
"""Get the Redis client instance.
Returns:
Redis client instance or None if using mock mode
Example:
>>> memory = RedisShortTermMemory()
>>> if memory.client:
... print("Redis connected")
"""
return self._client
@property
def metrics(self) -> "RedisMetrics":
"""Get Redis metrics instance.
Returns:
RedisMetrics instance with connection and operation statistics
Example:
>>> memory = RedisShortTermMemory()
>>> print(f"Retries: {memory.metrics.retries_total}")
"""
return self._metrics
def _create_client_with_retry(self) -> Any:
"""Create Redis client with retry logic."""
max_attempts = self._config.retry_max_attempts
base_delay = self._config.retry_base_delay
max_delay = self._config.retry_max_delay
last_error: Exception | None = None
for attempt in range(max_attempts):
try:
client = redis.Redis(**self._config.to_redis_kwargs())
# Test connection
client.ping()
logger.info(
"redis_connected",
host=self._config.host,
port=self._config.port,
attempt=attempt + 1,
)
return client
except (RedisConnectionError, RedisTimeoutError) as e:
last_error = e
self._metrics.retries_total += 1
if attempt < max_attempts - 1:
delay = min(base_delay * (2**attempt), max_delay)
logger.warning(
"redis_connection_retry",
attempt=attempt + 1,
max_attempts=max_attempts,
delay=delay,
error=str(e),
)
time.sleep(delay)
# All retries failed
logger.error(
"redis_connection_failed",
max_attempts=max_attempts,
error=str(last_error),
)
raise last_error if last_error else ConnectionError("Failed to connect to Redis")
def _execute_with_retry(self, operation: Callable[[], Any], op_name: str = "operation") -> Any:
"""Execute a Redis operation with retry logic."""
start_time = time.perf_counter()
max_attempts = self._config.retry_max_attempts
base_delay = self._config.retry_base_delay
max_delay = self._config.retry_max_delay
last_error: Exception | None = None
for attempt in range(max_attempts):
try:
result = operation()
latency_ms = (time.perf_counter() - start_time) * 1000
self._metrics.record_operation(op_name, latency_ms, success=True)
return result
except (RedisConnectionError, RedisTimeoutError) as e:
last_error = e
self._metrics.retries_total += 1
if attempt < max_attempts - 1:
delay = min(base_delay * (2**attempt), max_delay)
logger.warning(
"redis_operation_retry",
operation=op_name,
attempt=attempt + 1,
delay=delay,
)
time.sleep(delay)
latency_ms = (time.perf_counter() - start_time) * 1000
self._metrics.record_operation(op_name, latency_ms, success=False)
raise last_error if last_error else ConnectionError("Redis operation failed")
def _get(self, key: str) -> str | None:
"""Get value from Redis or mock with two-tier caching (local + Redis)"""
# Check local cache first (0.001ms vs 37ms for Redis/mock)
# This works for BOTH mock and real Redis modes
if self._local_cache_enabled and key in self._local_cache:
value, timestamp, last_access = self._local_cache[key]
now = time.time()
# Update last access time for LRU
self._local_cache[key] = (value, timestamp, now)
self._local_cache_hits += 1
return value
# Cache miss - fetch from storage (mock or Redis)
self._local_cache_misses += 1
# Mock mode path
if self.use_mock:
if key in self._mock_storage:
value, expires = self._mock_storage[key]
if expires is None or datetime.now().timestamp() < expires:
result = str(value) if value is not None else None
# Add to local cache for next access
if result and self._local_cache_enabled:
self._add_to_local_cache(key, result)
return result
del self._mock_storage[key]
return None
# Real Redis path
if self._client is None:
return None
result = self._client.get(key)
# Add to local cache if successful
if result and self._local_cache_enabled:
self._add_to_local_cache(key, str(result))
return str(result) if result else None
def _set(self, key: str, value: str, ttl: int | None = None) -> bool:
"""Set value in Redis or mock with two-tier caching"""
# Mock mode path
if self.use_mock:
expires = datetime.now().timestamp() + ttl if ttl else None
self._mock_storage[key] = (value, expires)
# Update local cache in mock mode too
if self._local_cache_enabled:
self._add_to_local_cache(key, value)
return True
# Real Redis path
if self._client is None:
return False
# Set in Redis
if ttl:
self._client.setex(key, ttl, value)
else:
result = self._client.set(key, value)
if not result:
return False
# Update local cache if enabled
if self._local_cache_enabled:
self._add_to_local_cache(key, value)
return True
def _delete(self, key: str) -> bool:
"""Delete key from Redis or mock and local cache"""
# Mock mode path
if self.use_mock:
deleted = False
if key in self._mock_storage:
del self._mock_storage[key]
deleted = True
# Remove from local cache if present
if self._local_cache_enabled and key in self._local_cache:
del self._local_cache[key]
return deleted
# Real Redis path
if self._client is None:
return False
# Delete from Redis
result = bool(self._client.delete(key) > 0)
# Also remove from local cache if present
if self._local_cache_enabled and key in self._local_cache:
del self._local_cache[key]
return result
def _keys(self, pattern: str) -> list[str]:
"""Get keys matching pattern"""
if self.use_mock:
import fnmatch
# Use list comp for small result sets (typical <1000 keys)
return [k for k in self._mock_storage.keys() if fnmatch.fnmatch(k, pattern)]
if self._client is None:
return []
keys = self._client.keys(pattern)
# Convert bytes to strings - needed for API return type
return [k.decode() if isinstance(k, bytes) else str(k) for k in keys]
# === Local LRU Cache Methods ===
def _add_to_local_cache(self, key: str, value: str) -> None:
"""Add entry to local cache with LRU eviction.
Args:
key: Cache key
value: Value to cache
"""
now = time.time()
# Evict oldest entry if cache is full
if len(self._local_cache) >= self._local_cache_max_size:
# Find key with oldest last_access time
oldest_key = min(self._local_cache, key=lambda k: self._local_cache[k][2])
del self._local_cache[oldest_key]
# Add new entry: (value, timestamp, last_access)
self._local_cache[key] = (value, now, now)
def clear_local_cache(self) -> int:
"""Clear all entries from local cache.
Returns:
Number of entries cleared
"""
count = len(self._local_cache)
self._local_cache.clear()
self._local_cache_hits = 0
self._local_cache_misses = 0
logger.info("local_cache_cleared", entries_cleared=count)
return count
def get_local_cache_stats(self) -> dict:
"""Get local cache performance statistics.
Returns:
Dict with cache stats (hits, misses, hit_rate, size)
"""
total = self._local_cache_hits + self._local_cache_misses
hit_rate = (self._local_cache_hits / total * 100) if total > 0 else 0.0
return {
"enabled": self._local_cache_enabled,
"size": len(self._local_cache),
"max_size": self._local_cache_max_size,
"hits": self._local_cache_hits,
"misses": self._local_cache_misses,
"hit_rate": hit_rate,
"total_requests": total,
}
# === Security Methods ===
def _sanitize_data(self, data: Any) -> tuple[Any, int]:
"""Sanitize data by scrubbing PII and checking for secrets.
Args:
data: Data to sanitize (dict, list, or str)
Returns:
Tuple of (sanitized_data, pii_count)
Raises:
SecurityError: If secrets are detected and blocking is enabled
"""
pii_count = 0
if data is None:
return data, 0
# Convert data to string for scanning
if isinstance(data, dict):
data_str = json.dumps(data)
elif isinstance(data, list):
data_str = json.dumps(data)
elif isinstance(data, str):
data_str = data
else:
# For other types, convert to string
data_str = str(data)
# Check for secrets first (before modifying data)
if self._secrets_detector is not None:
detections = self._secrets_detector.detect(data_str)
# Block critical and high severity secrets
critical_secrets = [
d
for d in detections
if d.severity in (SecretSeverity.CRITICAL, SecretSeverity.HIGH)
]
if critical_secrets:
self._metrics.secrets_blocked_total += len(critical_secrets)
secret_types = [d.secret_type.value for d in critical_secrets]
logger.warning(
"secrets_detected_blocked",
secret_types=secret_types,
count=len(critical_secrets),
)
raise SecurityError(
f"Cannot store data containing secrets: {secret_types}. "
"Remove sensitive credentials before storing."
)
# Scrub PII
if self._pii_scrubber is not None:
sanitized_str, pii_detections = self._pii_scrubber.scrub(data_str)
pii_count = len(pii_detections)
if pii_count > 0:
self._metrics.pii_scrubbed_total += pii_count
self._metrics.pii_scrub_operations += 1
logger.debug(
"pii_scrubbed",
pii_count=pii_count,
pii_types=[d.pii_type for d in pii_detections],
)
# Convert back to original type
if isinstance(data, dict):
try:
return json.loads(sanitized_str), pii_count
except json.JSONDecodeError:
# If PII scrubbing broke JSON structure, return original
# This can happen if regex matches part of JSON syntax
logger.warning("pii_scrubbing_broke_json_returning_original")
return data, 0
elif isinstance(data, list):
try:
return json.loads(sanitized_str), pii_count
except json.JSONDecodeError:
logger.warning("pii_scrubbing_broke_json_returning_original")
return data, 0
else:
return sanitized_str, pii_count
return data, pii_count
# === Working Memory (Stash/Retrieve) ===
def stash(
self,
key: str,
data: Any,
credentials: AgentCredentials,
ttl: TTLStrategy = TTLStrategy.WORKING_RESULTS,
skip_sanitization: bool = False,
) -> bool:
"""Stash data in short-term memory
Args:
key: Unique key for the data
data: Data to store (will be JSON serialized)
credentials: Agent credentials
ttl: Time-to-live strategy
skip_sanitization: Skip PII scrubbing and secrets detection (use with caution)
Returns:
True if successful
Raises:
ValueError: If key is empty or invalid
PermissionError: If credentials lack write access
SecurityError: If secrets are detected in data (when secrets_detection_enabled)
Note:
PII (emails, SSNs, phone numbers, etc.) is automatically scrubbed
before storage unless skip_sanitization=True or pii_scrub_enabled=False.
Secrets (API keys, passwords, etc.) will block storage by default.
Example:
>>> memory.stash("analysis_v1", {"findings": [...]}, creds)
"""
# Pattern 1: String ID validation
if not key or not key.strip():
raise ValueError(f"key cannot be empty. Got: {key!r}")
if not credentials.can_stage():
raise PermissionError(
f"Agent {credentials.agent_id} (Tier {credentials.tier.name}) "
"cannot write to memory. Requires CONTRIBUTOR or higher.",
)
# Sanitize data (PII scrubbing + secrets detection)
if not skip_sanitization:
data, pii_count = self._sanitize_data(data)
if pii_count > 0:
logger.info(
"stash_pii_scrubbed",
key=key,
agent_id=credentials.agent_id,
pii_count=pii_count,
)
full_key = f"{self.PREFIX_WORKING}{credentials.agent_id}:{key}"
payload = {
"data": data,
"agent_id": credentials.agent_id,
"stashed_at": datetime.now().isoformat(),
}
return self._set(full_key, json.dumps(payload), ttl.value)
def retrieve(
self,
key: str,
credentials: AgentCredentials,
agent_id: str | None = None,
) -> Any | None:
"""Retrieve data from short-term memory
Args:
key: Key to retrieve
credentials: Agent credentials
agent_id: Owner agent ID (defaults to credentials agent)
Returns:
Retrieved data or None if not found
Raises:
ValueError: If key is empty or invalid
Example:
>>> data = memory.retrieve("analysis_v1", creds)
"""
# Pattern 1: String ID validation
if not key or not key.strip():
raise ValueError(f"key cannot be empty. Got: {key!r}")
owner = agent_id or credentials.agent_id
full_key = f"{self.PREFIX_WORKING}{owner}:{key}"
raw = self._get(full_key)
if raw is None:
return None
payload = json.loads(raw)
return payload.get("data")
def clear_working_memory(self, credentials: AgentCredentials) -> int:
"""Clear all working memory for an agent
Args:
credentials: Agent credentials (must own the memory or be Steward)
Returns:
Number of keys deleted
"""
pattern = f"{self.PREFIX_WORKING}{credentials.agent_id}:*"
keys = self._keys(pattern)
count = 0
for key in keys:
if self._delete(key):
count += 1
return count
# === Pattern Staging ===
def stage_pattern(
self,
pattern: StagedPattern,
credentials: AgentCredentials,
) -> bool:
"""Stage a pattern for validation
Per EMPATHY_PHILOSOPHY.md: Patterns must be staged before
being promoted to the active library.
Args:
pattern: Pattern to stage
credentials: Must be CONTRIBUTOR or higher
Returns:
True if staged successfully
Raises:
TypeError: If pattern is not StagedPattern
PermissionError: If credentials lack staging access
"""
# Pattern 5: Type validation
if not isinstance(pattern, StagedPattern):
raise TypeError(f"pattern must be StagedPattern, got {type(pattern).__name__}")
if not credentials.can_stage():
raise PermissionError(
f"Agent {credentials.agent_id} cannot stage patterns. "
"Requires CONTRIBUTOR tier or higher.",
)
key = f"{self.PREFIX_STAGED}{pattern.pattern_id}"
return self._set(
key,
json.dumps(pattern.to_dict()),
TTLStrategy.STAGED_PATTERNS.value,
)
def get_staged_pattern(
self,
pattern_id: str,
credentials: AgentCredentials,
) -> StagedPattern | None:
"""Retrieve a staged pattern
Args:
pattern_id: Pattern ID
credentials: Any tier can read
Returns:
StagedPattern or None
Raises:
ValueError: If pattern_id is empty
"""
# Pattern 1: String ID validation
if not pattern_id or not pattern_id.strip():
raise ValueError(f"pattern_id cannot be empty. Got: {pattern_id!r}")
key = f"{self.PREFIX_STAGED}{pattern_id}"
raw = self._get(key)
if raw is None:
return None
return StagedPattern.from_dict(json.loads(raw))
def list_staged_patterns(
self,
credentials: AgentCredentials,
) -> list[StagedPattern]:
"""List all staged patterns awaiting validation
Args:
credentials: Any tier can read
Returns:
List of staged patterns
"""
pattern = f"{self.PREFIX_STAGED}*"
keys = self._keys(pattern)
patterns = []
for key in keys:
raw = self._get(key)
if raw:
patterns.append(StagedPattern.from_dict(json.loads(raw)))
return patterns
def promote_pattern(
self,
pattern_id: str,
credentials: AgentCredentials,
) -> StagedPattern | None:
"""Promote staged pattern (remove from staging for library add)
Args:
pattern_id: Pattern to promote
credentials: Must be VALIDATOR or higher
Returns:
The promoted pattern (for adding to PatternLibrary)
"""
if not credentials.can_validate():
raise PermissionError(
f"Agent {credentials.agent_id} cannot promote patterns. "
"Requires VALIDATOR tier or higher.",
)
pattern = self.get_staged_pattern(pattern_id, credentials)
if pattern:
key = f"{self.PREFIX_STAGED}{pattern_id}"
self._delete(key)
return pattern
def reject_pattern(
self,
pattern_id: str,
credentials: AgentCredentials,
reason: str = "",
) -> bool:
"""Reject a staged pattern
Args:
pattern_id: Pattern to reject
credentials: Must be VALIDATOR or higher
reason: Rejection reason (for audit)
Returns:
True if rejected
"""
if not credentials.can_validate():
raise PermissionError(
f"Agent {credentials.agent_id} cannot reject patterns. "
"Requires VALIDATOR tier or higher.",
)
key = f"{self.PREFIX_STAGED}{pattern_id}"
return self._delete(key)
# === Conflict Negotiation ===
def create_conflict_context(
self,
conflict_id: str,
positions: dict[str, Any],
interests: dict[str, list[str]],
credentials: AgentCredentials,
batna: str | None = None,
) -> ConflictContext:
"""Create context for principled negotiation
Per Getting to Yes framework:
- Separate positions from interests
- Define BATNA before negotiating
Args:
conflict_id: Unique conflict identifier
positions: agent_id -> their stated position
interests: agent_id -> underlying interests
credentials: Must be CONTRIBUTOR or higher
batna: Best Alternative to Negotiated Agreement
Returns:
ConflictContext for resolution
Raises:
ValueError: If conflict_id is empty
TypeError: If positions or interests are not dicts
PermissionError: If credentials lack permission
"""
# Pattern 1: String ID validation
if not conflict_id or not conflict_id.strip():
raise ValueError(f"conflict_id cannot be empty. Got: {conflict_id!r}")
# Pattern 5: Type validation
if not isinstance(positions, dict):
raise TypeError(f"positions must be dict, got {type(positions).__name__}")
if not isinstance(interests, dict):
raise TypeError(f"interests must be dict, got {type(interests).__name__}")
if not credentials.can_stage():
raise PermissionError(
f"Agent {credentials.agent_id} cannot create conflict context. "
"Requires CONTRIBUTOR tier or higher.",
)
context = ConflictContext(
conflict_id=conflict_id,
positions=positions,
interests=interests,
batna=batna,
)
key = f"{self.PREFIX_CONFLICT}{conflict_id}"
self._set(
key,
json.dumps(context.to_dict()),
TTLStrategy.CONFLICT_CONTEXT.value,
)
return context
def get_conflict_context(
self,
conflict_id: str,
credentials: AgentCredentials,
) -> ConflictContext | None:
"""Retrieve conflict context
Args:
conflict_id: Conflict identifier
credentials: Any tier can read
Returns:
ConflictContext or None
Raises:
ValueError: If conflict_id is empty
"""
# Pattern 1: String ID validation
if not conflict_id or not conflict_id.strip():
raise ValueError(f"conflict_id cannot be empty. Got: {conflict_id!r}")
key = f"{self.PREFIX_CONFLICT}{conflict_id}"
raw = self._get(key)
if raw is None:
return None
return ConflictContext.from_dict(json.loads(raw))
def resolve_conflict(
self,
conflict_id: str,
resolution: str,
credentials: AgentCredentials,
) -> bool:
"""Mark conflict as resolved
Args:
conflict_id: Conflict to resolve
resolution: How it was resolved
credentials: Must be VALIDATOR or higher
Returns:
True if resolved
"""
if not credentials.can_validate():
raise PermissionError(
f"Agent {credentials.agent_id} cannot resolve conflicts. "
"Requires VALIDATOR tier or higher.",
)
context = self.get_conflict_context(conflict_id, credentials)
if context is None:
return False
context.resolved = True
context.resolution = resolution
key = f"{self.PREFIX_CONFLICT}{conflict_id}"
# Keep resolved conflicts longer for audit
self._set(key, json.dumps(context.to_dict()), TTLStrategy.CONFLICT_CONTEXT.value)
return True
# === Coordination Signals ===
# REMOVED in v5.0 - Use empathy_os.telemetry.CoordinationSignals instead
# - send_signal() → CoordinationSignals.signal()
# - receive_signals() → CoordinationSignals.get_pending_signals()
# === Session Management ===
def create_session(
self,
session_id: str,
credentials: AgentCredentials,
metadata: dict | None = None,
) -> bool:
"""Create a collaboration session
Args:
session_id: Unique session identifier
credentials: Session creator
metadata: Optional session metadata
Returns:
True if created
Raises:
ValueError: If session_id is empty
TypeError: If metadata is not dict
"""
# Pattern 1: String ID validation
if not session_id or not session_id.strip():
raise ValueError(f"session_id cannot be empty. Got: {session_id!r}")
# Pattern 5: Type validation
if metadata is not None and not isinstance(metadata, dict):
raise TypeError(f"metadata must be dict, got {type(metadata).__name__}")
key = f"{self.PREFIX_SESSION}{session_id}"