Reiji-Maigo
A zero-dependency local (stdio) MCP server that gives AI agents a two-tier working memory: short-term ActivePool memory plus a sealed, bitemporal long-term MemoryCard store with progressive recall, evidence reading, swarm telemetry, and security auditing.
Inspect working memory —
reiji_pool_snapshotreads the ActivePool short-term snapshot, active task chains, and (optionally) staged undigested turn notes, with an optional timestamp override for deterministic decay evaluation.Manage working-memory lifecycle —
reiji_update_poolcreate/append/touch/status/compact events, archive or hibernate them into sealed MemoryCards in one of five locked domains (proj/infra/research/companion/life), and wake hibernated cards back into ActivePool; non-destructive and append-only (no hard deletes).Natural-language long-term recall —
reiji_hybrid_recallfuses L2 tag projection, Level-1 Personalized PageRank and Level-3 CJK FTS5 slices via RRF; supports domain filters, tag boosts, top_k, and optional raw slice inclusion.Strict tag-based recall —
reiji_recall_cardsqueries sealed MemoryCards by explicit controlled tags with min_tag_hits, optional Level-3 FTS5 fallback, and context padding.Verbatim evidence —
reiji_read_evidencereturns the exact source turns bound to a card's SourceSpan (with configurable padding) for provenance/code-snippet verification.Deep multi-hop recon —
reiji_scout_deepdispatches the read-only ScoutAgent for a cited briefing, abstaining when ungrounded (requires a configured Flash model).Swarm & cost telemetry —
reiji_swarm_pulsereports Scribe/Scout/Archivist health, 7-decimal anti-MemoryTax ROI ledger metrics, and cold-vault counts (summary/banner/both).Security verification —
reiji_security_auditchecks the HMAC audit hash chain, MemoryCard HMAC-SHA256 seals, and pending L1 human-approval queue, optionally returning raw chain entries.Trust posture — all tools are read-only except the single pool-mutation tool; no open-world access, no network egress beyond local stdio/127.0.0.1, and a
--read-onlymode can hide mutating tools.
🔒 Zero-Trust Security Self-Verification (Audit in 3 Seconds)
Long-term memory is an AI agent's highest-value attack surface — a single prompt-injected tool output or accidentally stored API key can poison every future session. reiji-maigo enforces strict physical and cryptographic boundaries from line one:
Zero Third-Party Dependencies (
dependencies = []): The microkernel, SQLite WAL + CJK-BigramFTS5ledger,Personalized PageRankgraph engine, three-bee swarm, encrypted vault, and nativeStdio MCPserver run 100% on the Python>= 3.10standard library (plus native Win32ctypes) — zero externalpipsupply-chain risk.Zero Unprompted External Egress (
Stdio/127.0.0.1Only):reiji mcpoperates strictly over localstdin/stdoutpipes with zero open network ports;reiji servehard-enforces127.0.0.1(SO_EXCLUSIVEADDRUSEon Windows to prevent port hijacking), anti-DNS-rebindingHost/Originvalidation, and boundedReplayGuardrequest-ID protection;Outbound LLM calls occur only when you explicitly configure a Flash endpoint via
reiji vault set-flashor environment variables.
Four-Layer Zero-Trust Memory Armor (
reiji_maigo/security/):L1 Ingress Sanitizer (
sanitizer.py): Zero-latency scrubbing of PEM keys, PATs, Bearer tokens, and API keys; physical blindfolding of personal media directories and binary image/audio/video paths; andORIGIN_TRUST_LEVELS(user_verified/assistant/untrusted_external) blocking untrusted tool outputs from mutating authoritative memory;L2 Tamper-Evident Hash Chain & Approval Gate (
audit_gate.py): Every sensitive action is appended to anHMAC-linked audit chain; high-risk overwrites/revocations on protected domains enter anL0/L1/L2human-approval queue;L3 Encrypted Credential Vault & Anti-Bomb Bundles (
vault.py): Credentials rest inside Win32DPAPIor POSIX0600encrypted storage; everyMemoryCardcarries a domain-separatedHMAC-SHA256seal (card_seals), and portable archives enforceZIP_STOREDanti-zip-bomb verification.
3-Second Source Audit Command:
# PowerShell — inspect every network, subprocess, socket, and bind-address call across the package:
Get-ChildItem .\reiji_maigo -Recurse -Filter *.py | Select-String -Pattern "HTTPConnection|urlopen|subprocess|socket|0\.0\.0\.0|shell=True"# Linux / macOS
grep -rnE "HTTPConnection|urlopen|subprocess|socket|0\.0\.0\.0|shell=True" ./reiji_maigoRelated MCP server: coord-mem MCP Server
✨ Design Philosophy: Breaking the Two Traps of 2026 Agent Memory
Named after the Midnight Lost Child (零时迷子) — the treasure tool that fully restores its bearer's vessel every night at the stroke of midnight — reiji-maigo is engineered to escape the two failure modes plaguing modern agent memory:
Trap 1: Flat
MEMORY.mdFiles & In-Place System-Prompt Edits (MemGPTstyle) — Mutating the system block shatters yourL0Prompt KV Cache on every write. Worse, once a codebase undergoes multiple architectural pivots, superseded drafts accumulate alongside final decisions in flat context, causing frontier model accuracy to collapse below no-memory baselines (TEPA/MemDelta).Trap 2: Heavy Vector + Graph DBs + Online Per-Turn Rewriting — Requiring Docker, vector stores, graph servers, and embedding APIs introduces severe
MemoryTax: burning tens of thousands of extra tokens and multi-second TTFT overhead online just to save a few hundred tokens of context, resulting in negative net ROI.
Reiji-Maigo takes a third path: keep the online hot path zero-blocking and 100% prefix-cache-locked, while offloading distillation, chain compaction, and bitemporal conflict resolution to an isolated three-bee Flash swarm and midnight curation:
Dimension | Flat | Heavy Vector + Graph DB Stack | Reiji-Maigo (零时迷子) |
Runtime Dependencies | None, but unstructured & unindexed | Docker + Vector DB + Graph DB + Embeddings |
|
Storage Engine | Fragile plain text, unbounded growth | Multi-service cluster, painful backups | Single-File SQLite WAL + CJK FTS5 + 15-Line PPR |
L0 Prefix KV Cache | ❌ Shattered on every header edit | ⚠️ Frequent dynamic top-of-prompt misses | ✅ |
Pivots & Retractions | ❌ Stale drafts linger & confuse attention | ❌ Cosine similarity blends old & new truths | ✅ |
Anti-Hallucination | ❌ Lossy summaries, jokes treated as fact | ❌ Decontextualized chunks, ungrounded claims | ✅ Banter Gate + |
Cost Transparency | Untracked | Hidden token bloat & negative | ✅ |
Poisoning & Integrity | Plaintext, vulnerable to web/tool injection | Lacks origin-trust tiers & card signatures | ✅ 4-Layer Zero-Trust Armor + |
🧪 Candid Author's Note: Why Zero Dense Vectors Yet & Early-Stage Status
Zero Dense Vectors by Choice (and Honesty):
Right now,
reiji-maigouses zero dense vector embeddings — no Chroma, no Qdrant, no FAISS, and no external embedding APIs. Retrieval runs purely on deterministic CJK-BigramFTS5+ ControlledL2Tag Projection (MeMo) + 15-LinePersonalized PageRank+RRF.Why? First, pure cosine similarity over dense vectors is notoriously hard to control and debug when superseded drafts and active decisions share nearly identical wording. Second — to be completely upfront — I haven't mastered the failure modes of dense-vector retrieval deeply enough yet to feel comfortable baking an opaque black box into the core kernel.
Instead of bolting on vector tech I don't fully control just for buzzwords,
ReijiKernelkeeps the core 100% deterministic and exposes a cleanregister_providers("reranker", ...)plugin slot — so optional dense/hybrid embedding rerankers can be mounted externally in the future without touching a single line of the microkernel.
First Exploratory Prototype (
v0.2— Not the Final Form):Treat this release as an early-stage experimental prototype (Generation 1) built to test these architectural hypotheses under real daily workloads. Prompt heuristics, decay thresholds, and plugin boundaries will evolve significantly once real longitudinal telemetry comes in — this is our starting line of exploration, not a finished monument.
🧭 Full-Pipeline Architecture
Front-Row Working Memory ·
ActivePool(reiji_maigo/pool/): Bounded prefrontal working memory featuring 4D Zeigarnik unfinished-task retention decay and lossless-span chain compaction (condensing old steps while preserving 100% ofSourceSpanturn coordinates).Back-Row Bitemporal Archive ·
CardStore+MemoRRF(reiji_maigo/cards/&plugins/hybrid_reranker.py):Enforces 5 locked L1 domains (
proj/infra/research/companion/life) and an anti-entropy controlled L2 tag dictionary;Four-Level Page-Fault Recall Ladder:
Level 0zero-mount banter bypass ➔Level 1MeMocontrolled-tag projection +PPRmulti-hop graph diffusion +RRFhybrid fusion ➔Level 2verbatimSourceSpanturn slicing ➔Level 3CJK-BigramFTS5deep search with automaticpending_backfillssleep self-healing;Built-in
Foresighttemporal expiry demotion ([EXPIRED_FORESIGHT]) andMemDreamsleep self-probing that automatically backfills missed colloquial synonyms into tag aliases.
Headless Three-Bee Swarm (
reiji_maigo/swarm/): Each worker operates inside a physically isolated capability proxy (Capabilities) under aSHA-256byte-lockedL0system prefix:🐝
ScribeAgent: Debounced async worker filtering banter, resolving pronouns, updatingActivePool, and staging granular notes inpool_event_notes(physically barred from mutatingCardStore);🐝
ScoutAgent: Strictly read-only capability sandbox (PermissionErroron any write) executing 3-drawer progressive reconnaissance with mandatory honest abstention when ungrounded;🐝
ArchivistAgent: Midnight curator dropping transientmicronoise, compacting long quest chains, minting 3-layerMemoryCardentries, resolvingTEPAconflicts, and drainingLevel 3backfills.
flowchart TB
subgraph Entry["Zero-Coupling Host Bridges (MCP / CLI / Companion / Star-Panel)"]
CLI["CLI Entrypoint (reiji)"]
MCP["Dual-Frame Stdio MCP (reiji mcp)"]
CompBridge["Companion Host Bridge (shinobu.py Tail Tools & Hooks)"]
PanelBridge["Desktop Star-Panel Bridge (star_panel.py Deck & L1 Review)"]
end
subgraph Security["Four-Layer Zero-Trust Armor (reiji_maigo/security)"]
Sanitizer["L1 Ingress Sanitizer (Secret Scrub / Media Blindfold / Origin Trust)"]
AuditGate["L2 Audit & Approval Gate (HMAC Hash Chain & L0/L1/L2 Review)"]
Vault["L3 Encrypted Vault (DPAPI/0600 Secrets & Anti-Bomb Bundles)"]
Loopback["L4 Loopback Guard (127.0.0.1 / Anti-Rebinding / ReplayGuard)"]
end
subgraph Kernel["Microkernel & Two-Tier Memory Core (ReijiKernel + ReijiMemoryEngine)"]
Pool["Front-Row ActivePool (Zeigarnik Decay / Lossless Compaction)"]
Cards["Back-Row CardStore (SQLite WAL + CJK FTS5 + PPR + TEPA)"]
L0Lock["100% L0 Prefix Cache Lock (SHA-256 Lock & EnSIMem SourceSpan)"]
end
subgraph Swarm["Headless Three-Bee Swarm (SwarmCoordinator & Pulse Telemetry)"]
Scribe["ScribeAgent (Debounced Queue / Banter Gate / Coref)"]
Scout["ScoutAgent (Read-Only Sandbox / 3-Drawer Recon / Abstention)"]
Archivist["ArchivistAgent (Midnight Curation / TEPA Override / Backfill)"]
end
subgraph Plugins["7 Built-In Toggleable Plugins (entry_points: reiji_maigo.plugins)"]
ROI["roi_ledger (7-Decimal Anti-MemoryTax Ledger)"]
Epoch["epoch_vault (Bidirectional SHA-256 Cold Vault)"]
Thermal["thermal_sync (250s Cache Warmth & 200K Cliff Radar)"]
CompInst["companion (Cross-Process Locked Reversible Installer)"]
Rerank["hybrid_reranker (MeMo + RRF + Foresight + MemDream)"]
Importer["bootstrap_importer (Idempotent 3-Source Cold-Start Importer)"]
Bench["bench_harness (6-Dimensional Adversarial Benchmark)"]
end
CLI --> Sanitizer
MCP --> Sanitizer
CompBridge --> Sanitizer
PanelBridge --> Loopback
Loopback --> AuditGate
Sanitizer --> Pool
Sanitizer --> AuditGate
AuditGate --> Cards
Cards --> Vault
Pool <--> Scribe
Pool --> Archivist
Archivist --> Cards
Cards <--> Scout
Cards <--> Rerank
L0Lock --- Cards
L0Lock --- Scout
Scribe -.-> ROI
Scout -.-> ROI
Archivist -.-> Epoch
Pool -.-> Thermal
Importer -.-> Pool
Bench -.-> Scout
CompBridge -.-> CompInst🚀 60-Second Quick Start
1. Install & Inspect (Zero External Dependencies)
Requires Python 3.10+ with zero third-party packages:
git clone https://github.com/zanex-dev/reiji-maigo.git
cd reiji-maigo
pip install -e . --no-depsCheck kernel health, loaded plugins, and the industrial swarm pulse banner (data defaults to ~/.reiji_maigo, overridable via REIJI_MAIGO_HOME):
reiji status
reiji swarm statusAppend a sanitized turn and run progressive + hybrid recall:
reiji turn --episode ep-demo --role user --content "Standardize on SQLite WAL mode with zero external vector databases."
reiji recall --query "SQLite WAL"
reiji rerank recall "external vector databases"2. Native reiji mcp for AI IDEs & Agents (Antigravity · Claude Code · Cursor)
reiji mcp auto-negotiates both NDJSON and Content-Length framing over stdio, exposing 8 tail-mounted tools and 3 read-only resources without touching your frozen system prompt prefix.
Generate an exact interpreter-bound MCP snippet in one command:
reiji companion mcp-config --jsonOr add reiji-maigo directly to your client's MCP configuration (append "--read-only" to physically hide mutating tools):
{
"mcpServers": {
"reiji-maigo": {
"command": "reiji",
"args": ["mcp"],
"env": {
"REIJI_MAIGO_HOME": "~/.reiji_maigo"
}
}
}
}3. reiji import Idempotent Cold-Start Ingestion
Eliminate day-one empty-memory cold starts by importing existing stage handoffs, transcript.jsonl logs, or legacy SQLite stores (with automatic secret scrubbing, media blindfolding, and SHA-256 fingerprint deduplication):
# Import Markdown handoff checkpoints (*.md) and mint HMAC-sealed seed MemoryCards
reiji import checkpoints ./workspace/.agents/checkpoints --domain proj
# Import JSONL transcripts or read-only legacy SQLite conversation databases
reiji import transcript ./session.jsonl
reiji import sqlite ./legacy_memory.db4. reiji bench run Six-Dimensional Adversarial Scorecard
Validate single_hop, multi_hop, temporal_foresight, tepa_reversal (3-step A -> B -> A' cascading override), abstention, and anti_poison_banter in an isolated sandbox:
# Zero-cost deterministic regression (<0.1s isolated sandbox verification)
reiji bench run --markdown
# Live evaluation against your encrypted Flash endpoint
reiji vault set-flash --base-url https://api.example.com/v1 --api-key sk-xxx --model gemini-2.5-flash
reiji bench run --mode live --markdown🛠️ CLI & Toggleable Plugin Matrix
Core Microkernel Commands (9)
Command | Purpose | Common Subcommands / Example |
| Kernel status, schema version, storage counts & security summary |
|
| Inspect hot |
|
| Level 1–3 progressive recall ( |
|
| Append a sanitized raw turn into the |
|
| Orchestrate Scribe/Scout/Archivist & render pulse telemetry |
|
| Verify tamper-evident hash chain, card HMAC seals & |
|
| Manage |
|
| Run |
|
| Launch zero-dependency dual-frame Stdio MCP server |
|
Built-In Self-Bootstrapping Plugins (7 · Individually Toggleable)
Plugin | CLI Command | Subcommands | Capability |
|
|
| 7-decimal USD anti- |
|
|
| Bidirectional |
|
|
| Win32 lock-free 16KB tail reader & |
|
|
| Cross-process locked, corrupt-backup-safe hook/skill installer |
|
|
|
|
|
|
|
|
|
|
| 6-dimensional adversarial memory benchmark & Markdown scorecard |
Environment Variables & Bare-Kernel Switches
Variable | Default | Description |
|
| Root directory for SQLite WAL database, audit chain & vault |
|
| Set |
| (empty) | Comma/semicolon-separated plugin opt-out list (e.g. |
|
| Custom directory for the append-only cold epoch vault |
|
| Target config directory override for |
📜 License & Commercial Authorization
Released under the PolyForm Noncommercial License 1.0.0 (official text):
Free for Noncommercial Use: Personal study, individual developer workflows, academic research, educational institutions, public research organizations, and non-profit charities.
Commercial Use Requires Prior Written Authorization: Any commercial deployment, enterprise internal production use, paid product integration, or commercial SaaS hosting requires prior written authorization from the author.
Copyright (c) 2026 zanex — Commercial use requires prior written authorization from the author.
Available Tools
8 toolsreiji_hybrid_recallARead-onlyIdempotent
Primary natural-language long-term memory search fusing controlled L2 tag projection, Level-1 Personalized PageRank, and Level-3 CJK-Bigram FTS5 slices via Reciprocal Rank Fusion (MemoRRF). Prefer this first for general recall; use reiji_recall_cards for strict tag-only filtering, reiji_read_evidence for full verbatim turn context, or reiji_scout_deep for multi-hop synthesis.
Inputs: query (required), pad, top_k, domain, +3 more.
reiji_pool_snapshotARead-onlyIdempotent
Read the current ActivePool short-term working-memory snapshot and active task chains. Call at session start or before calling reiji_update_pool; to search archived long-term memory cards instead, use reiji_hybrid_recall.
Inputs: now_iso, include_undigested.
reiji_read_evidenceARead-onlyIdempotent
Fetch the Level-2 verbatim raw conversation turns bound to a specific MemoryCard ID via its immutable SourceSpan coordinates. Use after reiji_hybrid_recall or reiji_recall_cards when exact historical wording, code snippets, or provenance verification are needed.
Inputs: card_id (required), pad.
reiji_recall_cardsARead-onlyIdempotent
Query long-term sealed MemoryCards by explicit controlled tags (Level-1 Personalized PageRank) with optional Level-3 FTS5 fallback. Use this when exact domain/tag filters are already known; prefer reiji_hybrid_recall for open-ended natural-language queries, and follow up with reiji_read_evidence to inspect verbatim source turns.
Inputs: pad, query, top_k, domain, +3 more.
reiji_scout_deepARead-onlyIdempotent
Dispatch the read-only ScoutAgent to execute multi-hop 3-drawer memory reconnaissance and synthesize a cited briefing (returning abstained=true when ungrounded). Use only for complex cross-episode questions where single-pass reiji_hybrid_recall is insufficient; requires a configured Flash model runner.
Inputs: query (required), domain, hint_tags.
reiji_security_auditARead-onlyIdempotent
Run a read-only zero-trust security verification over the tamper-evident HMAC audit hash chain, MemoryCard HMAC-SHA256 seals, and pending L1 human-approval queue. Use to detect tampering or check blocked high-risk memory mutations; for swarm throughput and ROI metrics, use reiji_swarm_pulse.
Inputs: limit, include_entries.
reiji_swarm_pulseARead-onlyIdempotent
Read operational health telemetry for the three-bee memory swarm (Scribe, Scout, Archivist), 7-decimal anti-MemoryTax ROI ledger metrics, and cold-vault counts. Use to inspect background curation status or token ROI; to verify cryptographic integrity and L1 approvals, use reiji_security_audit instead.
Inputs: format.
reiji_update_poolA
Manage the non-destructive lifecycle of ActivePool working-memory events: 'create' a new event (requires title, step, span), 'append' a progress step (requires event_id, step, span), 'touch' retention timestamp (requires event_id), update 'status' (requires event_id, status), 'compact' older steps losslessly (requires event_id, checkpoint_summary), 'archive' or 'hibernate' an event into a sealed long-term MemoryCard (requires event_id, domain), or 'wake' a hibernated card back into ActivePool (requires card_id, step, span). By zero-trust append-only design, sealed cards are superseded via archiving rather than hard-deleted.
Inputs: action (required), span, step, tags, +10 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
The four memory-retrieval tools (hybrid_recall, recall_cards, read_evidence, scout_deep) sit in the same neighborhood, but each description states a clear routing rule (natural language first, strict tags, verbatim evidence, multi-hop synthesis). Similarly, swarm_pulse vs security_audit and pool_snapshot vs update_pool are explicitly cross-referenced to prevent misselection. Only minor residual overlap between hybrid_recall and recall_cards keeps this from a 5.
All names share a consistent reiji_ prefix and snake_case formatting with no camelCase drift. However, verb style varies: update_pool, recall_cards, read_evidence use verb_noun, while pool_snapshot, hybrid_recall, swarm_pulse, security_audit, scout_deep are noun-based, so the action is not predictable from the name alone.
Eight tools is well within the ideal range and each one covers a distinct layer: working-memory lifecycle, long-term recall, evidence inspection, deep reconnaissance, telemetry, and security verification. No tool appears redundant or vestigial.
The working-memory lifecycle is fully covered (create, append, touch, status, compact, archive/hibernate, wake) plus long-term query, provenance, telemetry, and audit paths, with deliberate no-hard-delete semantics. Minor gaps remain: there is no direct tool to inspect a single card's metadata or to configure the Flash model runner that scout_deep requires, and no export/maintenance operation.
Maintenance
Related MCP Connectors
CellMath is a governed AI memory and knowledge-cell MCP server designed to stop context bloat, unverified memory drift, and agent hallucinations. Instead of dumping raw, noisy RAG chunks into every turn, CellMath organizes persistent agent knowledge into structured, isolated Knowledge Cells with causal graph edges and strict write-time governance—keeping the full 3-tool MCP schema ultra-compact (~1,200 tokens). Core 3-Tool Pipeline: • vault_access — Read-only lookup, cell hydration, and graph edge traversal with strict zero-match silence (never fabricates context when no verified cell exists). • verify_safety — Preflight security and policy gate that blocks destructive or unsafe operations before execution. • vault_commit — Governed state mutation (store, update, causal edges, session checkpoints, and 4-tier purge) enforcing source provenance. Built for Claude, Cursor, ChatGPT, Gemini, and autonomous agents over Streamable HTTP.
MCP server for Memanto - persistent semantic memory for any MCP-compatible agent
Self-hosted AI workspace: semantic RAG document search, long-term memory, and AI chat via MCP.
Private-by-default, local-first memory/context/task orchestrator for MCP apps and agents.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA pure SQLite structured long-term memory MCP server for AI agents, featuring adaptive Ebbinghaus forgetting curves, hierarchical memory tiers, trust feedback, and anomaly detection—all fully offline with deterministic scoring.MIT
- AlicenseNot gradedqualityDmaintenanceMemory-palace graph MCP server for AI agent memory, exposing memory_add / get / like / record_window / walk / retrieve / neighbors / rooms / misshelved / rehome operations over a zero-dependency, append-only, provenance-tracking knowledge graph with decay, PMI-derived adjacency, and spatial coordinates.MIT
- AlicenseBqualityBmaintenanceEvidence-governed coding agent memory and knowledge lifecycle MCP server for DeepSeek Harness (DSH), OpenAI Codex, and Google Antigravity. Provides local SQLite FTS5 + semantic hybrid retrieval, automatic session/compaction checkpointing, counter-example demotion, and a hard 1,200-char context budget guardrail with zero third-party Python dependencies.111MIT

KruschStackofficial
AlicenseCqualityBmaintenanceA local SQLite-backed MCP server that gives AI coding agents persistent cross-session memory and invariants, Turn-0 workspace grounding with spin-loop and output-defect guards, and two-phase-commit staging so file edits are audited and applied atomically. It also exposes AST symbol/call-graph search, bounded page memory, and workspace document retrieval, letting agents work safely across sessions without any cloud dependency.39317 npm3MIT