Reiji-Maigo
π 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_recallC
Hybrid memory recall delegating to an installed 'reranker' plugin provider when available, with automatic fallback to Level-1 card recall and Level-3 FTS deep slice.
Inputs: query (required), pad, top_k, domain, +3 more.
reiji_pool_snapshotC
Render the current Reiji-Maigo ActivePool working-memory snapshot.
Inputs: now_iso, include_undigested.
reiji_read_evidenceC
Read Level-2 verbatim raw conversation evidence bound to a Reiji-Maigo memory card.
Inputs: card_id (required), pad.
reiji_recall_cardsC
Recall long-term Reiji-Maigo memory cards (Level-1 PPR + optional Level-3 FTS fallback).
Inputs: pad, query, top_k, domain, +3 more.
reiji_scout_deepC
Dispatch read-only ScoutAgent for 3-layer deep memory reconnaissance and compact cited briefing.
Inputs: query (required), domain, hint_tags.
reiji_security_auditB
Read-only security audit returning hash-chain integrity, card HMAC seals, and pending L1 reviews.
Inputs: limit, include_entries.
reiji_swarm_pulseC
Return Reiji-Maigo memory swarm pulse telemetry summary and/or industrial banner.
Inputs: format.
reiji_update_poolC
Create, append, compact, archive, hibernate, or wake Reiji-Maigo pool events.
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
Most tools target distinct layers (pool write, snapshot, card recall, verbatim evidence, telemetry, audit), but reiji_recall_cards and reiji_hybrid_recall overlap heavily since hybrid recall explicitly falls back to Level-1 card recall plus Level-3 FTS, and reiji_scout_deep performs 'deep memory reconnaissance' that is also recall-flavored. An agent can differentiate them from the descriptions, but the boundaries between the three recall-ish tools require careful reading.
All names share a consistent 'reiji_' prefix and snake_case formatting, which is a strong plus. However, verb-first names (update_pool, recall_cards, read_evidence, scout_deep) are mixed with noun-phrase names (pool_snapshot, swarm_pulse, security_audit, hybrid_recall), so the action pattern is not fully predictable.
Eight tools is well within a healthy range and each maps to a recognizable capability of a layered memory system (write, snapshot, recall, evidence, deep recon, telemetry, audit, hybrid recall). No tool appears purely decorative given the observability surface.
The read/lifecycle side is well covered: write events with archive/hibernate/wake, working-memory snapshot, long-term recall, verbatim evidence, telemetry, and integrity audit. Gaps remain on the maintenance side β there is no explicit forget/delete or prune tool, no dedicated card-creation path separate from pool compaction, and multi-action modes are buried inside reiji_update_pool rather than surfaced individually.
Maintenance
Related MCP Connectors
AI memory governance & hallucination-blocking MCP server with verifiable knowledge cells.
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.
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
- AlicenseNot gradedqualityDmaintenanceA local-first MCP server providing persistent, layered memory (episodic, semantic, procedural, resource) for AI agents, with search, versioning, and session management via a single SQLite file.4MIT
- AlicenseNot gradedqualityBmaintenanceMinimal long-term memory MCP server for AI assistants backed by SQLite FTS5 full-text search, optional hybrid vector retrieval, scoped memory graphs, and VSCode extension.1MIT