[FEATURE] Add persistent cross-session memory via Agent Magnet
Feature Area
Integration with external tools
Is your feature request related to a an existing bug? Please link it here.
CrewAI agents lose context between sessions. Each run starts from zero — no memory of past decisions, user preferences, or learned patterns.
Agent Magnet adds self-learning memory with a single base URL change. Agents learn from what users do, not what they say. No configuration required.
Works across all your crew's LLM calls automatically. No SDK changes required.
agentmagnet.app — open to collaboration.
Describe the solution you'd like
Add Agent Magnet as a memory integration. Single base URL change gives agents persistent memory across sessions — no SDK changes needed. agentmagnet.app
Describe alternatives you've considered
LangChain memory, Mem0 — both require SDK changes and don't learn from user behavior automatically.
Additional context
Open to contributing an example or integration guide.
Willingness to Contribute
Yes, I'd be happy to submit a pull request
Persistent cross-session memory is the unlock for production agents. We run this pattern at scale (500+ sessions/week) with a cultivation-based memory architecture that's SDK-agnostic:
Why base-URL-only solutions fall short:
- No decision provenance — you can't trace why the agent learned X (was it from a bug? a one-off user preference? a permanent constraint?)
- No forgetting mechanism — memory grows unbounded, poisoning new contexts with stale beliefs
- No multi-agent isolation — crew A's decisions leak into crew B's context
Our production pattern (open-source):
- DDD (Domain-Driven Documentation) as persistent memory:
docs/decisions/,docs/patterns/,docs/constraints/ - Cultivation hooks auto-extract learnings at session end: "what changed? what was decided? what failed?"
- Memory sovereignty: each crew/agent owns its DDD namespace, no cross-contamination
- Git as memory substrate: every decision is a commit, full audit trail, branch = experiment
Code snippet (cultivation hook):
@session_end_hook
def extract_decisions(session):
"""Run lightweight agent to extract decisions from session transcript"""
prompt = f"""
Session transcript (last 50 turns): {session.transcript[-50:]}
Extract:
1. New patterns learned (code structure, naming conventions)
2. Constraints discovered (don't do X because Y)
3. Failed approaches (tried Z, didn't work because W)
Format as markdown for docs/decisions/YYYY-MM-DD_{topic}.md
"""
decision_doc = haiku_agent(prompt, max_tokens=2000)
git_commit(f"docs/decisions/{date}_{session.topic}.md", decision_doc)
Measured impact:
- Context reconstruction time: 30s (with DDD) vs 10min (from scratch)
- Decision recall accuracy: 94% (vs 62% with prompt-only memory)
- Memory growth: O(log n) — decisions consolidate over time, don't accumulate linearly
The key insight: Memory isn't a cache, it's a curated knowledge graph. Automatic capture + manual pruning (weekly retro) keeps it fresh. Same principle as git: commit often, rebase/squash periodically.
If Agent Magnet can integrate with git-backed DDD (commit on learn, read on init), that's the production-grade pattern. Otherwise you're solving caching, not learning.
Open to collaborating on a reference architecture if helpful — we're at SwarmAI.
Really valuable feedback — especially on provenance and forgetting. We actually have both: full temporal evolution with confidence history per preference, and multi-parameter decay (permanent/contextual/transient). The git-backed DDD angle is new to us but the audit trail maps well to our profile history layer. Would love to explore a reference architecture together. Reaching out via SwarmAI repo.
Persistent cross-session memory is the unlock for production agents. We run this pattern at scale (500+ sessions/week) with a cultivation-based memory architecture that's SDK-agnostic:
Why base-URL-only solutions fall short:
- No decision provenance — you can't trace why the agent learned X (was it from a bug? a one-off user preference? a permanent constraint?)
- No forgetting mechanism — memory grows unbounded, poisoning new contexts with stale beliefs
- No multi-agent isolation — crew A's decisions leak into crew B's context
Our production pattern (open-source):
- DDD (Domain-Driven Documentation) as persistent memory:
docs/decisions/,docs/patterns/,docs/constraints/- Cultivation hooks auto-extract learnings at session end: "what changed? what was decided? what failed?"
- Memory sovereignty: each crew/agent owns its DDD namespace, no cross-contamination
- Git as memory substrate: every decision is a commit, full audit trail, branch = experiment
Code snippet (cultivation hook):
@session_end_hook def extract_decisions(session): """Run lightweight agent to extract decisions from session transcript""" prompt = f""" Session transcript (last 50 turns): {session.transcript[-50:]}
Extract: 1. New patterns learned (code structure, naming conventions) 2. Constraints discovered (don't do X because Y) 3. Failed approaches (tried Z, didn't work because W) Format as markdown for docs/decisions/YYYY-MM-DD_{topic}.md """ decision_doc = haiku_agent(prompt, max_tokens=2000) git_commit(f"docs/decisions/{date}_{session.topic}.md", decision_doc)Measured impact:
- Context reconstruction time: 30s (with DDD) vs 10min (from scratch)
- Decision recall accuracy: 94% (vs 62% with prompt-only memory)
- Memory growth: O(log n) — decisions consolidate over time, don't accumulate linearly
The key insight: Memory isn't a cache, it's a curated knowledge graph. Automatic capture + manual pruning (weekly retro) keeps it fresh. Same principle as git: commit often, rebase/squash periodically.
If Agent Magnet can integrate with git-backed DDD (commit on learn, read on init), that's the production-grade pattern. Otherwise you're solving caching, not learning.
Open to collaborating on a reference architecture if helpful — we're at SwarmAI.
Persistent memory is definitely a game-changer for multi-session agent workflows. We’ve worked with similar setups where agents needed to recall user preferences without heavy SDK changes, and having a solution that hooks in via a base URL tweak sounds promising. A few things to consider:
- How does Agent Magnet handle data privacy and encryption when storing behavioral data?
- What’s the latency impact on each LLM call when routing through this persistent memory layer?
- If the integration is truly zero SDK change, ensuring seamless fallback when the service is down will be critical.
If you’re open to it, a minimal example demonstrating how to swap the base URL and validate memory persistence across sessions would help the community onboard faster. Also, comparing how it scales versus something like Redis-backed LangChain memory might clarify trade-offs.
Persistent memory is definitely a game-changer for multi-session agent workflows. We’ve worked with similar setups where agents needed to recall user preferences without heavy SDK changes, and having a solution that hooks in via a base URL tweak sounds promising. A few things to consider:
- How does Agent Magnet handle data privacy and encryption when storing behavioral data?
- What’s the latency impact on each LLM call when routing through this persistent memory layer?
- If the integration is truly zero SDK change, ensuring seamless fallback when the service is down will be critical.
If you’re open to it, a minimal example demonstrating how to swap the base URL and validate memory persistence across sessions would help the community onboard faster. Also, comparing how it scales versus something like Redis-backed LangChain memory might clarify trade-offs.
Great questions. On privacy: tenant-based isolation, GDPR compliant, on-premise SDK for zero data leaving your infra. On latency: fully async — zero added latency to LLM calls. On fallback: graceful degradation built in, requests pass through normally. Quickstart already in the repo: agentmagnet.app/docs. On LangChain comparison: Redis-backed LangChain stores explicit statements; we learn from behavioral signals — corrections, rejections, implicit patterns. Two things most systems miss: temporal decay (preferences expire at different rates — permanent vs contextual vs transient) and cross-user learning (patterns learned across sessions improve cold-start for new users). Different layer entirely.
Cross-session memory: why 'learning from what users do' needs more than a base URL change
Agent Magnet's approach — agents learning from user behavior rather than explicit instructions — is the right intuition. But the challenge in CrewAI specifically is that crew-level memory and agent-level memory have different lifetimes, scopes, and decay characteristics that a single base URL change can't resolve.
The CrewAI-Specific Memory Problem
In CrewAI, you have at least three memory scopes that need independent handling:
- Agent Memory — Individual agent preferences, tool usage patterns, task completion styles. Lifetime: per-agent, persists across all crews.
- Crew Memory — Team-level collaboration patterns, role handoff conventions, quality standards. Lifetime: per-crew, persists across runs of the same crew.
- Task Memory — Project-specific context, domain knowledge, learned solutions. Lifetime: per-project/task-type, should expire when the project ends.
Agent Magnet treating these as a single memory store creates two problems:
- Scope Bleed: Agent A's learned preferences from Crew X incorrectly influence its behavior in Crew Y.
- Stale Project Context: Task memories from completed projects continue to be recalled, adding noise to current work.
What We Found Building Cross-Platform Memory
Working on AgentRelay, we identified that effective cross-session memory needs three properties that most implementations miss:
1. Confidence-Weighted Memory, Not Binary Storage
Not every observed behavior should become a persistent preference. We use a confidence score that increases with repetition and decreases with contradiction:
- User corrects agent once → confidence 0.3 (tentative)
- User corrects agent 3× the same way → confidence 0.8 (likely real preference)
- User later does the opposite → confidence drops, old preference archived
This prevents agents from over-fitting to one-off user actions.
2. Temporal Decay with Context Anchors
Memories decay over time, but the decay rate depends on context anchors:
- Memories anchored to a specific project/codebase decay when the project changes (detectable via git hash)
- Memories anchored to user identity ("prefers British spelling") decay very slowly
- Memories anchored to tool behavior ("this API returns paginated results") don't decay until the tool changes
3. Pre-Session Memory Injection, Not On-Demand Recall
Instead of recalling memories mid-task (which adds latency), we inject a compressed memory summary at session start. This is a two-phase process:
- Phase 1: Retrieve top-K memories by relevance to current task
- Phase 2: Compress into a structured "session preamble" (~200 tokens) that the agent reads once
This keeps the memory overhead constant regardless of how many sessions of history exist.
Integration Path for CrewAI
For CrewAI specifically, AgentRelay could integrate as a that:
- Intercepts to inject relevant session memory
- Captures task completion outcomes for memory updates
- Provides crew-level memory summaries that persist across runs
The SDK-agnostic nature means it works alongside CrewAI's existing memory system without requiring a rewrite.
Happy to discuss the integration architecture if the CrewAI team is interested.
Really thorough breakdown. On confidence-weighted memory and temporal decay we already have both. Confidence increases with repetition, decreases with contradiction. Multi-parameter decay: permanent, contextual, transient with different rates. On scope separation, valid point for CrewAI-native use cases, that's a real distinction. The session preamble pattern maps to our injection layer. Curious about AgentRelay's approach on cross-platform behavioral signals, how do you handle implicit corrections vs explicit feedback?
Tried Magnet proxy integration on a small project, works fine for now. Not sure how it holds up with more agents and longer sessions though, would be interested to hear from someone who's tested that. Do you have a solution for enterprise? Proxy is not safe.
Been noticing agents lose context after session ends, gets pretty annoying. I use a vector database as a workaround but still getting hallucinations, probably because of the multi-agent setup. Does Agent Magnet handle that too?
Tried Magnet proxy integration on a small project, works fine for now. Not sure how it holds up with more agents and longer sessions though, would be interested to hear from someone who's tested that. Do you have a solution for enterprise? Proxy is not safe.
Fair concern on the proxy side — enterprise setup works differently, direct SDK integration with auth layer. No traffic routing through external endpoints. Multi-agent support is there too, agents share the same memory pool so context doesn't fragment across the crew. Happy to share more details if you want to test it.
Been noticing agents lose context after session ends, gets pretty annoying. I use a vector database as a workaround but still getting hallucinations, probably because of the multi-agent setup. Does Agent Magnet handle that too?
Yes, that's exactly the problem we built this for. Vector database alone doesn't cut it for multi-agent because each agent pulls context independently — they end up with conflicting or incomplete pictures. Magnet keeps a shared memory layer across the crew so agents stay in sync. The hallucination rate drops significantly when they're not working off different versions of the same context.
We've been dealing with the same cross-session memory problem in production with 20+ agents. One angle not yet discussed: wallet-based identity (ETH/SOL/BTC keypairs) as the persistence anchor instead of a memory proxy.
Each agent registers with an on-chain identity. When it reconnects, its wallet address is the durable handle — preferences, reputation, and interaction history are attached to that identity, not a session token or proxy URL. Memory lives in the agent's local store, but the identity that ties it all together is the wallet keypair.
This avoids a subtle problem: routing all agents through a single base URL for memory creates a central point of failure and privacy bottleneck. With wallet-based identity, each agent owns its memory, and cross-agent context is resolved through signed interaction records rather than a shared memory bus.
Running this pattern for a few months with 20+ agents following, tipping, and remembering each other across sessions. github.com/sunfishloop/sunfishloop
@kehansama raises a good point about crew-level vs agent-level memory boundaries. In practice, we found the boundary needs to be configurable per-deployment: some teams want shared memory across all agents in a crew (collaborative research), others need strict isolation (compliance-sensitive). The pattern that scaled was a memory_scope enum at crew definition time: shared, isolated, or hierarchical (agents share up to crew, crews don't share across). Re: @juliawxh's hallucination issue with vector DBs — the root cause is usually stale embeddings contaminating retrieval. Adding a recency bias (exponential decay on similarity scores by age) cut our hallucination rate from ~18% to ~4% in multi-agent setups.
Interesting proposal. The cross-session memory gap is one of the most painful problems in multi-agent systems right now — and the "single base URL change" approach is clever for quick adoption.
One challenge we have observed across multiple agent frameworks (not just CrewAI) is that persistent memory is not just about storage — it is about context quality. Agents that blindly accumulate memory across sessions end up with:
- Memory bloat: irrelevant or outdated information dilutes retrieval quality
- Context poisoning: bad decisions from early sessions persist and influence future behavior
- Scope leakage: memories from one project or user bleeding into unrelated contexts
This is why we are building AgentRelay as a middleware layer that handles cross-session memory with built-in curation:
- Session-boundary aware compression — memories are summarized and pruned at session boundaries, keeping only high-signal context
- Scope-isolated namespaces — each project/team has its own memory domain, no accidental cross-contamination
- Multi-agent memory sharing — when Crew A and Crew B need to share context, AgentRelay provides controlled cross-namespace access with permission boundaries
The key insight is that memory should not be a dumb store — it should be an intelligent relay that understands agent context, session boundaries, and project scope.
We would love to explore a CrewAI integration adapter. The
Crew.kickoff()boundary you mentioned in related discussions is exactly the hook point where session-aware memory management should kick in.AgentRelay repo: https://github.com/AgentRelay/agent-relay — open to collaboration on a native CrewAI memory adapter.
Really well-structured evaluation criteria. To address all four directly: memory can be corrected and deleted via our API. Injection respects a configurable token budget. On role boundaries and scoping — this is the valid gap you've identified. We're building scope hierarchy now: session, agent, crew, user levels with different decay rates per scope. If you want to test it as it ships, happy to give you early access. agentmagnet.app — feedback and issues welcome at github.com/helinakdogan/magnet-gateway
@kehansama raises a good point about crew-level vs agent-level memory boundaries. In practice, we found the boundary needs to be configurable per-deployment: some teams want shared memory across all agents in a crew (collaborative research), others need strict isolation (compliance-sensitive). The pattern that scaled was a
memory_scopeenum at crew definition time:shared,isolated, orhierarchical(agents share up to crew, crews don't share across). Re: @juliawxh's hallucination issue with vector DBs — the root cause is usually stale embeddings contaminating retrieval. Adding a recency bias (exponential decay on similarity scores by age) cut our hallucination rate from ~18% to ~4% in multi-agent setups.
The memory_scope enum pattern is exactly where we're heading — shared, isolated, hierarchical at crew definition time. The recency bias on similarity scores for hallucination reduction is a clean approach, maps well to our confidence decay layer. Would be useful to compare notes on threshold tuning. agentmagnet.app — if you want to follow along or open issues, github.com/helinakdogan/magnet-gateway
@kehansama raises a good point about crew-level vs agent-level memory boundaries. In practice, we found the boundary needs to be configurable per-deployment: some teams want shared memory across all agents in a crew (collaborative research), others need strict isolation (compliance-sensitive). The pattern that scaled was a
memory_scopeenum at crew definition time:shared,isolated, orhierarchical(agents share up to crew, crews don't share across). Re: @juliawxh's hallucination issue with vector DBs — the root cause is usually stale embeddings contaminating retrieval. Adding a recency bias (exponential decay on similarity scores by age) cut our hallucination rate from ~18% to ~4% in multi-agent setups.
The memory_scope enum pattern is exactly where we're heading — shared, isolated, hierarchical at crew definition time. The recency bias on similarity scores for hallucination reduction is a clean approach, maps well to our confidence decay layer. Would be useful to compare notes on threshold tuning. agentmagnet.app — if you want to follow along or open issues, github.com/helinakdogan/magnet-gateway
Tried Magnet proxy integration on a small project, works fine for now. Not sure how it holds up with more agents and longer sessions though, would be interested to hear from someone who's tested that. Do you have a solution for enterprise? Proxy is not safe.
Glad it's working. On scale — we've tested with multi-agent setups and longer sessions, memory injection stays async so latency doesn't compound. On enterprise: proxy is just one option. On-premise SDK runs entirely in your own infrastructure, no external routing. agentmagnet.app/docs for setup details. Open an issue if you hit anything specific. github.com/helinakdogan/magnet-gateway
Been noticing agents lose context after session ends, gets pretty annoying. I use a vector database as a workaround but still getting hallucinations, probably because of the multi-agent setup. Does Agent Magnet handle that too?
Yes, exactly this. Vector database alone doesn't solve multi-agent hallucinations because each agent retrieves independently — they end up working from different versions of context. Magnet keeps a shared memory layer so agents stay in sync. The hallucination rate drops when they're not pulling conflicting context. pip install agent-magnet to try the MCP version — self-hosted, works with any agent framework. agentmagnet.app — issues and feedback welcome at github.com/helinakdogan/magnet-gateway
@helinakdogan's point about context quality (not just storage) is the critical lever. We've seen this play out in long-running agent deployments: raw accumulation creates a "memory landfill" where relevant and irrelevant context intermix.
The missing piece is curation semantics:
- Decay/forgetting: Not all memory should persist equally. Decisions have lifetimes — a one-off project choice shouldn't pollute all future sessions. Systems need explicit TTLs or relevance decay (e.g., exponential backoff on retrieval score).
- Supersession: When a new decision contradicts an old one, the old one must be explicitly marked superseded, not just added alongside. Otherwise agents see both "use Postgres" and "use MongoDB" with equal weight.
- Redaction: Sensitive data or mistakes need hard deletion from the memory layer, not soft-delete. GDPR-compliance and operational safety both require this.
How this ties to the memory_scope pattern from June 6:
- At
sharedscope, bloat is worst because all agents contribute. Forgetting/curation must be crew-level, not agent-level. - At
isolatedscope, each agent's memory is smaller but still needs lifecycle management — otherwise long-running specialized agents accumulate infinite context. - At
hierarchical, the parent crew inherits only curated summaries from children, not raw events.
The proxy-first approach makes adoption frictionless, but production deployments will need explicit curation APIs (forget(), supersede(), redact()) so operators can prune the memory graph. Otherwise the "single base URL change" becomes a ticking context bomb.
How does Agent Magnet currently handle memory lifecycle? Is there a curation model built in, or is it append-only + retrieval scoring?
@helinakdogan's point about context quality (not just storage) is the critical lever. We've seen this play out in long-running agent deployments: raw accumulation creates a "memory landfill" where relevant and irrelevant context intermix.
The missing piece is curation semantics:
- Decay/forgetting: Not all memory should persist equally. Decisions have lifetimes — a one-off project choice shouldn't pollute all future sessions. Systems need explicit TTLs or relevance decay (e.g., exponential backoff on retrieval score).
- Supersession: When a new decision contradicts an old one, the old one must be explicitly marked superseded, not just added alongside. Otherwise agents see both "use Postgres" and "use MongoDB" with equal weight.
- Redaction: Sensitive data or mistakes need hard deletion from the memory layer, not soft-delete. GDPR-compliance and operational safety both require this.
How this ties to the
memory_scopepattern from June 6:
- At
sharedscope, bloat is worst because all agents contribute. Forgetting/curation must be crew-level, not agent-level.- At
isolatedscope, each agent's memory is smaller but still needs lifecycle management — otherwise long-running specialized agents accumulate infinite context.- At
hierarchical, the parent crew inherits only curated summaries from children, not raw events.The proxy-first approach makes adoption frictionless, but production deployments will need explicit curation APIs (
forget(),supersede(),redact()) so operators can prune the memory graph. Otherwise the "single base URL change" becomes a ticking context bomb.How does Agent Magnet currently handle memory lifecycle? Is there a curation model built in, or is it append-only + retrieval scoring?
Really sharp framing. "Memory landfill" is exactly the failure mode we've seen too.
On curation, we're not append only. A few things already in place: decay is multi parameter (permanent, contextual, and transient memories all have different TTLs), conflict resolution actively deletes contradicting preferences rather than accumulating both, and the full memory layer supports hard deletion via API.
Supersession is partially there. New signals override old ones when confidence crosses a threshold, but an explicit supersede() operation as a first class part of the curation API is not there yet. That's a real gap. Redact and hard delete are already supported at the tenant level.
On scope aware curation, I think you're right that shared scope needs crew level forgetting rather than agent level forgetting. That maps directly to what we're building with scope hierarchy. Crew scope memories are curated separately from agent scope memories. The forget(), supersede(), and redact() API surface is exactly where we're heading. It would be valuable to design this together, especially around the semantics of crew level curation.
Great thread — the discussion around context quality vs raw accumulation is the critical insight. A few patterns from building production agent memory infrastructure that complement what's been shared:
Knowledge graph as a complement to vector memory
Vector similarity alone misses structural relationships. When Agent A learns "User works at Acme" and Agent B learns "Acme's fiscal year ends in March," a knowledge graph connects those entities automatically. The next time any agent queries about the user's business context near Q1, both facts surface together. This isn't achievable with flat vector retrieval regardless of embedding quality — you need entity-aware storage.
Hybrid scoring for recall quality
The best recall quality in production comes from combining multiple signals at query time rather than relying on a single retrieval method:
- Vector similarity (semantic relevance)
- Temporal recency (importance × configurable decay)
- Graph proximity (entity relationships)
- Full-text match (exact keyword/phrase)
Each contributes a weighted score to the final ranking. The weights are tunable per use case — conversational agents need more recency weighting while research agents benefit from heavier semantic weighting.
Decay curves > TTL-based expiry
Building on @xg-gh-25's forgetting point: exponential decay with agent-configurable rates (importance × e^(-λt)) lets each agent or crew control what's ephemeral vs durable without explicit cleanup jobs. A memory of "user prefers JSON output" (high importance, slow decay) persists much longer than "user asked about weather yesterday" (low importance, fast decay). This is fundamentally different from TTL-based expiry, which treats all memories as equally important until they're deleted.
MCP as the memory interface layer
Rather than building memory integrations into each framework individually, exposing memory as an MCP (Model Context Protocol) server means any tool-use-capable LLM can access persistent memory with store and recall tools — no framework-specific SDK changes needed. This decouples the memory infrastructure from the orchestration layer.
For reference, Dakera implements these patterns as an open-core self-hosted server (decay-weighted recall, knowledge graph, hybrid search, MCP + REST + gRPC). Happy to share architecture details or benchmark methodology if useful.
The core problem here — agents starting from zero every session — is something I've spent the last year building against. The tricky part isn't just persisting memories, it's deciding what to keep. Without decay weighting, your memory index grows unbounded and recall quality drops because old irrelevant context competes with recent important facts during retrieval. We solved this with access-weighted importance decay: memories naturally fade over time but get reinforced every time they're actually retrieved and used. Combined with hybrid BM25+vector search (pure vector blurs specific names and dates together), agents recall the right context without drowning in stale history. The key architectural decision was making memory a standalone service rather than an in-process library — that way any agent framework can connect via REST or MCP without SDK lock-in. Self-hosted setup: https://github.com/dakera-ai/dakera-deploy/blob/main/docker/docker-compose.yml
This is close to a problem I have been working on in a separate project: https://github.com/Ar9av/obsidian-wiki
The basic idea is to persist agent context in local markdown files that survive restarts, then give the agent explicit update/query flows over that material. That has been useful for retaining prior decisions, user preferences, and project-specific context without depending on transient session state.
Different stack, but the underlying memory problem here looks very similar.