memorydrift 3.0.0__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.

Potentially problematic release.


This version of memorydrift might be problematic. Click here for more details.

memorylayer/decay.py ADDED
@@ -0,0 +1,241 @@
1
+ """
2
+ MemoryLayer — Decay Engine (Human-Calibrated v2.0)
3
+
4
+ Models memory of any person looking back across their life.
5
+ The age-at-encoding factor implements three neuroscience phenomena:
6
+
7
+ CHILDHOOD AMNESIA (age 0-7):
8
+ Near-zero encoding — most memories lost regardless of emotion.
9
+ Exception: extreme emotional events leave a faint somatic trace (floor 0.05).
10
+
11
+ LATENCY PERIOD (age 7-12):
12
+ Linear recovery — selective survival of vivid events.
13
+
14
+ REMINISCENCE BUMP (age 12-25, peak at 17):
15
+ Gaussian elevation — adolescent and early-adult memories are recalled
16
+ at 1.5-1.6× the rate of mid-adult memories. (Rubin & Schulkind 1997)
17
+
18
+ ADULT BASELINE (age 25-35): multiplier ~1.0
19
+ GENTLE DECLINE (age 35+): slight encoding weakness with age
20
+
21
+ Formula (from patent):
22
+ strength(t) = max(floor, exp(-t / (stability × halflife)) × importance)
23
+ stability = 1 + (emotional_weight × 2.5) + (repetition_count × 0.6)
24
+ floor = emotional_weight × 0.18 × age_factor
25
+
26
+ Halflives:
27
+ Working : ~1 hour
28
+ Episodic : 365 days (1 year — vivid for ~2-3 years)
29
+ Semantic : 1825 days (5 years)
30
+ Identity : infinite
31
+ """
32
+
33
+ import math
34
+ from dataclasses import dataclass
35
+ from enum import Enum
36
+ from typing import Optional
37
+
38
+
39
+ class MemoryLayer(Enum):
40
+ WORKING = "working"
41
+ EPISODIC = "episodic"
42
+ SEMANTIC = "semantic"
43
+ IDENTITY = "identity"
44
+ PROSPECTIVE = "prospective" # intentions that decay fast if unacted on
45
+
46
+
47
+ class FidelityLevel(Enum):
48
+ VIVID = "VIVID" # strength > 0.70 — "I clearly remember…"
49
+ CLEAR = "CLEAR" # 0.45 – 0.70 — "I remember…"
50
+ FADED = "FADED" # 0.22 – 0.45 — "I vaguely recall…"
51
+ VAGUE = "VAGUE" # 0.08 – 0.22 — "I have a faint sense that…"
52
+ FEELING = "FEELING" # 0.03 – 0.08 — "I don't remember what happened, but I remember how it felt"
53
+ FORGOTTEN = "FORGOTTEN" # < 0.03 — not returned at all
54
+
55
+
56
+ HALFLIFE = {
57
+ MemoryLayer.WORKING: 0.042, # ~1 hour
58
+ MemoryLayer.EPISODIC: 365.0, # 1 year
59
+ MemoryLayer.SEMANTIC: 1825.0, # 5 years
60
+ MemoryLayer.IDENTITY: 1e9, # permanent
61
+ MemoryLayer.PROSPECTIVE: 3.0, # 3 days — intentions fade fast if unacted on
62
+ }
63
+
64
+ FIDELITY_THRESHOLDS = [
65
+ (0.70, FidelityLevel.VIVID),
66
+ (0.45, FidelityLevel.CLEAR),
67
+ (0.22, FidelityLevel.FADED),
68
+ (0.08, FidelityLevel.VAGUE),
69
+ (0.03, FidelityLevel.FEELING), # emotion survives, episodic detail gone
70
+ (0.00, FidelityLevel.FORGOTTEN),
71
+ ]
72
+
73
+
74
+ # ── Change 3: Smooth continuous age-encoding function ──────────────────────────
75
+ # Replaces the old discrete band dict. No hard jumps between ages.
76
+ # Three regions stitched together:
77
+ # 0-7 : quadratic recovery from near-zero (childhood amnesia)
78
+ # 7-12 : linear climb through latency period
79
+ # 12-30: Gaussian bell curve peaking at age 17 (reminiscence bump — Rubin 1997)
80
+ # 30+ : gentle decline from adult baseline
81
+
82
+ def age_encoding_factor_smooth(age: float) -> float:
83
+ """
84
+ Continuous age-encoding multiplier applied to initial importance.
85
+ Implements childhood amnesia, latency period, reminiscence bump, and aging decline.
86
+ """
87
+ # Childhood amnesia: steep recovery from near-zero (quadratic)
88
+ if age < 7:
89
+ return 0.04 + (0.51 * (age / 7) ** 2)
90
+
91
+ # Latency period: linear climb
92
+ if age < 12:
93
+ return 0.55 + (0.65 * (age - 7) / 5)
94
+
95
+ # Reminiscence bump: Gaussian bell curve peaking at age 17
96
+ # (Rubin & Schulkind 1997: adolescent memories recalled at 1.5-2× adult rate)
97
+ if age < 30:
98
+ bump_peak = 17.0
99
+ bump_width = 7.0
100
+ bump_height = 0.60
101
+ bump = bump_height * math.exp(-((age - bump_peak) ** 2) / (2 * bump_width ** 2))
102
+ return 1.0 + bump
103
+
104
+ # Adult baseline with gradual encoding decline after 35
105
+ return max(0.75, 1.0 - ((age - 30) * 0.004))
106
+
107
+
108
+ def age_encoding_factor(age_at_encoding: Optional[float]) -> float:
109
+ """Public API: returns smooth age-encoding multiplier. None → adult baseline (1.0)."""
110
+ if age_at_encoding is None:
111
+ return 1.0
112
+ return age_encoding_factor_smooth(age_at_encoding)
113
+
114
+
115
+ # ── Change 2: Emotional early floor for pre-7 memories ────────────────────────
116
+ # Even though episodic details are lost in childhood amnesia, highly emotional
117
+ # events leave a somatic/emotional imprint — "I remember being terrified"
118
+ # not "I remember what happened." This floor is deliberately below VAGUE
119
+ # threshold (0.08): it represents a felt trace, not a retrievable memory.
120
+
121
+ def emotional_early_floor(age_at_encoding: Optional[float], emotional_weight: float) -> float:
122
+ """
123
+ Additional floor for high-emotion memories formed before age 7.
124
+ Returns a value in [0, 0.05] — below retrieval threshold but mathematically present.
125
+ """
126
+ if age_at_encoding is None or age_at_encoding >= 7:
127
+ return 0.0
128
+ if emotional_weight > 0.85:
129
+ return 0.05 # "I remember being scared" — feeling survives, not detail
130
+ if emotional_weight > 0.65:
131
+ return 0.02 # very faint emotional trace
132
+ return 0.0 # neutral early memories: nothing survives
133
+
134
+
135
+ @dataclass
136
+ class DecayResult:
137
+ strength: float
138
+ fidelity: FidelityLevel
139
+ stability: float
140
+ floor: float # effective floor (standard × age_factor, or early_floor if higher)
141
+ days_elapsed: float
142
+ years_elapsed: float
143
+ layer: MemoryLayer
144
+ emotional_weight: float
145
+ repetition_count: int
146
+ age_factor: float # smooth age-encoding multiplier applied
147
+
148
+
149
+ def compute_strength(
150
+ days_elapsed: float,
151
+ emotional_weight: float,
152
+ repetition_count: int,
153
+ importance: float,
154
+ layer: MemoryLayer,
155
+ age_at_encoding: Optional[float] = None,
156
+ ) -> DecayResult:
157
+ """
158
+ Compute current memory strength using the MemoryLayer decay formula.
159
+
160
+ Args:
161
+ days_elapsed: time since memory was stored (fractional days)
162
+ emotional_weight: 0.0–1.0 emotional significance
163
+ repetition_count: times this memory has been recalled
164
+ importance: base importance at write time (0.0–1.0)
165
+ layer: which memory layer
166
+ age_at_encoding: person's age (years) when memory was formed.
167
+ None → adult default (1.0 factor, no early floor).
168
+ """
169
+ halflife = HALFLIFE[layer]
170
+ stability = 1.0 + (emotional_weight * 2.5) + (repetition_count * 0.6)
171
+ age_factor = age_encoding_factor(age_at_encoding)
172
+
173
+ # Raw floor (Claim 1 of patent: emotionally-modulated floor effect)
174
+ floor_base = emotional_weight * 0.18
175
+ standard_floor = floor_base * age_factor
176
+
177
+ # Change 2: additional somatic trace for intense early-childhood memories
178
+ early_floor = emotional_early_floor(age_at_encoding, emotional_weight)
179
+ effective_floor = max(standard_floor, early_floor)
180
+
181
+ # Effective starting importance adjusted for age-at-encoding
182
+ effective_importance = min(1.0, importance * age_factor)
183
+
184
+ if layer == MemoryLayer.IDENTITY:
185
+ raw = effective_importance
186
+ else:
187
+ raw = math.exp(-days_elapsed / (stability * halflife)) * effective_importance
188
+
189
+ strength = max(effective_floor, min(1.0, raw))
190
+ fidelity = _classify_fidelity(strength)
191
+
192
+ return DecayResult(
193
+ strength=round(strength, 4),
194
+ fidelity=fidelity,
195
+ stability=round(stability, 3),
196
+ floor=round(effective_floor, 4),
197
+ days_elapsed=round(days_elapsed, 3),
198
+ years_elapsed=round(days_elapsed / 365.25, 2),
199
+ layer=layer,
200
+ emotional_weight=emotional_weight,
201
+ repetition_count=repetition_count,
202
+ age_factor=round(age_factor, 4),
203
+ )
204
+
205
+
206
+ def _classify_fidelity(strength: float) -> FidelityLevel:
207
+ for threshold, level in FIDELITY_THRESHOLDS:
208
+ if strength >= threshold:
209
+ return level
210
+ return FidelityLevel.FORGOTTEN
211
+
212
+
213
+ def decay_curve(
214
+ emotional_weight: float,
215
+ importance: float,
216
+ layer: MemoryLayer,
217
+ days: list,
218
+ age_at_encoding: Optional[float] = None,
219
+ ) -> list:
220
+ """Return list of (day, strength, fidelity) tuples — for display/plotting."""
221
+ return [
222
+ (d, *((r := compute_strength(d, emotional_weight, 0, importance,
223
+ layer, age_at_encoding)).strength,
224
+ r.fidelity.value))
225
+ for d in days
226
+ ]
227
+
228
+
229
+ def human_readable_age(days: float) -> str:
230
+ """Convert days elapsed to a human-readable time string."""
231
+ if days < 1:
232
+ hours = days * 24
233
+ return f"{hours:.0f}h ago" if hours >= 1 else "just now"
234
+ if days < 14:
235
+ return f"{days:.0f} days ago"
236
+ if days < 60:
237
+ return f"{days/7:.0f} weeks ago"
238
+ if days < 365:
239
+ return f"{days/30.4:.0f} months ago"
240
+ years = days / 365.25
241
+ return f"{years:.1f} years ago" if years < 2 else f"{years:.0f} years ago"
@@ -0,0 +1,37 @@
1
+ """
2
+ MemoryLayer — Embedding Utilities
3
+
4
+ Lazy-loads SentenceTransformer 'all-MiniLM-L6-v2' (384-dim, ~23MB, CPU-fast).
5
+ Falls back gracefully — returns None — when sentence-transformers is absent.
6
+ """
7
+
8
+ from typing import Optional
9
+
10
+ _embed_model = None
11
+ EMBED_AVAILABLE: Optional[bool] = None
12
+
13
+
14
+ def get_embedder():
15
+ """Lazy-load the embedding model. Safe to call repeatedly."""
16
+ global _embed_model, EMBED_AVAILABLE
17
+ if EMBED_AVAILABLE is not None:
18
+ return _embed_model
19
+ try:
20
+ from sentence_transformers import SentenceTransformer
21
+ _embed_model = SentenceTransformer("all-MiniLM-L6-v2")
22
+ EMBED_AVAILABLE = True
23
+ except Exception:
24
+ _embed_model = None
25
+ EMBED_AVAILABLE = False
26
+ return _embed_model
27
+
28
+
29
+ def embed(text: str) -> Optional[list]:
30
+ """
31
+ Return a 384-dim embedding for `text`, or None if the model is unavailable.
32
+ Result is a plain Python list so it can be stored in metadata dicts.
33
+ """
34
+ model = get_embedder()
35
+ if model is None:
36
+ return None
37
+ return model.encode(text, convert_to_numpy=True).tolist()
memorylayer/emotion.py ADDED
@@ -0,0 +1,243 @@
1
+ """
2
+ MemoryLayer — Emotion Classifier
3
+
4
+ Two classifiers available:
5
+
6
+ classify(text) — rule-based, zero dependencies (always available)
7
+ neural_emotional_weight(text)— j-hartmann/emotion-english-distilroberta-base via
8
+ HuggingFace transformers (~10ms on CPU, lazy-loaded)
9
+
10
+ NEURAL_AVAILABLE is set to True/False on first call to neural_emotional_weight().
11
+ Falls back gracefully if transformers is not installed.
12
+ """
13
+
14
+ import os
15
+ import re
16
+ from dataclasses import dataclass
17
+ from typing import Optional
18
+
19
+ # ── Load .env without requiring python-dotenv ─────────────────────────────────
20
+ _env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), ".env")
21
+ if os.path.exists(_env_path):
22
+ with open(_env_path) as _ef:
23
+ for _line in _ef:
24
+ _line = _line.strip()
25
+ if _line and not _line.startswith("#") and "=" in _line:
26
+ _k, _v = _line.split("=", 1)
27
+ os.environ.setdefault(_k.strip(), _v.strip())
28
+
29
+ # ── Neural classifier — lazy-loaded on first use ─────────────────────────────
30
+ _neural_pipeline = None
31
+ NEURAL_AVAILABLE: Optional[bool] = None # None = not yet attempted
32
+
33
+
34
+ def _load_neural():
35
+ """Lazy-load the HuggingFace emotion pipeline. Safe to call multiple times."""
36
+ global _neural_pipeline, NEURAL_AVAILABLE
37
+ if NEURAL_AVAILABLE is not None:
38
+ return _neural_pipeline
39
+ try:
40
+ hf_token = os.getenv("HF_TOKEN")
41
+ if hf_token:
42
+ from huggingface_hub import login as hf_login
43
+ hf_login(token=hf_token, add_to_git_credential=False)
44
+ from transformers import pipeline as hf_pipeline
45
+ _neural_pipeline = hf_pipeline(
46
+ "text-classification",
47
+ model="j-hartmann/emotion-english-distilroberta-base",
48
+ top_k=None, # return all labels (replaces deprecated return_all_scores=True)
49
+ device=-1, # CPU
50
+ )
51
+ NEURAL_AVAILABLE = True
52
+ except Exception:
53
+ _neural_pipeline = None
54
+ NEURAL_AVAILABLE = False
55
+ return _neural_pipeline
56
+
57
+
58
+ def neural_emotional_weight(text: str) -> float:
59
+ """
60
+ Score emotional weight using distilroberta-base emotion model.
61
+ Returns 0.0–1.0. Falls back to rule-based classify() if model unavailable.
62
+
63
+ High-emotion labels: fear, anger, sadness, surprise, joy
64
+ Neutral label: neutral
65
+ """
66
+ pipe = _load_neural()
67
+ if pipe is None:
68
+ return classify(text).weight
69
+
70
+ output = pipe(text[:512])
71
+ # top_k=None → [[{label, score}, ...]] (list-of-lists for single input)
72
+ # Older API fallback: [{label, score}, ...] (flat list of dicts)
73
+ scores = output[0] if isinstance(output[0], list) else output
74
+ high_labels = {"fear", "anger", "sadness", "surprise", "joy"}
75
+ raw = sum(s["score"] for s in scores if s["label"].lower() in high_labels)
76
+ return round(min(1.0, raw), 3)
77
+
78
+
79
+ @dataclass
80
+ class EmotionResult:
81
+ weight: float # 0.0–1.0
82
+ dominant_emotion: str # e.g. "grief", "joy", "neutral"
83
+ confidence: float # how certain the classifier is
84
+ signals: list # list of matched keywords
85
+
86
+
87
+ # High-emotion keywords grouped by category, each with a base score
88
+ HIGH_EMOTION = {
89
+ # Grief / loss (strong negative)
90
+ "died": 0.92, "death": 0.92, "dead": 0.90, "killed": 0.90,
91
+ "murdered": 0.92, "suicide": 0.92, "funeral": 0.85, "grief": 0.88,
92
+ "mourning": 0.85, "loss": 0.78, "lost": 0.72, "miss": 0.70,
93
+ "heartbroken": 0.88, "devastated": 0.90, "destroyed": 0.85,
94
+ "shattered": 0.85, "crushed": 0.82,
95
+
96
+ # Fear / trauma
97
+ "terrified": 0.88, "scared": 0.80, "afraid": 0.78, "fear": 0.80,
98
+ "panic": 0.85, "trauma": 0.88, "nightmare": 0.82, "abuse": 0.90,
99
+ "violence": 0.88, "attacked": 0.88, "threatened": 0.82,
100
+ "helpless": 0.82, "trapped": 0.80,
101
+
102
+ # Rage / anger
103
+ "furious": 0.85, "rage": 0.88, "angry": 0.75, "hate": 0.82,
104
+ "despise": 0.82, "betrayed": 0.90, "betrayal": 0.90,
105
+ "lied": 0.78, "cheated": 0.82, "humiliated": 0.85,
106
+
107
+ # Joy / love (strong positive)
108
+ "love": 0.82, "loved": 0.82, "wedding": 0.85, "married": 0.82,
109
+ "born": 0.88, "birth": 0.88, "baby": 0.82, "daughter": 0.72,
110
+ "son": 0.72, "mother": 0.70, "father": 0.70, "family": 0.65,
111
+ "proud": 0.75, "achieved": 0.72, "graduated": 0.80,
112
+ "promotion": 0.75, "won": 0.72, "victory": 0.78, "success": 0.68,
113
+ "celebrated": 0.75, "happy": 0.70, "joy": 0.78, "ecstatic": 0.88,
114
+ "overjoyed": 0.88, "elated": 0.85,
115
+
116
+ # Shock / surprise
117
+ "shocked": 0.80, "surprised": 0.65, "unexpected": 0.65,
118
+ "accident": 0.82, "suddenly": 0.70, "overnight": 0.55,
119
+
120
+ # Passing / death euphemisms
121
+ "passed away": 0.92, "passed on": 0.90, "gone forever": 0.92,
122
+ "no longer with us": 0.90, "taken from us": 0.90,
123
+
124
+ # Regret / guilt
125
+ "regret": 0.78, "guilty": 0.78, "ashamed": 0.80, "sorry": 0.65,
126
+ "mistake": 0.65, "forgive": 0.72, "forgiveness": 0.75,
127
+
128
+ # Hope / longing
129
+ "hope": 0.62, "dream": 0.60, "wish": 0.58, "pray": 0.65,
130
+ "finally": 0.60, "waited": 0.58,
131
+ }
132
+
133
+ # Medium-emotion — contextual weight
134
+ MED_EMOTION = {
135
+ "important": 0.40, "remember": 0.38, "never forget": 0.72,
136
+ "best day": 0.70, "worst day": 0.78, "best moment": 0.70,
137
+ "first time": 0.55, "last time": 0.60, "always": 0.40,
138
+ "never": 0.45, "changed": 0.50, "realized": 0.48,
139
+ "decided": 0.42, "promised": 0.65, "swore": 0.68,
140
+ }
141
+
142
+ # Low / neutral
143
+ LOW_EMOTION = {
144
+ "meeting": 0.15, "report": 0.10, "email": 0.10,
145
+ "task": 0.10, "work": 0.15, "project": 0.15,
146
+ "reminder": 0.12, "note": 0.10, "update": 0.10,
147
+ "schedule": 0.10, "plan": 0.12,
148
+ }
149
+
150
+ INTENSIFIERS = {
151
+ "extremely": 1.4, "absolutely": 1.35, "incredibly": 1.35,
152
+ "deeply": 1.3, "completely": 1.25, "totally": 1.2,
153
+ "very": 1.15, "really": 1.10, "quite": 1.05,
154
+ "so": 1.08, "such": 1.05,
155
+ }
156
+
157
+ DIMINISHERS = {
158
+ "slightly": 0.6, "a bit": 0.65, "somewhat": 0.70,
159
+ "barely": 0.5, "hardly": 0.5, "not very": 0.55,
160
+ "kind of": 0.72, "sort of": 0.72,
161
+ }
162
+
163
+ NEGATIONS = {"not", "never", "no", "don't", "didn't", "wasn't",
164
+ "isn't", "aren't", "won't", "can't", "couldn't", "wouldn't"}
165
+
166
+
167
+ def classify(text: str) -> EmotionResult:
168
+ """Classify the emotional weight of a text string."""
169
+ if not text or not text.strip():
170
+ return EmotionResult(weight=0.0, dominant_emotion="neutral",
171
+ confidence=1.0, signals=[])
172
+
173
+ text_lower = text.lower()
174
+ words = re.findall(r"\b\w+\b", text_lower)
175
+ word_set = set(words)
176
+
177
+ scores = []
178
+ signals = []
179
+ dominant = "neutral"
180
+ dominant_score = 0.0
181
+
182
+ # Check negation context: words within 3 positions before each keyword
183
+ word_positions = {w: [i for i, x in enumerate(words) if x == w] for w in word_set}
184
+
185
+ def _is_negated(keyword_pos: int) -> bool:
186
+ window = max(0, keyword_pos - 3)
187
+ return any(words[i] in NEGATIONS for i in range(window, keyword_pos))
188
+
189
+ # Score high-emotion keywords
190
+ for phrase, score in {**HIGH_EMOTION, **MED_EMOTION}.items():
191
+ phrase_words = phrase.split()
192
+ if len(phrase_words) == 1:
193
+ kw = phrase_words[0]
194
+ if kw in word_set:
195
+ positions = word_positions.get(kw, [])
196
+ for pos in positions:
197
+ effective = score * (0.5 if _is_negated(pos) else 1.0)
198
+ # Apply intensifier/diminisher from previous word
199
+ if pos > 0:
200
+ prev = words[pos - 1]
201
+ effective *= INTENSIFIERS.get(prev, 1.0)
202
+ effective *= DIMINISHERS.get(prev, 1.0)
203
+ scores.append(effective)
204
+ signals.append(f"{kw}({effective:.2f})")
205
+ if effective > dominant_score:
206
+ dominant_score = effective
207
+ dominant = kw
208
+ else:
209
+ # Multi-word phrase
210
+ if phrase in text_lower:
211
+ scores.append(score)
212
+ signals.append(f'"{phrase}"({score:.2f})')
213
+ if score > dominant_score:
214
+ dominant_score = score
215
+ dominant = phrase
216
+
217
+ # Punctuation bonus
218
+ exclamations = len(re.findall(r"!", text))
219
+ questions = len(re.findall(r"\?", text))
220
+ all_caps = len(re.findall(r"\b[A-Z]{3,}\b", text))
221
+ punc_bonus = min(0.15, exclamations * 0.04 + questions * 0.02 + all_caps * 0.03)
222
+ if punc_bonus > 0:
223
+ scores.append(punc_bonus)
224
+ signals.append(f"punctuation(+{punc_bonus:.2f})")
225
+
226
+ # Combine: take max of top scores + weighted average of rest
227
+ if not scores:
228
+ return EmotionResult(weight=0.10, dominant_emotion="neutral",
229
+ confidence=0.9, signals=[])
230
+
231
+ scores_sorted = sorted(scores, reverse=True)
232
+ top = scores_sorted[0]
233
+ rest_avg = sum(scores_sorted[1:]) / max(len(scores_sorted) - 1, 1)
234
+ weight = min(1.0, top * 0.7 + rest_avg * 0.3)
235
+
236
+ confidence = min(1.0, 0.5 + len(signals) * 0.1)
237
+
238
+ return EmotionResult(
239
+ weight=round(weight, 3),
240
+ dominant_emotion=dominant,
241
+ confidence=round(confidence, 2),
242
+ signals=signals[:6], # top 6 for display
243
+ )
@@ -0,0 +1,166 @@
1
+ """
2
+ MemoryLayer — Fidelity-Degraded Content Retrieval (Patent Claim 2)
3
+
4
+ Retrieved memory content is dynamically compressed in specificity
5
+ proportional to computed temporal strength.
6
+
7
+ VIVID (>0.70) : "I clearly remember: [full verbatim content]"
8
+ CLEAR (0.45–) : "I remember: [full content]"
9
+ FADED (0.22–) : "I vaguely recall: [first sentence only]"
10
+ VAGUE (0.08–) : "I have a faint sense that: [one-line gist]"
11
+ FEELING (0.03–) : "I don't remember what happened, but I remember how it felt — [emotion descriptor]"
12
+ FORGOTTEN(<.03) : Not returned to AI at all
13
+ """
14
+
15
+ import re
16
+ from dataclasses import dataclass
17
+ from .decay import FidelityLevel
18
+
19
+
20
+ @dataclass
21
+ class FidelityResult:
22
+ fidelity: FidelityLevel
23
+ prefix_phrase: str # "I clearly remember:", "I vaguely recall:", …
24
+ displayed_content: str # what gets injected into the LLM prompt
25
+ original_length: int
26
+ displayed_length: int
27
+ compression_ratio: float
28
+
29
+
30
+ PREFIX = {
31
+ FidelityLevel.VIVID: "I clearly remember",
32
+ FidelityLevel.CLEAR: "I remember",
33
+ FidelityLevel.FADED: "I vaguely recall",
34
+ FidelityLevel.VAGUE: "I have a faint sense that",
35
+ FidelityLevel.FEELING: "I don't remember what happened, but I remember how it felt —",
36
+ FidelityLevel.FORGOTTEN: "",
37
+ }
38
+
39
+
40
+ def degrade_content(content: str, fidelity: FidelityLevel) -> FidelityResult:
41
+ """
42
+ Apply fidelity degradation to content string.
43
+ Returns a FidelityResult with appropriately compressed text and prefix phrase.
44
+ """
45
+ original_len = len(content)
46
+ prefix = PREFIX[fidelity]
47
+
48
+ if fidelity == FidelityLevel.FORGOTTEN:
49
+ return FidelityResult(
50
+ fidelity=fidelity,
51
+ prefix_phrase="",
52
+ displayed_content="",
53
+ original_length=original_len,
54
+ displayed_length=0,
55
+ compression_ratio=0.0,
56
+ )
57
+
58
+ if fidelity in (FidelityLevel.VIVID, FidelityLevel.CLEAR):
59
+ shown = content
60
+ elif fidelity == FidelityLevel.FADED:
61
+ shown = _first_sentence(content)
62
+ elif fidelity == FidelityLevel.VAGUE:
63
+ shown = _gist(content)
64
+ elif fidelity == FidelityLevel.FEELING:
65
+ # Emotion survives — details do not. Return only the emotional descriptor.
66
+ shown = _emotional_feeling(content)
67
+ else:
68
+ shown = ""
69
+
70
+ displayed = f"{prefix}: {shown}" if shown else ""
71
+
72
+ return FidelityResult(
73
+ fidelity=fidelity,
74
+ prefix_phrase=prefix,
75
+ displayed_content=displayed,
76
+ original_length=original_len,
77
+ displayed_length=len(shown),
78
+ compression_ratio=round(len(shown) / max(original_len, 1), 3),
79
+ )
80
+
81
+
82
+ # ── Content extractors ────────────────────────────────────────────────────────
83
+
84
+ def _first_sentence(text: str) -> str:
85
+ """Extract just the first sentence."""
86
+ text = text.strip()
87
+ m = re.search(r"[.!?](?:\s|$)", text)
88
+ if m:
89
+ return text[:m.end()].strip()
90
+ return text[:100].strip() + ("…" if len(text) > 100 else "")
91
+
92
+
93
+ def _gist(text: str) -> str:
94
+ """Very short gist: subject + verb core (first clause or first 8 words)."""
95
+ text = text.strip()
96
+ comma = text.find(",")
97
+ if 10 < comma < 80:
98
+ return text[:comma].strip()
99
+ words = text.split()
100
+ short = " ".join(words[:8])
101
+ if len(words) > 8:
102
+ short += "…"
103
+ return short
104
+
105
+
106
+ def _emotional_feeling(content: str) -> str:
107
+ """
108
+ Return a 2-3 word emotional descriptor.
109
+ The specific episodic detail is lost — only the emotional quality survives.
110
+ This models the somatic trace of early childhood memories.
111
+ """
112
+ c = content.lower()
113
+
114
+ # Death / grief
115
+ if any(w in c for w in ["died", "death", "dead", "passed away", "funeral",
116
+ "grief", "mourning", "loss", "murder", "killed"]):
117
+ return "profound grief and loss"
118
+ # Fear / trauma
119
+ if any(w in c for w in ["terrified", "scared", "panic", "abuse", "attacked",
120
+ "helpless", "trapped", "hurt", "trauma", "nightmare"]):
121
+ return "fear and helplessness"
122
+ # Rage / betrayal
123
+ if any(w in c for w in ["furious", "rage", "angry", "betrayed", "humiliated",
124
+ "lied", "cheated", "hate"]):
125
+ return "anger and hurt"
126
+ # Joy / love
127
+ if any(w in c for w in ["love", "joy", "happy", "ecstatic", "overjoyed",
128
+ "celebrated", "won", "born", "birth", "wedding"]):
129
+ return "warmth and joy"
130
+ # Pride / achievement
131
+ if any(w in c for w in ["proud", "achieved", "graduated", "promotion", "won",
132
+ "victory", "success"]):
133
+ return "pride and excitement"
134
+ # Sadness / longing
135
+ if any(w in c for w in ["miss", "sad", "heartbroken", "devastated", "lonely",
136
+ "regret", "cried", "cry"]):
137
+ return "sadness and longing"
138
+ # Surprise / shock
139
+ if any(w in c for w in ["shocked", "surprised", "unexpected", "suddenly",
140
+ "accident"]):
141
+ return "surprise and disorientation"
142
+ # Generic fallback — keep first 3 words stripped of punctuation
143
+ words = re.sub(r"[^\w\s]", "", content).split()
144
+ return " ".join(words[:3]).lower() if words else "something significant"
145
+
146
+
147
+ def build_prompt_context(retrieved_memories: list) -> str:
148
+ """
149
+ Build the memory context block for injection into an LLM system prompt.
150
+ Each memory is labelled with its fidelity so the LLM calibrates confidence.
151
+ FEELING memories are included but labelled as somatic traces.
152
+ """
153
+ if not retrieved_memories:
154
+ return ""
155
+
156
+ lines = ["[MEMORY CONTEXT — respond with appropriate certainty]\n"]
157
+ for i, rm in enumerate(retrieved_memories, 1):
158
+ f = rm.decay.fidelity.value
159
+ lines.append(f"Memory {i} [{f}]: {rm.display_content}")
160
+
161
+ lines.append(
162
+ "\n[If a memory is FADED or VAGUE, express uncertainty naturally. "
163
+ "If FEELING, acknowledge only the emotion — never assert what happened. "
164
+ "Never assert vague memories as facts. FORGOTTEN = not mentioned.]"
165
+ )
166
+ return "\n".join(lines)