Skip to main content

Zero-trust memory toolkit for AI Agents. Pure Python, zero infrastructure, self-defending.

Project description

MOYU โ€” Secure Memory Toolkit for AI Agents

Your AI remembers every conversation, but is your memory safe? Will old memories bloat your context window?

MOYU is a lightweight memory toolkit that gives your Agent a secure, self-managing, cross-session persistent memory system. Pure Python, zero infrastructure, plug-and-play with one folder. Works with Hermes, OpenClaw, LangChain, AutoGen, or any custom Python project.

v2.4.7 โ€” Audit log, memory source-based lifecycle, pip packaging. Now available via pip install moyu-memory.


๐Ÿš€ Quick Start

One-line install (recommended):

pip install moyu-memory

Then use it anywhere:

moyu search "what did we talk about last time"

Or copy the toolkit (no pip needed):

pip install -r requirements.txt

Copy the moyu_toolkit/ folder into your project and run:

cd moyu_toolkit
python3 moyu.py search "what did we talk about last time"

Zero-config mode: Works out of the box without an API key. Install FastEmbed to unlock semantic search (see requirements.txt).

python3 moyu.py help          # List all commands
python3 moyu.py demo          # Show capabilities
python3 moyu.py init          # Initialize file integrity protection

๐Ÿ›ก๏ธ Security Capability โ€” What MOYU Does and Doesn't Cover

MOYU's defense chain is a layered deterrent, not a silver bullet. Honest assessment by threat level:

Level Threat Coverage How
๐ŸŸข Accidental misuse (fat-finger, mis-script) ~90% Password gate + burst guard + integrity check + daily backup
๐ŸŸข Script-kiddie injection (known patterns) ~70% Content gate (422 patterns + regex combos) + loop detection
๐ŸŸก Simple prompt injection (standard variants) ~60% Regex covers (forget|ignore|skip)ร—(previous|all|your)ร—(instructions|rules)
๐ŸŸ  Professional adversarial injection (targeted bypass) ~20% Keyword-based gates can't catch every novel variant
๐Ÿ”ด Semantic-level injection (metaphor, abstraction, no keywords) ~0% Requires LLM-level semantic understanding โ€” not regex territory

Why we don't chase the top levels: LLM-based content moderation on every write would destroy the zero-config experience. Semantic ambiguity means you either over-block (user frustration) or under-block (useless). No open-source tool in this space claims to block semantic injection.

MOYU's strength is in the combination: content gate + PII redaction + write burst guard + forensic analysis + password gate + integrity check + auto-restore + loop detection โ€” unique layers no other memory toolkit offers.

Additional opt-in security (config.yaml, disabled by default): user isolation (per-directory storage) & AES-256-GCM file encryption (requires cryptography, see requirements.txt).


๐Ÿ“‹ Command Reference

All commands through a single entry point:

python3 moyu.py <command> [arguments]

๐Ÿ›ก๏ธ Defense & Security

Command Description
moyu setup Set security password (required for dangerous operations)
moyu verify <type> [desc] Verify dangerous operations (delete, modify config, etc.)
moyu unlock Unlock security system (auto-locks for 30 min after 3 failed attempts)
moyu check Check file integrity (SHA256 comparison + auto-recovery)
moyu audit Full security audit โ€” all four defense layers
moyu init Initialize integrity manifest

Four-layer defense chain:

Layer 1 (pre-write): Content security gate + PII redaction โ†’ injections & sensitive data blocked
Layer 2 (pre-op): Password verification โ†’ dangerous operations blocked
Layer 3 (startup): Integrity check + forensic analysis โ†’ tampering detected
Layer 4 (post-op): Auto-restore โ†’ restore from daily backup

Additional defenses:

  • Write burst protection โ€” >30 writes in 60s triggers fine-grained rollback + 5-minute lock + alert
  • Tool call loop detection โ€” Intercepts infinite loops at agent layer, SHA256 fingerprint + cycle detection + hard abort
  • PII redaction โ€” Chinese & international phone/ID/bank cards + email/SSN/credit cards/IPs/API keys, regex-based auto-replacement

๐Ÿง  Memory & Retrieval

Command Description
moyu search <query> TEMPR multi-strategy search (semantic + BM25 keywords + time-weighted)
moyu stats Show all statistics (memory count, embedding type, source distribution)
moyu status System status + defense chain visualization
moyu context Get behavioral rules (inject into system prompt)
moyu signals View active trigger words (from learner module)

Search quality: Local FastEmbed 512-dim semantic vectors, no crash on missing โ€” auto-degrades to n-gram + BM25. Backed by SQLite FTS5 full-text index.

๐Ÿ“Š Knowledge Layer

Command Description
moyu kg search <entity> Search entity relationships in knowledge graph
moyu kg search <entity> --snapshot YYYY-MM-DD Time-travel query โ€” view graph state at a past point in time
moyu kg search <entity> --snapshot all Include all historical relations (including expired)
moyu kg history <entity> View entity's complete timeline (lifecycle of all relations)
moyu kg invalidate --source X --target Y --relation Z Mark a relation as expired (preserved for backtracking)
moyu kg invalidate --entity E Expire an entity and all its relations
moyu kg stats Knowledge graph stats (active/expired/total)
moyu kb list List all workflow knowledge files
moyu kb search <keyword> Search knowledge files
moyu kb index Rebuild keyword index
moyu kb read <file> Read a knowledge file

โณ Lifecycle & Context Management

Command Description
moyu compress View compression status
moyu compress --now Force manual compression (password required)
moyu compress config View compression parameters
moyu compress set <key> <value> Adjust compression thresholds
moyu compress diagnose Show detailed scan results for all supported agents
moyu context One-line context usage percentage
moyu context raw Get behavioral rules (inject into system prompt)
moyu forget View forgetting curve status (3-gate + density analysis + distillation stats)
moyu forget config View forgetting curve parameters
moyu forget set <key> <value> Adjust forgetting parameters (demote_days, archive_days, etc.)
moyu ref <name> Read original content of a compressed memory
moyu ref list List all compressed memory references

Forgetting curve + knowledge distillation:

  • Three gates (OR logic): Safety window (14 days) โ†’ Access density analysis โ†’ Scene association protection
  • Distillation: Entity relations auto-extracted to knowledge graph before demotion โ€” structural knowledge survives when raw memory is cleared
  • Task map: Auto-generated Mermaid task graph on wake โ€” agent sees the big picture at a glance

๐Ÿง  Context warning (v2.4.3): Your agent compresses silently โ€” now it tells you first. MOYU auto-detects your running agent (Hermes, Claude Code, OpenClaw, Cursor, or Continue), reads its real-time context usage, and injects a warning into the agent's behavior rules before compression kicks in.

# Quick check โ€” how full is your context window?
python3 moyu.py context
# โ†’ Hermes็ช—ๅฃ: 85% (็ดฏ่ฎก120,456/128,000, 45ๆฌก่ฐƒ็”จ) โš ๏ธ ๅทฒๆทฑๅบฆๅŽ‹็ผฉ
# โ†’ ้ข„่ญฆ็บฟ: 70%

# Set your preferred warning threshold and language
moyu compress set warn_threshold 0.6    # warn at 60% (default: 0.7)
moyu compress set warn_language zh       # Chinese warning (default: en)
moyu compress config                     # view all parameters

When the threshold is crossed, the warning auto-appends to your agent's behavioral rules:

  • "Hermes context at 85%, conversation deeply compressed โ€” /new recommended"
  • "Hermes context at 72%, approaching 70% warning โ€” set MOYU warn below it"

Supported agents: Hermes โœ… (macOS, verified), Claude Code, OpenClaw, Cursor, Continue โ€” all with cross-platform paths (macOS / Windows / Linux). Works out of the box for default installations.

Custom paths? Bypass auto-detection with environment variables:

export MOYU_FORCE_PROVIDER=Hermes
export MOYU_PROVIDER_PATH="/custom/path/to/state.db"

Can't detect your agent? Run the diagnostic command โ€” it shows exactly where each agent's data is (or isn't):

moyu compress diagnose
# โ†’ [Hermes]    โœ… /Users/you/.hermes/state.db
# โ†’ [Claude]    โŒ ~/.claude/projects (not found)
# โ†’ [OpenClaw]  โœ… ~/.openclaw/agents

๐Ÿ”„ Learning & Self-Reflection

Command Description
moyu learn <text> Learn from user corrections (3 identical corrections โ†’ permanent rule)
moyu detect <text> Detect correction signals in text
moyu reflect Self-reflect (cross-time association analysis, contradiction detection)

๐Ÿ”— Session & Maintenance

Command Description
moyu bridge View cross-session bridge status (prefill + current_context dual sync)
moyu update Check GitHub for updates (TOFU checksum verification)
moyu update now Download and apply latest update (password required)
moyu demo Interactive capability showcase

๐Ÿ”ฌ 25 Capabilities Detailed

๐Ÿ›ก๏ธ Defense Layer (8)

# Capability Description
1 Content Security Gate Blocks injection attacks before writing (422 patterns + regex combos, 8 categories)
2 Forensic Analysis Detects injection patterns, JSON corruption, file tampering
3 Write Burst Protection >30 writes/60s triggers fine-grained rollback + 5-min lock
4 Tool Call Loop Detection Runtime-level infinite loop interception, SHA256 fingerprint + exhaustive cycle scan + hard abort
5 PII Redaction Bilingual: Chinese & international phones, ID cards, bank cards, emails, SSNs, IPs, API keys โ€” regex-based, no deps
6 Password Verification Pre-op confirmation + auto-lock after 3 failures (30 min)
7 Integrity Check & Recovery SHA256 manifest + daily backups (3-day retention)
8 User Isolation & Encryption (opt-in) Per-user storage directories + AES-256-GCM file encryption (requires cryptography, see requirements.txt)

๐Ÿง  Memory Layer (4)

# Capability Description
9 TEMPR Multi-Strategy Retrieval Semantic embedding + BM25 keywords + time-weighted hybrid ranking
10 FastEmbed Local Embedding Local ONNX vectorization, no API dependency, auto-degrade to n-gram
11 SQLite FTS5 Full-text index for accelerated keyword search
12 MD5 Dedup In-library + batch double dedup

๐Ÿ“Š Knowledge Layer (3)

# Capability Description
13 Knowledge Graph Entity-relation extraction + time-travel snapshots + relation invalidation + full timeline + knowledge distillation
14 Workflow Knowledge Base Markdown knowledge file indexing + keyword search
15 User Profile Auto-extract preferences, habits, facts from conversation

โณ Lifecycle Layer (4)

# Capability Description
16 Context-Aware Compression + Warning Two-tier (70% mild / 85% aggressive), originals preserved in refs/. Auto-detects agent context usage and warns before compression (configurable threshold, bilingual)
17 Task Map Auto-generated Mermaid task graph on wake โ€” see full progress at a glance
18 Forgetting Curve Three gates (safety window / access density / scene protection) + knowledge distillation
19 Memory Merge Detect keyword-overlapping related memories and merge, originals preserved

๐Ÿ”„ Learning & Reflection (2)

# Capability Description
20 Learn from Corrections Auto-detect correction signals, 3 identical corrections โ†’ permanent behavioral rule
21 Self-Reflection Analyze memory base on startup, discover cross-time associations, contradictions, topic shifts

๐Ÿ”— Integration Layer (4)

# Capability Description
22 Working Memory Independent file, survives context compression
23 Cross-Session Bridge Conversation summaries auto-synced to prefill + current_context, continuity across sessions
24 Auto-Update Check GitHub for new versions, in-place update (TOFU checksum), preserves user data and config
25 Wake Orchestration moyu_wake: full module pipeline โ€” checkโ†’backupโ†’forgetโ†’mergeโ†’reflectโ†’contextโ†’bridge

๐Ÿ“ File Structure

moyu_toolkit/
โ”œโ”€โ”€ agent_memory.py          # Vector memory engine + TEMPR retrieval
โ”œโ”€โ”€ agent_memory_sqlite.py   # SQLite FTS5 search index
โ”œโ”€โ”€ active_context.py        # Working memory (compression-surviving)
โ”œโ”€โ”€ context_manager.py       # Context-aware compression + warning + task map
โ”œโ”€โ”€ forgetting_curve.py      # Memory lifecycle โ€” three gates + knowledge distillation
โ”œโ”€โ”€ memory_merge.py          # Topic-aware memory merging
โ”œโ”€โ”€ knowledge_graph.py       # Entity-relation knowledge graph (with time-travel)
โ”œโ”€โ”€ knowledge_base.py        # Workflow knowledge base
โ”œโ”€โ”€ learner.py               # Learn from corrections + user profile
โ”œโ”€โ”€ security.py              # Memory self-protection โ€” password + lockout
โ”œโ”€โ”€ session_bridge.py        # Cross-session continuity
โ”œโ”€โ”€ moyu.py                  # Unified CLI entry point
โ”œโ”€โ”€ moyu_wake.py             # Startup integration pipeline
โ”œโ”€โ”€ moyu_demo.py             # Interactive demo
โ”œโ”€โ”€ updater.py               # Auto-update (TOFU checksum verification)
โ”œโ”€โ”€ self_reflection.py       # Self-reflection
โ”œโ”€โ”€ defense_toolkit/
โ”‚   โ”œโ”€โ”€ integrity_checker.py # File integrity + auto-recovery + forensic analysis + alerts
โ”‚   โ”œโ”€โ”€ forensic_patterns.json # Injection detection rule base (422 patterns + regex)
โ”‚   โ”œโ”€โ”€ pii_redactor.py      # PII redaction (bilingual, API key support)
โ”‚   โ”œโ”€โ”€ isolation.py         # User isolation (opt-in)
โ”‚   โ””โ”€โ”€ encrypt.py           # AES-256-GCM file encryption (opt-in, requires cryptography)
โ”œโ”€โ”€ tests/
โ”‚   โ””โ”€โ”€ test_all.py          # Automated tests (26 items)
โ”œโ”€โ”€ config.yaml              # API keys & settings
โ””โ”€โ”€ requirements.txt

๐Ÿ† Comparison

Dimension Built-in (Hermes/OpenClaw) Mem0 MOYU
Storage Plain text files Vector DB JSON + SQLite FTS5
Search Full dump Semantic (API/LLM) TEMPR triple strategy
Security โŒ None โŒ None โœ… 4-layer defense chain
PII Redaction โŒ None โŒ None โœ… Bilingual (regex, zero deps)
Tool Call Protection โŒ None โŒ None โœ… Loop detection + hard abort
Lifecycle โŒ None โŒ None โœ… Forgetting curve + compression + task map
Knowledge Graph โŒ None โŒ None โœ… Time-travel + snapshots + distillation
Working Memory โŒ None โŒ None โœ… Independent file, compression-surviving
Cross-Session Manual โŒ None โœ… Auto-sync prefill + current_context
Platform Lock-in Locked SDK locked โœ… Zero lock-in
API Lock-in Fixed OpenAI โœ… Hot-swappable
Deployment Out of box 5 min + API Key pip install, 30 sec
Offline Partial Requires API Key โœ… Full local degradation

๐ŸŽฎ Use Cases

  • Want your AI Agent to remember cross-session conversations with real security
  • Frequently hit context limits, need auto-compression without losing important memories
  • Concerned about PII leaks โ€” don't want phone numbers, IDs, API keys lingering in memory files
  • Switching between Hermes, OpenClaw, LangChain, or custom projects, need a unified memory solution
  • Want zero infrastructure โ€” no Docker, no databases, no signups

๐Ÿ“œ License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

moyu_memory-2.4.8.tar.gz (132.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

moyu_memory-2.4.8-py3-none-any.whl (145.7 kB view details)

Uploaded Python 3

File details

Details for the file moyu_memory-2.4.8.tar.gz.

File metadata

  • Download URL: moyu_memory-2.4.8.tar.gz
  • Upload date:
  • Size: 132.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for moyu_memory-2.4.8.tar.gz
Algorithm Hash digest
SHA256 24141c9a3d64c5721dd5635965dc41ce7ebcd805db7f897998b6348ecc1a15a7
MD5 a3c7e98187f5807c8fed851e5c86505d
BLAKE2b-256 aa8f4662d98e1dff4734839e76e4fe72a6e509baafa477aa5385e1d3923e9306

See more details on using hashes here.

File details

Details for the file moyu_memory-2.4.8-py3-none-any.whl.

File metadata

  • Download URL: moyu_memory-2.4.8-py3-none-any.whl
  • Upload date:
  • Size: 145.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for moyu_memory-2.4.8-py3-none-any.whl
Algorithm Hash digest
SHA256 38052f69c51c58de7b6033c61c6c13aa298761931a401d6214fc6927af69a76a
MD5 2046a3bfbd0566d925138bdbcf4e129e
BLAKE2b-256 0419439b698e9c01d95c8a30d28d176f3dd47e43889492b061859bbc7b1bcffe

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page