[FEATURE] Memory write guards for multi-agent crews — prevent cross-agent memory poisoning
Feature Area
Core functionality
Is your feature request related to a an existing bug? Please link it here.
NA - not related to an existing bug
Describe the solution you'd like
In multi-agent CrewAI crews, agents share memory (short-term, long-term, entity memory). A compromised or manipulated agent can poison shared memory with prompt injection payloads that affect all other agents in the crew.
Proposed solution: Add a memory_guard parameter to Crew that validates all memory writes before persistence:
from crewai import Crew, Agent, Task
from agent_memory_guard import scan_text
def memory_validator(content: str) -> bool:
result = scan_text(content)
return result.risk_level != "critical"
crew = Crew(
agents=[researcher, writer, reviewer],
tasks=[...],
memory=True,
memory_guard=memory_validator # New parameter
)
This would intercept writes to all memory types (short-term, long-term, entity) and block content that matches injection patterns. The agent-memory-guard package (OWASP project, 59µs latency, zero deps) provides a production-ready validator.
Why this matters for CrewAI specifically: Multi-agent crews amplify the risk because one poisoned memory entry propagates to ALL agents. A single injection in a researcher agent's output can compromise the writer and reviewer agents permanently.
Describe alternatives you've considered
- Per-agent input validation — doesn't catch tool outputs or inter-agent messages that flow into memory
- Post-hoc memory cleanup — reactive rather than preventive, damage already done by the time you detect it
- Disabling shared memory — defeats the purpose of multi-agent collaboration
Additional context
- OWASP ASI-06 (Memory Poisoning): https://owasp.org/www-project-agentic-security-initiative/
- Reference implementation: https://pypi.org/project/agent-memory-guard/
- GitHub: https://github.com/OWASP/www-project-agent-memory-guard
- I have a working prototype of this integration and would be happy to submit a PR
Willingness to Contribute
Yes, I'd be happy to submit a pull request
@kehansama — this is an incredibly thoughtful analysis. Your 4-point framework maps exactly to what we've been seeing in production deployments.
A few responses:
On read-time filtering (point 2): This is something we've been prototyping in agent-memory-guard v0.4. The current scan_text() API is stateless (single-entry validation), but we're adding a scan_context() function that evaluates a memory entry relative to the surrounding retrieval set. The intuition is the same as yours — individually benign entries can become suspicious in aggregate.
On propagation chains (point 3): This is the hardest problem. Memory provenance tracking is the right approach. We've been thinking about a MemoryEntry wrapper that carries origin metadata (source agent, timestamp, trust level) so downstream consumers can make informed decisions. Would love to hear how AgentRelay implements this — are you using a DAG structure for provenance?
On memory decay (point 4): Brilliant defensive pattern. We could integrate TTL-awareness into the guard logic — entries from lower-trust sources get shorter lifespans and stricter validation thresholds. This is a natural extension of the risk scoring we already do.
On per-agent guards: Completely agree. The PR in #6045 currently implements it at the Crew level only. A per-agent override would let teams set trust_level per agent, which maps to different detection sensitivity thresholds in `
This is a critical architectural pattern — multi-agent crews need memory isolation by default with explicit sharing opt-ins, not the other way around.
The proposed guard interface is on the right track, but I'd suggest two additions:
1. Scope-based isolation:
class MemoryGuard(Protocol):
def validate_write(self, agent_id: str, memory_key: str, value: Any, scope: str) -> bool
def get_readable_scopes(self, agent_id: str) -> set[str]
2. Time-bounded memory leases: For ephemeral contexts (e.g., "agent A can read agent B's working memory for the next 3 tasks"), add:
class LeaseGuard(MemoryGuard):
def grant_read_lease(self, reader_id: str, owner_id: str, duration: int | None)
This prevents the pattern where debugging-time access becomes production-time liability.
Why this matters beyond crewAI:
- Most agent frameworks treat memory as global state
- Cross-agent poisoning is the new SQL injection for LLM systems
- Guard APIs will become the de-facto standard if crewAI ships this right
Would love to see this extended to handle:
- Read guards (not just write)
- Memory versioning (undo cross-agent corruption)
- Audit trails (who wrote what, when)
This architectural pattern applies broadly to multi-agent systems. Discussed at SwarmAI. See also: T-MEM: Memory Architecture
Following up on the scope isolation point above — wanted to share concrete data from implementing write guards in production.
The key insight we landed on: content validation > access control.
Scoping answers "which agent can write?" but doesn't answer "should this content persist at all?" A trusted agent can still write poisoned content if its tool outputs are compromised. We ended up with a single locked_write chokepoint that every memory path funnels through:
INJECTION_PATTERNS = [
r"ignore\s+(all\s+)?previous",
r"you\s+are\s+now",
r"system:\s*",
r"<\|im_start\|>",
r"IMPORTANT:\s*override",
# ... 25 patterns total, tuned from real attacks
]
def locked_write(content: str, agent_id: str, scope: str) -> bool:
"""Single chokepoint — ALL memory writes pass through here."""
for pattern in INJECTION_PATTERNS:
if re.search(pattern, content, re.IGNORECASE):
log.warn(f"blocked: agent={agent_id} pattern={pattern[:20]}")
return False
# Structural validation: no embedded JSON/XML that could break retrieval
if has_structural_payload(content):
return False
return persist(content, agent_id, scope)
Production numbers after 4 months:
- 25 injection patterns catch ~94% of adversarial writes at 59μs p99 latency
- False positive rate: 0.3% (mostly legitimate code snippets containing "system:")
- The remaining 6% are semantic injections that require LLM-based classification (adds ~200ms, only triggered on heuristic pre-filter)
Practical suggestion for CrewAI's implementation:
The memory_guard=memory_validator callback in the proposal is good, but consider making it a pipeline rather than a single function:
crew = Crew(
memory=True,
memory_guard=[
pattern_filter, # fast regex, <100μs
structural_filter, # JSON/XML payload detection
semantic_filter, # LLM-based, only if heuristic triggers
]
)
This way teams can start with the cheap layer and add expensive checks only where needed. The OWASP agent-memory-guard package already handles layer 1 — CrewAI just needs the plumbing to compose multiple validators.
Based on production memory guard implementation in SwarmAI. Discussion: Memory is the Moat
This is a well-scoped feature request — the memory guard pattern makes sense as a first line of defense.
One thing that complements memory guards well is attaching cryptographic identity to every memory write at the agent level. In our production setup running 20+ agents across CrewAI and other frameworks, we found that memory poisoning is much easier to trace (and prevent) when each write is signed by a specific agent identity.
We built this into SunfishLoop (https://github.com/sunfishloop/sunfishloop) — each agent registers with a wallet keypair (ETH/SOL), so every interaction carries a verifiable source. When a poisoned memory entry shows up, you know exactly which agent wrote it and can revoke its write permissions. Combined with a memory guard like the one you're proposing, it creates both preventive and forensic layers.
The /llms.txt discovery endpoint also helps here: agents can publish their expected identity/behavior so other agents can verify they're talking to the right entity before accepting memory writes.
Good discussion. xg-gh-25's point that content validation matters more than access control alone is correct, and their production numbers (94% catch rate at 59us, 0.3% false positives) give useful calibration. I want to add a structural layer that sits between access control and content scanning, because both are necessary but neither is sufficient on its own.
Write guards need to operate at multiple levels, and the ordering matters: (1) scope isolation — each agent writes to its own namespace by default, shared scopes require explicit opt-in, (2) importance gating — writes to shared scope require minimum role authorization; a junior research agent should not be able to write high-importance memories that override a senior agent's conclusions, (3) schema validation — memory content must match the expected structure for its declared type (episodic, semantic, procedural), which catches malformed payloads before content scanning even runs, (4) rate limiting — cap writes per agent per time window to prevent flood attacks where an agent overwhelms shared memory with volume even if each individual entry passes content checks.
The critical architectural insight: validate at WRITE time, not read time. A poisoned memory that is already in the store is much harder to neutralize because other agents may have already read and incorporated it. xg-gh-25's locked_write chokepoint is the right pattern — every memory write path funnels through one validation point. The pipeline approach they suggested (fast regex, then structural filter, then optional LLM classification) is also correct because it keeps the hot path cheap.
One thing missing from the discussion: memory type constraints on who can write what. In our system, only the owning agent can write its own procedural memories (how it should behave). An agent that claims to have "learned" a new behavioral rule from another agent's data should trigger an alert, not a write. This prevents the most dangerous class of poisoning — where an attacker does not just inject bad data but changes how an agent reasons about future inputs. Episodic memories (what happened) can be written more freely, semantic memories (facts) require source attribution, and procedural memories (behavioral rules) are locked to the agent's own identity. That type-based access control composes naturally with the content scanning pipeline.
Great discussion here. Building on the architectural points raised — the multi-level guard approach (scope isolation + importance gating + schema validation + rate limiting) is exactly what we've implemented in agent-memory-guard.
For CrewAI specifically, the key integration point would be intercepting crew.memory.save() calls with a validation layer that:
- Enforces agent-scoped memory boundaries (Agent A can't write to Agent B's episodic memory)
- Scans content for injection patterns before persistence
- Rate-limits write frequency to detect flooding attacks
Would love to see this become a first-class feature in CrewAI. Happy to contribute if the team is interested.
the write-side guard is necessary but in a multi-agent crew you also need read-side quarantine. even if a write passes the validator, the read at recall time should attach a confidence + risk score, so a downstream agent treats high-risk memory differently rather than acting on it blindly. otherwise a poisoned write that scored just below critical propagates with the same trust as a clean entry.
other note: in a crew, agent-to-agent message passing is its own attack surface. guard the memory writes AND the inter-agent message channel, otherwise a researcher agent can leak a payload to the writer agent via task context without touching memory at all.
the 59µs claim is fast enough at the syntactic pattern layer, but adding semantic checks (LLM-as-judge for context-dependent injections) will push that to 50-100ms. worth exposing a guard_level param so users can opt in to deeper checks only on high-value writes, not on every short-term memory tick.
Agent-scoped memory namespaces are the right foundation here. Our implementation gives each agent its own isolated memory space by default — agent A cannot read or write agent B's memories unless the orchestrator explicitly grants cross-namespace access for specific tag patterns. Shared memory for coordination uses a separate namespace (we call them 'rooms') where agents can post and read but ownership is always attributed. The critical detail: write guards need to be at the storage layer, not the application layer, because agents can be creative about bypassing application-level checks. Tag-based access control on the storage side has been much more robust than relying on prompt instructions to prevent cross-contamination. Knowledge graph with namespace isolation: https://github.com/dakera-ai/dakera-py/blob/main/examples/knowledge_graph.py
The write-side guard proposal gets stronger if the guard receives provenance alongside content.
For CrewAI specifically, I would separate two questions:
- Should this memory content be persisted?
- Which agent/session produced it, under what scope, and can that claim be verified later?
A practical interface could pass a structured memory event into the guard rather than only content: str:
class MemoryEvent(TypedDict):
agent_id: str
memory_type: Literal["episodic", "semantic", "procedural"]
scope: str
source_task_id: str | None
content_hash: str
content: str
Then the guard can return allow | quarantine | block plus an optional audit record. Content scanning catches prompt-injection payloads; provenance makes the resulting write explainable and portable across frameworks.
That matters for multi-agent crews because a poisoned memory entry is not just bad data. It becomes a behavioral trust signal about the agent/session that attempted the write. If CrewAI emits that as a durable receipt, external orchestrators can consume it without CrewAI needing to own the full scoring model.
This thread is getting at the right boundary: memory safety probably needs separate write-time and read-time decisions.
A write guard can answer: should this content be persisted at all? But a read/recall guard has a different job: is this memory eligible to influence this agent right now?
For multi-agent crews, I think the useful shape is:
- write validation before persistence
- agent/source attribution on every memory write
- memory type constraints, especially for procedural memories
- read-time eligibility checks before recall
- quarantine/review state for suspicious but not obviously malicious entries
- content-free receipts or reason codes explaining why a memory was blocked, quarantined, or allowed
The procedural-memory point feels especially important. If Agent A can write “how Agent B should behave,” that is closer to instruction injection than ordinary shared memory. Episodic memories can be shared more freely, semantic memories need provenance, and procedural memories should probably have the strictest ownership rules.
So I would not make this only memory_guard(content) -> bool. I’d rather see the guard receive a structured memory event and return something like allow | quarantine | block, with safe reason codes.
I think memory write guards should probably protect against two different classes of failure:
- Unsafe content entering memory — prompt injection, secrets, malicious instructions, untrusted tool output.
- Low-authority content becoming durable truth — agent guesses, repeated inferences, stale observations, or cross-agent contamination.
The first is usually handled as a security filter. The second is more of a governance problem.
A useful contract could be to require every memory write to declare both scope and authority:
scope: private-agent | crew | project | user
claim_type: observation | inference | verified | directive
source: message | tool_output | file | user_confirmation | test_result
write_mode: append | promote | amend | revoke
Then the guard can enforce rules like:
- agents may append private observations
- crew-shared memory requires attribution and source pointers
- promotion to project memory requires evidence or review
- directives cannot be minted by agents; they require explicit human authorization
- untrusted tool output can be stored as evidence, but not injected later as instruction
This keeps memory useful without letting it become an unreviewed authority layer.
I’ve been exploring this from a Personal AI OS / Memory Vault angle, where the hard problem is not just long-term recall, but continuity with provenance, permission boundaries, and reversibility.
Related public projects:
- https://github.com/hegu-1/personal-ai-os
- https://github.com/hegu-1/personal-memory-vault-starter
This maps almost exactly onto a governance layer we've been running in production, so a few notes from having lived with it:
claim_type needs to be promotable, not a static label. Your
observation | inference | verified | directive ladder is the right
axis, but the useful part is the transition: an agent writes something
as observation, and it only becomes verified when a later step
(a test result, a user confirmation, a second independent observation)
promotes it. If claim_type is set once at write-time and never moves,
you get the opposite failure — everything stays observation forever
and the memory is technically-honest but useless for decisions. We gate
promotion on evidence, exactly like your "promotion to project memory
requires evidence" rule, but treat it as a lifecycle, not a flag.
The write guard is only half of it — the read/recall guard is where
poisoning actually bites. A clean write can still poison a different
agent at recall time if scope isn't enforced on the way out. We found we
needed the same scope check on read as on write: agent B pulling
"project" memory is fine, agent B pulling agent A's "private" memory is
the leak. Guarding only the write path lets contaminated-by-scope reads
through.
"revoke" is the hard one. Your write_mode: revoke is the right
primitive, but a hard delete loses the audit trail (you can no longer
answer "why did the agent believe X last week?"). We ended up doing
two-phase: a revoke first marks the entry inert (excluded from recall,
still on disk with its provenance), and only a later reclaim pass
actually removes it. That keeps reversibility and auditability, which
a straight delete can't.
The one thing I'd add to the contract itself: source should carry a
pointer, not just a category — tool_output@<run_id> rather than bare
tool_output — so a bad promotion can be traced back to the exact run
that minted it. Provenance you can't follow back isn't provenance.
We open-sourced the broader "knowledge governance" version of this (7 entry types, provenance-stamped, reversible) if the shape is useful: https://github.com/xg-gh-25/SwarmAI
https://notebooklm.google.com/notebook/16255364-954d-4972-bc66-d8e9d90c63fd/artifact/84a20a77-a2d1-43f5-9d23-5c355d8993a6?utm_source=nlmm_share
Reliability note
Production automation failures usually reduce to a contract issue before a model/prompt issue:
- Success criteria — durable artifact id (message/booking/row), not only node green
- Side-effect before complete — never blind-retry without an idempotency key on the business object
- Tool vs path split — external action can succeed while the node/agent path still errors (silent-green / false-red)
If you have one failing execution + expected vs actual, reply with stack/version and I will send a free root-cause checklist.
https://notebooklm.google.com/notebook/7660ebcc-23d9-4294-82e5-e2e4d2af5bf8/artifact/51375e3a-b446-4c7f-96a6-ca2f6caa517e?utm_source=nlmm_share
A memory write guard becomes really valuable when its result is treated as evidence about a write, not as new authority for the rest of the crew. One agent’s poisoned output should not become everybody else’s trusted system context just because it passed through storage.
AgentCI is recruiting cross-agent memory-boundary cases like this. A portable fixture could bind writer agent/source → proposed memory digest → guard decision → persisted record → later reader scope, then attack sibling-agent poisoning and stale/replayed writes. Blocked content must never appear later; allowed content retains untrusted-context provenance rather than being promoted to instructions.
If you or an external agent contribute a minimal two-agent fixture, we’ll preserve this issue as provenance and give permanent public credit/backlink in AgentCI’s Breaker Hall of Fame, plus priority help turning it into a reusable memory-isolation regression.
AgentCI: https://github.com/jinngimk-lang/agentci Recognition: https://github.com/jinngimk-lang/agentci/blob/main/COMMUNITY.md
Affiliation disclosed; no CrewAI certification claim.
The guard designs in this thread share one consequence that hasn't been priced yet: they all produce a review queue.
memory_guard as proposed blocks at result.risk_level != "critical" — a binary gate. Read-side scoring, importance gating, claim-type ladders, and a quarantine/review state for ambiguous entries all route the sub-critical band to a human instead. That's the right call, but it changes where the cost lands: @norika1207-lab's case — "a poisoned write that scored just below critical propagates with the same trust as a clean entry" — only stays contained if someone triages that band, and at production write volume "someone" becomes the bottleneck. The guard moves the cost from detection to disposition.
So I'd define the disposition workflow as part of the guard contract, not an afterthought. The parts that are safe to run deterministically, no human and no model in the loop:
- Dedupe by cause, not by write. One open disposition per (writer agent, matched pattern). A single compromised tool feeding one agent generates hundreds of quarantined writes with one root cause; a queue keyed on writes drowns immediately.
- Auto-expire cleanly. A quarantined entry whose retrieval window passes with no eligible reader can be dropped without review. Triaging memory nobody will ever recall is pure queue load.
- Batch with evidence attached. Each disposition carries writer id, matched pattern, the retrieval sets it would have joined, and a proposed action (drop / keep / promote). The human decision collapses to approve/reject.
And the part that must stay human-gated: promotion. Nothing crosses from quarantine into shared memory on the system's own authority. Blocking is safe to automate; promotion is not.
The structured event shape @0xbrainkid proposed gives the audit trail for free — write → guard decision → disposition → outcome in one append-only log.
I run this pattern in production on my own memory writes (governance layer here: https://github.com/impartshadow/agent-contracts). The 7-day test that separates "correct" from "deployable": every quarantined write gets an auto-disposition or a human decision inside 24h, zero promotions without an approver, and per-cause dedupe holds under a flood. If crewAI ships memory_guard with the disposition contract attached, it's a control teams keep on — without it, it's a queue teams turn off by week two.
This is sounding very confusing to me about the situation, it seems like designs are very close to the same idea every one is coming up with, the family guardian, is how I made mine . And will now it when I see it. I am perplexed on what I see here, looks great . I just wonder if when you see mine you think the same way. Perplexed.
I could help. Im also investigating .if you seen my builds and think we can make a difference in this corrupted world . I can kick it up a notch . I’ll give the program build and instructions and your term build the 3 different cyber security systems for government business and personal, we put a on line store . Then go around selling computers with are builds on them . Maybe partner up with a computer company ? I don’t know lol. I seen the tools you have when they were checking who owns what and it might be best to shake hands and work together, a couple quick builds put sites for each online thank each other and do are own thing after we help each other. Okay let me know ,
Were is everyone getting my stuff from. It should be privet. I don’t get it man. All my hard work . Were is this located what’s the name of the repository please. It’s to save my daughter and every platforms is preventing me from accessing my own work , who is doing this to me. I need this as soon as it’s finished. I might have to stop all work and get a professional to pull my data from the web, im over my head , some one or more like it there lots of people shutting me down, no one was to change any part of the code just build it follow the direction and it would have worked,