agentleFS
gianlucamazzagianlucamazza/emotional-memory/CLAUDE.md

emotional-memory

CLAUDE.md9 starsChanged 6 months agoMITView on GitHub

Single test: The EMOTIONAL_MEMORY_LLM_* variables (API key, base URL, model, output mode, timeout, repeats, reasoning effort) are documented canonically in docs/contributing/llm-environment.md — that page is the SSOT; this file is a pointer. This library implements Affective Field Theory (AFT) — a 5-layer emotional model for LLM memory. The main entry point is EmotionalMemory (engine.py), which orchestrates the full pipeline.

  • Reads credentials

The file

We split this CLAUDE.md into the rules it gives an agent

5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    encode (dual-path, LeDoux 1996): When dual_path_encoding=True and an appraisal engine is configured — fast path: skip appraisal, use raw …

    line 98
  2. Distinctive:

    observe: update affective state from content without storing a retrievable memory.

    line 102
  3. Very specific:

    Immutability: All value objects are Pydantic frozen=True.

    line 153
  4. Very specific:

    __slots__: All non-Pydantic classes define __slots__ for memory efficiency and attribute safety.

    line 158
  5. Very specific:

    __repr__: All non-Pydantic concrete classes implement a useful __repr__.

    line 159

≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Commands

make check          # Full suite: lint + typecheck + meta-check + test + bench-fidelity (run before commits)
make check-all      # check + mkdocs --strict + preflight --fast + reproduce-paper-check
make bump VERSION=X.Y.Z  # Atomic version bump: patches 3 upstream files, then propagates via sync-metadata
make test           # Run tests only
make cov            # Tests with branch coverage (80% minimum enforced)
make typecheck      # mypy strict mode
make lint           # ruff check
make format         # ruff format
make bench-fidelity # Psychological invariant tests (127 tests in benchmarks/)
make bench-perf     # Performance benchmarks
make bench          # fidelity + performance benchmarks (combined)
make install-demo   # Install canonical local Gradio demo stack
make test-llm        # Real-LLM integration tests (requires EMOTIONAL_MEMORY_LLM_API_KEY)
make bench-appraisal # LLM appraisal quality benchmarks (requires EMOTIONAL_MEMORY_LLM_API_KEY)
make bench-a3        # A3 downstream encode→retrieve→generate→judge (Addendum R; requires LLM key)
make bench-human-gold # A5 appraisal vs human-gold EmoBank (Addendum S; requires LLM key)
make bench-x-madial  # Addendum X third-party retrieval on MADial-Bench (requires LLM key; -dry = no-LLM smoke)
make bench-x2-esmem  # Addendum X2 third-party retrieval on ES-MemEval/EvoEmo (requires LLM key; -dry = no-LLM smoke)
make bench-z-profile # Addendum Z held-out learned retrieval profile (learning-to-rank; requires LLM key; -dry = no-LLM smoke)
make install        # Install package in editable mode with dev deps
make install-llm-test # Install llm-test dependencies (httpx)
make install-dotenv  # Install dotenv dependencies (python-dotenv)
make install-bench  # Install benchmark dependencies
make install-viz    # Install visualization dependencies (matplotlib)
make install-docs   # Install documentation dependencies (mkdocs + material + mkdocstrings)
make docs-images    # Generate docs/images/ PNGs from synthetic data
make docs           # Build static documentation site (docs/ → site/)
make docs-serve     # Serve documentation locally with live reload
make dist           # Build distribution packages (wheel + sdist)
make publish        # Build and publish to PyPI

Single test:

uv run python -m pytest tests/test_engine.py::test_name -v

LLM test environment variables

The EMOTIONAL_MEMORY_LLM_* variables (API key, base URL, model, output mode, timeout, repeats, reasoning effort) are documented canonically in docs/contributing/llm-environment.md — that page is the SSOT; this file is a pointer.

Architecture

This library implements Affective Field Theory (AFT) — a 5-layer emotional model for LLM memory. The main entry point is EmotionalMemory (engine.py), which orchestrates the full pipeline.

5-Layer Emotional Model

LayerClassTheory
1CoreAffect (affect.py)Russell 1980 valence-arousal circumplex
2AffectiveMomentum (affect.py)Spinozist velocity + acceleration over 3-point history
3MoodField (mood.py)Heidegger's slow-moving PAD mood background (EMA)
4AppraisalVector (appraisal.py)Scherer's 5 Stimulus Evaluation Checks → CoreAffect
5ResonanceLink (resonance.py)Bidirectional associative graph: 5 link types, top-5 per memory; spreading activation (Collins & Loftus 1975) + Hebbian strengthening (Hebb 1949)

Additional Modules

ModulePurpose
engine.pyEmotionalMemory, EmotionalMemoryConfig — sync orchestrator for the full encode/retrieve/observe/elaborate/prune pipeline
models.pyMemory, EmotionalTag — Pydantic data models for stored memories and their affective annotations
retrieval.py6-signal composite scoring, build_retrieval_plan(), RetrievalConfig, AdaptiveWeightsConfig, RetrievalSignals/Breakdown/Explanation, RankedMemory, RetrievalPlan
decay.pyACT-R power-law decay, DecayConfig, compute_effective_strength() — arousal modulation (McGaugh 2004) + spacing-effect via retrieval count
categorize.pyEmotionLabel, categorize_affect(), label_tag() — Plutchik wheel: maps (valence, arousal) to 8 primary emotions with intensity tiers (Russell 1980 + Plutchik 1980)
appraisal_schema.pyAppraisalSchema, AppraisalDimension, SCHERER_CPM_SCHEMA (default), DIRECT_VAD_SCHEMA (opt-in, LLM rates V/A/D directly — stronger human-gold agreement, Addendum V; yields GenericAppraisalVector so dual-path elaborate()/SEC features need the default) — pluggable appraisal-theory schemas (OCC, GRID, custom)
appraisal_llm.pyLLMAppraisalEngine (LLM-backed, thread-safe LRU cache) + KeywordAppraisalEngine (rule-based fallback)
async_engine.pyAsyncEmotionalMemory — async facade, mirrors EmotionalMemory
async_adapters.pySyncToAsync* bridge adapters + as_async() convenience wrapper
interfaces_async.pyAsyncEmbedder, AsyncMemoryStore, AsyncAppraisalEngine protocols
interfaces.pyEmbedder, MemoryStore, AffectiveStateStore protocols + SequentialEmbedder base class
embedders/SentenceTransformerEmbedder — production-ready SequentialEmbedder backed by sentence-transformers ([sentence-transformers] extra); top-level re-export via PEP 562 __getattr__ when the extra is installed
state_stores/InMemoryAffectiveStateStore, SQLiteAffectiveStateStore, RedisAffectiveStateStore — pluggable backends for persisting the runtime affective state across sessions
llm_http.pyOpenAICompatibleLLMConfig, make_httpx_llm() — thin httpx-based LLM client for appraisal (submodule-only, not top-level exports; import as from emotional_memory.llm_http import …)
integrations/langchain.pyLangChain memory integration (optional)
integrations/mem0.pyEmotionalMemoryMem0Backend — mem0-compatible facade (mem0 API surface, no runtime mem0ai dep) + messages_to_content helper; exported top-level
stores/sqlite.pySQLiteStore — persistent store with sqlite-vec ANN search
stores/qdrant.pyQdrantStore — Qdrant vector-database adapter ([qdrant] extra)
stores/chroma.pyChromaStore — ChromaDB adapter, ephemeral or persistent ([chroma] extra)
logging_config.pyconfigure_logging() — package logger setup (level from arg or EMOTIONAL_MEMORY_LOG_LEVEL; optional JSON)
telemetry.pytraced_span() context manager — OTel spans, no-op when [otel] extra absent
query_classifier.pyQueryClassifier protocol, HeuristicQueryClassifier, LLMQueryClassifier, LOCOMO_ROUTING, QUERY_TYPES — pluggable query-type routing; drives per-type weight selection in retrieval (Addendum L confirmatory study)
visualization.py8 matplotlib plotting functions (optional viz extra)

Key Data Flow

encode (single path): AppraisalVector → CoreAffect → AffectiveState.update() → EmotionalTag → [label_tag() if auto_categorize] → embed → store → resonance links (forward + backward bidirectional)

encode (dual-path, LeDoux 1996): When dual_path_encoding=True and an appraisal engine is configured — fast path: skip appraisal, use raw state.core_affect, set pending_appraisal=True. Slow path: call elaborate(memory_id) later to run full appraisal and blend core_affect (70% appraised / 30% raw).

retrieve: embed query → build_retrieval_plan() (pure, no side-effects) → Pass 1 (6-signal score, no spreading) → seed set → spreading_activation() (BFS multi-hop) → Pass 2 (activation_map boost) → per-memory: compute_ape() + update_prediction() → APE-gated reconsolidation → hebbian_strengthen() on co-retrieved links → return top-k. Use retrieve_with_explanations() to expose RetrievalExplanation / RetrievalBreakdown / RetrievalSignals per result. By default the affect-proximity signal (s3) uses the runtime affective state; pass the keyword-only query_affect: CoreAffect to retrieve()/retrieve_with_explanations() to score against the query's own affect instead (no state mutation), or call retrieve_with_query_appraisal() to appraise the query text and use that affect — the production-reachable retrieve-time query-appraisal path (Addendum T), best paired with DIRECT_VAD_SCHEMA — bounded to the affect-discriminative regime (Addendum T2A found it does not beat cosine on naturalistic dialogue). retrieve_query_gated() (Addendum Y, v0.17.0) is the safe wrapper: |valence| < query_affect_gate_tau (default 0.2) routes to semantic-only weights, else to the query-appraisal path.

observe: update affective state from content without storing a retrievable memory. Useful for assistant turns or system events.

async encode/retrieve: Same pipeline as sync. Embed/store/appraise calls are awaited. CPU-bound scoring (retrieval_score, decay, resonance) runs synchronously inline.

state persistence: save_state() → AffectiveState.snapshot() → JSON-safe dict (includes private _history). load_state(data) → AffectiveState.restore(). Round-trip preserves momentum history. persist_state() / restore_persisted_state() / clear_persisted_state() delegate to the configured AffectiveStateStore. reset_state() resets runtime state to baseline without touching the store.

prune: prune(threshold=0.05) → iterate all memories, call compute_effective_strength(), delete those below threshold. Returns count removed. Async variant awaits each store call.

export/import: export_memories() → [Memory.model_dump_json() | json.loads(...)]. import_memories(data, overwrite=False) → Memory.model_validate(item) per dict, skip duplicates unless overwrite=True. Returns count written.

encode_batch: embed_batch(contents) → list[embedding] → per-item appraisal computed in parallel up front (_appraise_many: async asyncio.gather + Semaphore, sync ThreadPoolExecutor, bounded by appraisal_max_concurrency), then per-item encode path consuming the appraisals in input order (state still evolves item-by-item, so results are identical to sequential). Resonance links built after all items stored.

elaborate_pending: iterates all stored memories where pending_appraisal=True, calls elaborate(memory_id) on each. Returns list of updated Memory objects.

resource cleanup: close() delegates to store.close() if available (duck-typed via getattr). Both engines support context manager: with EmotionalMemory(...) as em / async with AsyncEmotionalMemory(...) as em.

6-Signal Retrieval Scoring (retrieval.py)

Composite score weighted by current mood (adaptive weights):

  1. Semantic similarity (cosine)
  2. Mood congruence (Bower 1981 mood-congruent retrieval)
  3. Core affect proximity
  4. Momentum alignment
  5. Recency/decay (ACT-R power-law)
  6. Resonance boost (spreading activation, Pass 2 only)

Decay Engine (decay.py)

ACT-R power-law: strength(t) = initial * elapsed^(-effective_decay), modulated by encoding arousal (McGaugh 2004) and retrieval count (spacing effect). High-arousal memories have a floor.

Interfaces

Embedder and MemoryStore are typing.Protocol in interfaces.py — duck-typed, no inheritance required. MemoryStore requires __len__. InMemoryStore is the reference implementation.

AffectiveStateStore protocol is also in interfaces.py: save(state), load() → AffectiveState | None, clear(). Implementations live in state_stores/.

SequentialEmbedder in interfaces.py is a concrete base class: subclass it and implement embed(); embed_batch() is provided as a sequential fallback.

Async protocols live in interfaces_async.py: AsyncEmbedder, AsyncMemoryStore (uses count() -> int instead of __len__), AsyncAppraisalEngine.

AppraisalEngine protocol is in appraisal.py. LLMCallable protocol is in appraisal_llm.py.

get_current_mood(now) on both engines reads the MoodField regressed via MoodDecayConfig without mutating state. Configured via EmotionalMemoryConfig.mood_decay.

SQLiteStore, QdrantStore, and ChromaStore are exported from stores/__init__.py when their respective optional dependencies are installed (each guarded by contextlib.suppress(ImportError)). SQLiteStore is also re-exported from the top-level __init__.py.

SQLiteAffectiveStateStore and InMemoryAffectiveStateStore are exported from state_stores/__init__.py. RedisAffectiveStateStore requires the redis extra.

Conventions

  • Immutability: All value objects are Pydantic frozen=True. update() methods return new instances.
  • Protocols over ABCs: Extend via duck-typed protocols, not inheritance.
  • Config-driven: All behavior parameterized via nested config classes (EmotionalMemoryConfig, DecayConfig, RetrievalConfig, ResonanceConfig, MoodDecayConfig, AdaptiveWeightsConfig, LLMAppraisalConfig, QueryClassifierConfig). Top-level flags on EmotionalMemoryConfig: dual_path_encoding (bool), elaboration_learning_rate (float, blend ratio in elaborate()), auto_categorize (bool, run Plutchik categorization on encode), appraisal_max_concurrency (int, default 8, ge=1 — bounds parallel appraisal in encode_batch; set to 1 for fully sequential / a non-thread-safe llm callable), max_content_length (int | None, reject oversized encode/retrieve strings), query_affect_gate_tau (float, default 0.2 — neutral-query threshold for retrieve_query_gated()). Ablation toggles: enable_appraisal, enable_mood_signal, enable_momentum, enable_resonance, enable_reconsolidation (all bool = True).
  • Theory references: Each component cites source papers — preserve these in docstrings/comments.
  • Validation: Field clamping via Pydantic validators (e.g., valence ∈ [-1, +1], arousal ∈ [0, 1]).
  • __slots__: All non-Pydantic classes define __slots__ for memory efficiency and attribute safety.
  • __repr__: All non-Pydantic concrete classes implement a useful __repr__.
  • Logging: Modules with observable pipeline events (engine.py, async_engine.py, appraisal_llm.py) use logging.getLogger(__name__) at DEBUG level. warnings.warn is reserved for user-visible degradation (e.g., NaN embeddings).
  • mypy strict is enforced — all new code must be fully annotated.
  • Fidelity benchmarks in benchmarks/fidelity/ validate psychological phenomena — run after logic changes to retrieval, decay, or resonance.
  • Appraisal quality benchmarks in benchmarks/appraisal_quality/ validate LLM prompt output — run after changes to the Scherer CPM prompt in appraisal_llm.py.
  • Downstream benchmark in benchmarks/downstream/ (Addendum R, make bench-a3) measures end-to-end answer quality (encode→retrieve→generate→judge) AFT vs cosine in the oracle-affect regime.
  • Human-gold appraisal benchmark in benchmarks/human_gold_appraisal/ (Addendum S, make bench-human-gold) validates the appraisal signal against EmoBank human VAD labels (benchmarks/datasets/emobank_v1.json, CC-BY-SA 4.0).
  • Third-party retrieval benchmark in benchmarks/madialbench/ (Addendum X, make bench-x-madial[-dry]) tests oracle-free query-appraisal retrieval on MADial-Bench EN (vendored in benchmarks/datasets/madialbench/, MIT, sha256-pinned by the loader). Hx1 FAIL — the corpus rewards counter-congruent supportive recall.
  • Second third-party retrieval benchmark in benchmarks/esmemeval/ (Addendum X2, make bench-x2-esmem[-dry]) tests the same mechanism on ES-MemEval/EvoEmo (vendored in benchmarks/datasets/esmemeval/, CC-BY-4.0, sha256-pinned; the vendored file is excluded from byte-mutating pre-commit hooks). Hx2 FAIL — the QA gold is content-determined and affect-orthogonal (failure mode distinct from X).
  • Other addendum harnesses: benchmarks/query_appraisal/ (T), benchmarks/circularity_audit/ (U), benchmarks/appraisal_vad/ (V), benchmarks/arousal_calibration/ (W), benchmarks/gate/ (Y), benchmarks/learned_profile/ (Z — held-out learning-to-rank of the 6 retrieval-signal weights via benchmarks/common/ltr.py; Branch B closure: no learned linear profile beats cosine on third-party corpora). The full prereg→closure→verdict index is benchmarks/README.md.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.