cortext-memory 0.1.0__tar.gz

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 (37) hide show
  1. cortext_memory-0.1.0/LICENSE +21 -0
  2. cortext_memory-0.1.0/PKG-INFO +194 -0
  3. cortext_memory-0.1.0/README.md +162 -0
  4. cortext_memory-0.1.0/cortext/__init__.py +72 -0
  5. cortext_memory-0.1.0/cortext/core/__init__.py +1 -0
  6. cortext_memory-0.1.0/cortext/core/decay/__init__.py +23 -0
  7. cortext_memory-0.1.0/cortext/core/decay/ebbinghaus.py +126 -0
  8. cortext_memory-0.1.0/cortext/core/decay/forget_gate.py +169 -0
  9. cortext_memory-0.1.0/cortext/core/entity.py +85 -0
  10. cortext_memory-0.1.0/cortext/core/graph.py +226 -0
  11. cortext_memory-0.1.0/cortext/core/memory.py +253 -0
  12. cortext_memory-0.1.0/cortext/core/recall/__init__.py +38 -0
  13. cortext_memory-0.1.0/cortext/core/recall/embedding.py +157 -0
  14. cortext_memory-0.1.0/cortext/core/recall/extractor.py +132 -0
  15. cortext_memory-0.1.0/cortext/core/recall/extractors/__init__.py +19 -0
  16. cortext_memory-0.1.0/cortext/core/recall/extractors/regex_lang.py +335 -0
  17. cortext_memory-0.1.0/cortext/core/recall/pack.py +81 -0
  18. cortext_memory-0.1.0/cortext/core/recall/parser.py +194 -0
  19. cortext_memory-0.1.0/cortext/core/recall/text_extractor.py +224 -0
  20. cortext_memory-0.1.0/cortext/core/relation.py +138 -0
  21. cortext_memory-0.1.0/cortext/core/validation/__init__.py +19 -0
  22. cortext_memory-0.1.0/cortext/core/validation/canonical.py +448 -0
  23. cortext_memory-0.1.0/cortext/cortex.py +325 -0
  24. cortext_memory-0.1.0/cortext/integration/__init__.py +5 -0
  25. cortext_memory-0.1.0/cortext/integration/hermes_bridge.py +138 -0
  26. cortext_memory-0.1.0/cortext/workers/__init__.py +5 -0
  27. cortext_memory-0.1.0/cortext/workers/dream_agent.py +293 -0
  28. cortext_memory-0.1.0/cortext_memory.egg-info/PKG-INFO +194 -0
  29. cortext_memory-0.1.0/cortext_memory.egg-info/SOURCES.txt +35 -0
  30. cortext_memory-0.1.0/cortext_memory.egg-info/dependency_links.txt +1 -0
  31. cortext_memory-0.1.0/cortext_memory.egg-info/requires.txt +15 -0
  32. cortext_memory-0.1.0/cortext_memory.egg-info/top_level.txt +1 -0
  33. cortext_memory-0.1.0/pyproject.toml +55 -0
  34. cortext_memory-0.1.0/setup.cfg +4 -0
  35. cortext_memory-0.1.0/tests/test_cortext.py +243 -0
  36. cortext_memory-0.1.0/tests/test_definitive.py +194 -0
  37. cortext_memory-0.1.0/tests/test_hermes_bridge.py +112 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jhony Miler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,194 @@
1
+ Metadata-Version: 2.4
2
+ Name: cortext-memory
3
+ Version: 0.1.0
4
+ Summary: Cognitive memory for AI agents — W5H-structured, contradiction-aware, internationalized, token-efficient
5
+ Author-email: Jhony Miler <jonatasmiler@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/jhonymiler/Cortex
8
+ Project-URL: Repository, https://github.com/jhonymiler/Cortex
9
+ Project-URL: Issues, https://github.com/jhonymiler/Cortex/issues
10
+ Keywords: memory,agents,llm,ai,rag
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.0; extra == "dev"
23
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.1; extra == "dev"
25
+ Provides-Extra: ollama
26
+ Provides-Extra: openai
27
+ Provides-Extra: embeddings
28
+ Requires-Dist: sentence-transformers>=2.2; extra == "embeddings"
29
+ Provides-Extra: all
30
+ Requires-Dist: sentence-transformers>=2.2; extra == "all"
31
+ Dynamic: license-file
32
+
33
+ # Cortex
34
+
35
+ *Read this in [Português](README.pt-br.md).*
36
+
37
+ > **A cognitive memory system for AI agents — structured, internationalized, contradiction-aware, and token-efficient.**
38
+
39
+ Cortex gives an LLM agent a long-term memory that is *structured* rather than a
40
+ flat vector store. Every memory is decomposed into a **W5H** record (who, what,
41
+ why, when, where, how), validated against what is already known so the agent
42
+ does not silently store contradictions, and recalled through a deterministic
43
+ structural parser that returns a **compact** context string instead of a wall
44
+ of raw chunks.
45
+
46
+ It is a pure Python library with **zero required dependencies**, local-first,
47
+ and designed to plug into an agent loop as a transparent memory layer (recall
48
+ before the turn, store after it).
49
+
50
+ ```python
51
+ from cortext import CortexV5
52
+
53
+ cortex = CortexV5(namespace="myapp")
54
+
55
+ # Store a structured memory (W5H)
56
+ cortex.remember(
57
+ who=["Maria"],
58
+ what="reportou erro de pagamento",
59
+ why="cartão expirado",
60
+ where="suporte",
61
+ how="orientada a atualizar dados",
62
+ lang="pt",
63
+ )
64
+
65
+ # Recall — returns (compact_context, RecallResult)
66
+ context, result = cortex.recall("O que Maria pediu?")
67
+ print(context)
68
+ # Maria | reportou erro de pagamento
69
+ ```
70
+
71
+ ## Why structured memory
72
+
73
+ Most agent memory is "embed the turn, retrieve top-k chunks." That works until
74
+ it doesn't: chunks are bulky, retrieval mixes unrelated facts, and nothing stops
75
+ the store from holding `X` and `not X` at the same time.
76
+
77
+ Cortex takes a different stance — memory is **encoded information**, not mere
78
+ correlation. It is built around five structural properties (discrete schema,
79
+ syntax, an arbitrary-but-stable mapping to external referents, an independent
80
+ interpreter, and functional semantics driven by usage). In practice that buys
81
+ you four concrete things:
82
+
83
+ | Property | What it means in practice |
84
+ |---|---|
85
+ | **Structured (W5H)** | Recall returns `Maria \| reportou erro → orientada a atualizar dados`, not a 90-token chunk. |
86
+ | **Normative** | A `CanonicalValidator` detects contradictions *at write time* (3 levels: heuristic → embedding → LLM-as-judge) and can warn or block. |
87
+ | **Internationalized** | The W5H schema is language-neutral; only extraction is language-specific, and it is pluggable (PT/EN/ES regex + optional LLM fallback). |
88
+ | **Self-pruning** | Ebbinghaus decay + a forget gate + an optional background `DreamAgent` that replays, consolidates duplicates, and prunes what is no longer used. |
89
+
90
+ ## Benchmarks
91
+
92
+ Reproducible on this repo (`python bench/run_benchmark.py`), comparing Cortex
93
+ against an unstructured top-k baseline across 2 scenarios:
94
+
95
+ | Scenario | Tokens (baseline → Cortex) | Savings | P@5 (baseline → Cortex) | Contradiction detection |
96
+ |---|---|---|---|---|
97
+ | customer_support | 540 → 123 | **77.2%** | 0.367 → 0.778 | 100% |
98
+ | personal_assistant | 380 → 111 | **70.8%** | 0.840 → 0.860 | 67% |
99
+ | **Average** | — | **74.0%** | **0.603 → 0.819** | 83.5% |
100
+
101
+ - **~74% fewer context tokens** for the same retrieved information.
102
+ - **Precision@5 up from 0.60 to 0.82** — recall returns the *right* memories.
103
+ - **Zero false positives** in contradiction detection across both scenarios.
104
+ - **~0.1 ms** average recall latency (pure Python, in-memory graph).
105
+
106
+ Token savings directly cut prompt cost and free context budget for the actual
107
+ task; higher precision means the agent sees fewer irrelevant memories.
108
+
109
+ ## Install
110
+
111
+ ```bash
112
+ pip install cortext-memory
113
+ ```
114
+
115
+ Optional extras:
116
+
117
+ ```bash
118
+ pip install "cortext-memory[embeddings]" # sentence-transformers for embedding-level validation
119
+ pip install "cortext-memory[dev]" # pytest, ruff
120
+ ```
121
+
122
+ Cortex runs with **no extra dependencies** by default. The embedding and
123
+ LLM-as-judge contradiction levels are opt-in.
124
+
125
+ ## How it works
126
+
127
+ ```
128
+ WRITE text/W5H ──▶ CanonicalValidator (3-level) ──▶ Memory Graph
129
+ (warn or block contradictions)
130
+
131
+ RECALL query ──▶ LangDetector ──▶ HybridExtractor ──▶ QueryIntent (W5H)
132
+
133
+ Memory Graph ──▶ StructuralQueryParser ──▶ pack_for_context
134
+
135
+ compact context string
136
+
137
+ DECAY Ebbinghaus retrievability + ForgetGate, with an optional background
138
+ DreamAgent that replays, consolidates duplicates, and prunes.
139
+ ```
140
+
141
+ ### Internationalization
142
+
143
+ The W5H schema is universal; **extraction** is the only language-specific part,
144
+ and it is pluggable:
145
+
146
+ ```python
147
+ from cortext import RegexExtractor, HybridExtractor, LLMExtractor
148
+
149
+ extractor = HybridExtractor(
150
+ primary=RegexExtractor(default_lang="auto"), # PT, EN, ES — detected per query
151
+ fallback=LLMExtractor(model_fn=my_llm_call), # any language, when regex misses
152
+ )
153
+ ```
154
+
155
+ Recall is matched within the language of the stored content — store and query in
156
+ the same language for best results, or wire an LLM extractor for arbitrary
157
+ languages.
158
+
159
+ ## Using it inside an agent
160
+
161
+ The intended pattern is a transparent memory layer: recall before the LLM call,
162
+ store after it. `HermesCortexBridge` is a reference implementation of exactly
163
+ this:
164
+
165
+ ```python
166
+ from cortext.integration import HermesCortexBridge
167
+
168
+ bridge = HermesCortexBridge(namespace="session-1")
169
+
170
+ # Before the LLM call — inject recalled context:
171
+ context = bridge.pre_chat(user_input)
172
+ system_prompt = context + "\n\n" + base_system_prompt
173
+
174
+ # After the turn — persist it:
175
+ bridge.post_chat(user_message=user_input, assistant_message=reply)
176
+ ```
177
+
178
+ See [docs/INTEGRATION.md](docs/INTEGRATION.md) for plugging Cortex into an agent
179
+ (including the Hermes memory plugin) and [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
180
+ for the component-by-component design.
181
+
182
+ ## Development
183
+
184
+ ```bash
185
+ python -m venv venv && source venv/bin/activate
186
+ pip install -e ".[dev]"
187
+
188
+ pytest # 190+ tests
189
+ python bench/run_benchmark.py # reproduce the benchmarks
190
+ ```
191
+
192
+ ## License
193
+
194
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,162 @@
1
+ # Cortex
2
+
3
+ *Read this in [Português](README.pt-br.md).*
4
+
5
+ > **A cognitive memory system for AI agents — structured, internationalized, contradiction-aware, and token-efficient.**
6
+
7
+ Cortex gives an LLM agent a long-term memory that is *structured* rather than a
8
+ flat vector store. Every memory is decomposed into a **W5H** record (who, what,
9
+ why, when, where, how), validated against what is already known so the agent
10
+ does not silently store contradictions, and recalled through a deterministic
11
+ structural parser that returns a **compact** context string instead of a wall
12
+ of raw chunks.
13
+
14
+ It is a pure Python library with **zero required dependencies**, local-first,
15
+ and designed to plug into an agent loop as a transparent memory layer (recall
16
+ before the turn, store after it).
17
+
18
+ ```python
19
+ from cortext import CortexV5
20
+
21
+ cortex = CortexV5(namespace="myapp")
22
+
23
+ # Store a structured memory (W5H)
24
+ cortex.remember(
25
+ who=["Maria"],
26
+ what="reportou erro de pagamento",
27
+ why="cartão expirado",
28
+ where="suporte",
29
+ how="orientada a atualizar dados",
30
+ lang="pt",
31
+ )
32
+
33
+ # Recall — returns (compact_context, RecallResult)
34
+ context, result = cortex.recall("O que Maria pediu?")
35
+ print(context)
36
+ # Maria | reportou erro de pagamento
37
+ ```
38
+
39
+ ## Why structured memory
40
+
41
+ Most agent memory is "embed the turn, retrieve top-k chunks." That works until
42
+ it doesn't: chunks are bulky, retrieval mixes unrelated facts, and nothing stops
43
+ the store from holding `X` and `not X` at the same time.
44
+
45
+ Cortex takes a different stance — memory is **encoded information**, not mere
46
+ correlation. It is built around five structural properties (discrete schema,
47
+ syntax, an arbitrary-but-stable mapping to external referents, an independent
48
+ interpreter, and functional semantics driven by usage). In practice that buys
49
+ you four concrete things:
50
+
51
+ | Property | What it means in practice |
52
+ |---|---|
53
+ | **Structured (W5H)** | Recall returns `Maria \| reportou erro → orientada a atualizar dados`, not a 90-token chunk. |
54
+ | **Normative** | A `CanonicalValidator` detects contradictions *at write time* (3 levels: heuristic → embedding → LLM-as-judge) and can warn or block. |
55
+ | **Internationalized** | The W5H schema is language-neutral; only extraction is language-specific, and it is pluggable (PT/EN/ES regex + optional LLM fallback). |
56
+ | **Self-pruning** | Ebbinghaus decay + a forget gate + an optional background `DreamAgent` that replays, consolidates duplicates, and prunes what is no longer used. |
57
+
58
+ ## Benchmarks
59
+
60
+ Reproducible on this repo (`python bench/run_benchmark.py`), comparing Cortex
61
+ against an unstructured top-k baseline across 2 scenarios:
62
+
63
+ | Scenario | Tokens (baseline → Cortex) | Savings | P@5 (baseline → Cortex) | Contradiction detection |
64
+ |---|---|---|---|---|
65
+ | customer_support | 540 → 123 | **77.2%** | 0.367 → 0.778 | 100% |
66
+ | personal_assistant | 380 → 111 | **70.8%** | 0.840 → 0.860 | 67% |
67
+ | **Average** | — | **74.0%** | **0.603 → 0.819** | 83.5% |
68
+
69
+ - **~74% fewer context tokens** for the same retrieved information.
70
+ - **Precision@5 up from 0.60 to 0.82** — recall returns the *right* memories.
71
+ - **Zero false positives** in contradiction detection across both scenarios.
72
+ - **~0.1 ms** average recall latency (pure Python, in-memory graph).
73
+
74
+ Token savings directly cut prompt cost and free context budget for the actual
75
+ task; higher precision means the agent sees fewer irrelevant memories.
76
+
77
+ ## Install
78
+
79
+ ```bash
80
+ pip install cortext-memory
81
+ ```
82
+
83
+ Optional extras:
84
+
85
+ ```bash
86
+ pip install "cortext-memory[embeddings]" # sentence-transformers for embedding-level validation
87
+ pip install "cortext-memory[dev]" # pytest, ruff
88
+ ```
89
+
90
+ Cortex runs with **no extra dependencies** by default. The embedding and
91
+ LLM-as-judge contradiction levels are opt-in.
92
+
93
+ ## How it works
94
+
95
+ ```
96
+ WRITE text/W5H ──▶ CanonicalValidator (3-level) ──▶ Memory Graph
97
+ (warn or block contradictions)
98
+
99
+ RECALL query ──▶ LangDetector ──▶ HybridExtractor ──▶ QueryIntent (W5H)
100
+
101
+ Memory Graph ──▶ StructuralQueryParser ──▶ pack_for_context
102
+
103
+ compact context string
104
+
105
+ DECAY Ebbinghaus retrievability + ForgetGate, with an optional background
106
+ DreamAgent that replays, consolidates duplicates, and prunes.
107
+ ```
108
+
109
+ ### Internationalization
110
+
111
+ The W5H schema is universal; **extraction** is the only language-specific part,
112
+ and it is pluggable:
113
+
114
+ ```python
115
+ from cortext import RegexExtractor, HybridExtractor, LLMExtractor
116
+
117
+ extractor = HybridExtractor(
118
+ primary=RegexExtractor(default_lang="auto"), # PT, EN, ES — detected per query
119
+ fallback=LLMExtractor(model_fn=my_llm_call), # any language, when regex misses
120
+ )
121
+ ```
122
+
123
+ Recall is matched within the language of the stored content — store and query in
124
+ the same language for best results, or wire an LLM extractor for arbitrary
125
+ languages.
126
+
127
+ ## Using it inside an agent
128
+
129
+ The intended pattern is a transparent memory layer: recall before the LLM call,
130
+ store after it. `HermesCortexBridge` is a reference implementation of exactly
131
+ this:
132
+
133
+ ```python
134
+ from cortext.integration import HermesCortexBridge
135
+
136
+ bridge = HermesCortexBridge(namespace="session-1")
137
+
138
+ # Before the LLM call — inject recalled context:
139
+ context = bridge.pre_chat(user_input)
140
+ system_prompt = context + "\n\n" + base_system_prompt
141
+
142
+ # After the turn — persist it:
143
+ bridge.post_chat(user_message=user_input, assistant_message=reply)
144
+ ```
145
+
146
+ See [docs/INTEGRATION.md](docs/INTEGRATION.md) for plugging Cortex into an agent
147
+ (including the Hermes memory plugin) and [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
148
+ for the component-by-component design.
149
+
150
+ ## Development
151
+
152
+ ```bash
153
+ python -m venv venv && source venv/bin/activate
154
+ pip install -e ".[dev]"
155
+
156
+ pytest # 190+ tests
157
+ python bench/run_benchmark.py # reproduce the benchmarks
158
+ ```
159
+
160
+ ## License
161
+
162
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,72 @@
1
+ """Cortext — Memory system for AI agents.
2
+
3
+ 5-element detector compliant, internationalized, efficient.
4
+ """
5
+
6
+ from cortext.cortex import CortexV5
7
+ from cortext.core.memory import Memory
8
+ from cortext.core.entity import Entity
9
+ from cortext.core.relation import Relation, RelationType
10
+ from cortext.core.graph import MemoryGraph, RecallResult
11
+ from cortext.core.validation import (
12
+ CanonicalValidator,
13
+ ValidationResult,
14
+ ValidationStatus,
15
+ ValidationPolicy,
16
+ create_default_validator,
17
+ create_strict_validator,
18
+ )
19
+ from cortext.core.recall import (
20
+ StructuralQueryParser,
21
+ QueryIntent,
22
+ pack_for_context,
23
+ RegexExtractor,
24
+ LLMExtractor,
25
+ HybridExtractor,
26
+ )
27
+ from cortext.core.decay import (
28
+ DecayConfig,
29
+ retrievability,
30
+ effective_stability,
31
+ decay_status,
32
+ ForgetGate,
33
+ ForgetGateConfig,
34
+ )
35
+ from cortext.workers import DreamAgent
36
+
37
+ __version__ = "0.1.0"
38
+
39
+ __all__ = [
40
+ # Main entry point
41
+ "CortexV5",
42
+ # Core data structures
43
+ "Memory",
44
+ "Entity",
45
+ "Relation",
46
+ "RelationType",
47
+ "MemoryGraph",
48
+ "RecallResult",
49
+ # Validation
50
+ "CanonicalValidator",
51
+ "ValidationResult",
52
+ "ValidationStatus",
53
+ "ValidationPolicy",
54
+ "create_default_validator",
55
+ "create_strict_validator",
56
+ # Recall
57
+ "StructuralQueryParser",
58
+ "QueryIntent",
59
+ "pack_for_context",
60
+ "RegexExtractor",
61
+ "LLMExtractor",
62
+ "HybridExtractor",
63
+ # Decay
64
+ "DecayConfig",
65
+ "retrievability",
66
+ "effective_stability",
67
+ "decay_status",
68
+ "ForgetGate",
69
+ "ForgetGateConfig",
70
+ # Workers
71
+ "DreamAgent",
72
+ ]
@@ -0,0 +1 @@
1
+ """Core data structures: Memory, Entity, Relation, MemoryGraph."""
@@ -0,0 +1,23 @@
1
+ """
2
+ Decay subsystem: Ebbinghaus R = e^(-t/S) + Forget Gate.
3
+ """
4
+
5
+ from cortext.core.decay.ebbinghaus import (
6
+ DecayConfig,
7
+ retrievability,
8
+ effective_stability,
9
+ decay_status,
10
+ )
11
+ from cortext.core.decay.forget_gate import (
12
+ ForgetGate,
13
+ ForgetGateConfig,
14
+ )
15
+
16
+ __all__ = [
17
+ "DecayConfig",
18
+ "retrievability",
19
+ "effective_stability",
20
+ "decay_status",
21
+ "ForgetGate",
22
+ "ForgetGateConfig",
23
+ ]
@@ -0,0 +1,126 @@
1
+ """
2
+ Ebbinghaus decay — R = e^(-t/S).
3
+
4
+ The classic forgetting curve, applied to memory retrieval. Simple,
5
+ universal, and validated empirically (Ebbinghaus, 1885).
6
+
7
+ Formula: R = e^(-t/S)
8
+ - R: retrievability (0.0-1.0)
9
+ - t: time since last access (days)
10
+ - S: stability (days) — base × modifiers
11
+
12
+ Stability modifiers (extensible):
13
+ - access_count: more accesses = more stable (log scale)
14
+ - importance: high importance = more stable
15
+ - consolidation: consolidated memories = more stable
16
+ - (custom) user-defined via metadata
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ from dataclasses import dataclass
23
+ from datetime import datetime
24
+ from typing import TYPE_CHECKING
25
+
26
+ if TYPE_CHECKING:
27
+ from cortext.core.memory import Memory
28
+
29
+
30
+ @dataclass
31
+ class DecayConfig:
32
+ """Tunables for the decay function."""
33
+
34
+ # Base stability (days for 63% decay without reinforcement)
35
+ base_stability_days: float = 7.0
36
+
37
+ # Stability modifiers
38
+ access_log_multiplier: float = 1.0 # log(access_count + 1) factor
39
+ importance_bonus: float = 1.3 # bonus for high importance (>0.7)
40
+ consolidation_bonus: float = 2.0 # bonus for consolidated memories
41
+
42
+ # Min/max stability (prevent degenerate values)
43
+ min_stability: float = 0.1
44
+ max_stability: float = 365.0
45
+
46
+ # Thresholds for status
47
+ active_threshold: float = 0.7
48
+ fading_threshold: float = 0.3
49
+ forgotten_threshold: float = 0.1
50
+
51
+
52
+ def retrievability(
53
+ memory: "Memory",
54
+ now: datetime | None = None,
55
+ config: DecayConfig | None = None,
56
+ ) -> float:
57
+ """
58
+ Compute retrievability of a memory using the Ebbinghaus curve.
59
+
60
+ R = e^(-t/S), where S = base_stability × modifiers.
61
+
62
+ Returns:
63
+ float between 0.0 (forgotten) and 1.0 (fresh)
64
+ """
65
+ if config is None:
66
+ config = DecayConfig()
67
+ now = now or datetime.now()
68
+
69
+ # Reference time = last access, fallback to creation
70
+ reference_time = memory.last_accessed or memory.when
71
+ days_since = max(0.0, (now - reference_time).total_seconds() / 86400)
72
+
73
+ # Compute effective stability
74
+ s = effective_stability(memory, config)
75
+
76
+ # Ebbinghaus formula
77
+ return math.exp(-days_since / s)
78
+
79
+
80
+ def effective_stability(
81
+ memory: "Memory",
82
+ config: DecayConfig | None = None,
83
+ ) -> float:
84
+ """
85
+ Compute the effective stability S for a memory.
86
+
87
+ S = base × access_modifier × importance_modifier × consolidation_modifier
88
+ """
89
+ if config is None:
90
+ config = DecayConfig()
91
+
92
+ s = config.base_stability_days
93
+
94
+ # Access count modifier (logarithmic)
95
+ access_factor = 1.0 + config.access_log_multiplier * math.log(memory.access_count + 1)
96
+ s *= access_factor
97
+
98
+ # Importance bonus
99
+ if memory.importance > 0.7:
100
+ s *= config.importance_bonus
101
+
102
+ # Consolidation bonus
103
+ if memory.is_consolidated:
104
+ s *= config.consolidation_bonus
105
+
106
+ return max(config.min_stability, min(config.max_stability, s))
107
+
108
+
109
+ def decay_status(
110
+ memory: "Memory",
111
+ now: datetime | None = None,
112
+ config: DecayConfig | None = None,
113
+ ) -> str:
114
+ """
115
+ Get a categorical status: "active" | "fading" | "weak" | "forgotten".
116
+ """
117
+ if config is None:
118
+ config = DecayConfig()
119
+ r = retrievability(memory, now, config)
120
+ if r >= config.active_threshold:
121
+ return "active"
122
+ elif r >= config.fading_threshold:
123
+ return "fading"
124
+ elif r >= config.forgotten_threshold:
125
+ return "weak"
126
+ return "forgotten"