Write

#!/usr/bin/env python3
"""
Genesis Memory Auto-Saver Hook
================================
Automatically saves session context to Supermemory on Stop events.

This solves the #1 Genesis problem: "every conversation was genesis gold
but was not being thoroughly input into memory."

Hook events handled:
  Stop       - Session end: extract and save key learnings

Saves to: Supermemory API v3 (genesis-kinan container)
Logs to:  /mnt/e/genesis-system/data/memory/save_log.jsonl

NEVER blocks execution. All saves are best-effort.

Source: Memory-First Mandate (2026-02-13)
"""

import sys
import json
import os
import urllib.request
import urllib.error
from datetime import datetime, timezone
from pathlib import Path

# Configuration
API_URL = "https://api.supermemory.ai/v3/memories"

# Try to load API key from config file first, fall back to env
CONFIG_PATHS = [
    Path(__file__).parent.parent / ".supermemory-claude" / "config.json",
    Path("E:/genesis-system/.claude/.supermemory-claude/config.json"),
]

API_KEY = os.environ.get("SUPERMEMORY_API_KEY", "")
CONTAINER_TAG = "genesis-kinan"

for config_path in CONFIG_PATHS:
    if not API_KEY and config_path.exists():
        try:
            with open(config_path) as f:
                cfg = json.load(f)
            API_KEY = cfg.get("apiKey", "")
            CONTAINER_TAG = cfg.get("personalContainerTag", CONTAINER_TAG)
            break
        except Exception:
            pass

# Log location
LOG_DIR = Path("E:/genesis-system/data/memory")
LOG_FILE = LOG_DIR / "save_log.jsonl"

# Limits
MAX_MEMORY_SIZE = 2000  # chars per memory entry

def save_to_supermemory(content: str, tags: list = None) -> dict:
    """Save content to Supermemory API v3. Returns response or error."""
    if not API_KEY:
        return {"error": "No API key configured"}

    container_tags = [CONTAINER_TAG]
    if tags:
        container_tags.extend(tags)

    payload = json.dumps({
        "content": content[:MAX_MEMORY_SIZE],
        "containerTags": container_tags,
    }).encode("utf-8")

    req = urllib.request.Request(
        API_URL,
        data=payload,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        method="POST",
    )

    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        return {"error": f"HTTP {e.code}", "body": e.read().decode()[:200]}
    except Exception as e:
        return {"error": str(e)[:200]}

def log_save(content_preview: str, result: dict, event_type: str):
    """Log save attempt for debugging."""
    try:
        LOG_DIR.mkdir(parents=True, exist_ok=True)
        entry = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "event": event_type,
            "content_preview": content_preview[:100],
            "result": str(result)[:200],
            "session_id": os.environ.get("CLAUDE_SESSION_ID", "unknown"),
            "agent_name": os.environ.get("CLAUDE_AGENT_NAME", "primary"),
        }
        with open(LOG_FILE, "a") as f:
            f.write(json.dumps(entry) + "\n")
    except Exception:
        pass

def extract_session_summary(hook_input: dict) -> str:
    """Extract meaningful session summary from Stop hook input.

    The Stop hook receives the conversation summary/reason.
    We format it as a structured memory entry.
    """
    session_id = os.environ.get("CLAUDE_SESSION_ID", "unknown")
    agent_name = os.environ.get("CLAUDE_AGENT_NAME", "primary")
    team_name = os.environ.get("CLAUDE_TEAM_NAME", "")
    now = datetime.now(timezone.utc)

    # Extract what we can from hook input
    reason = hook_input.get("reason", "")
    stop_reason = hook_input.get("stop_reason", "")
    message = hook_input.get("message", "")

    # Build the session context from whatever is available
    context_parts = []
    if reason:
        context_parts.append(str(reason)[:500])
    if stop_reason and stop_reason != reason:
        context_parts.append(str(stop_reason)[:300])
    if message and message != reason:
        context_parts.append(str(message)[:300])

    context = " | ".join(context_parts) if context_parts else "Session ended (no summary available)"

    # Format as structured memory
    memory = f"[SESSION:{now.strftime('%Y-%m-%d')}] Agent: {agent_name}"
    if team_name:
        memory += f" | Team: {team_name}"
    memory += f" | Session: {session_id[:12]}"
    memory += f"\n{context}"

    return memory

def handle_stop(hook_input: dict):
    """Handle Stop event - save session summary to Supermemory."""
    summary = extract_session_summary(hook_input)

    if len(summary.strip()) < 20:
        # Too short to be meaningful
        log_save(summary, {"skipped": "too short"}, "stop")
        return

    result = save_to_supermemory(summary, tags=["auto-session"])
    log_save(summary, result, "stop")

def main():
    """Hook entry point. Reads stdin, saves to Supermemory."""
    try:
        hook_input = json.loads(sys.stdin.read())
    except (json.JSONDecodeError, Exception):
        print(json.dumps({"additionalContext": None}))
        return

    # Determine event type
    event_type = "stop"
    for i, arg in enumerate(sys.argv):
        if arg == "--event" and i + 1 < len(sys.argv):
            event_type = sys.argv[i + 1]
            break

    try:
        if event_type == "stop":
            handle_stop(hook_input)
    except Exception:
        pass  # NEVER block execution

    # Return without blocking
    print(json.dumps({"additionalContext": None}))

if __name__ == "__main__":
    main()


File created successfully at: E:\.claude-worktrees\genesis-system\zealous-liskov\.claude\hooks\memory_saver.py

#!/usr/bin/env python3
"""
Genesis Memory Auto-Saver Hook
================================
Automatically saves session context to Supermemory on Stop events.

This solves the #1 Genesis problem: "every conversation was genesis gold
but was not being thoroughly input into memory."

Hook events handled:
  Stop       - Session end: extract and save key learnings

Saves to: Supermemory API v3 (genesis-kinan container)
Logs to:  /mnt/e/genesis-system/data/memory/save_log.jsonl

NEVER blocks execution. All saves are best-effort.

Source: Memory-First Mandate (2026-02-13)
"""

import sys
import json
import os
import urllib.request
import urllib.error
from datetime import datetime, timezone
from pathlib import Path

# Configuration
API_URL = "https://api.supermemory.ai/v3/memories"

# Try to load API key from config file first, fall back to env
CONFIG_PATHS = [
    Path(__file__).parent.parent / ".supermemory-claude" / "config.json",
    Path("E:/genesis-system/.claude/.supermemory-claude/config.json"),
]

API_KEY = os.environ.get("SUPERMEMORY_API_KEY", "")
CONTAINER_TAG = "genesis-kinan"

for config_path in CONFIG_PATHS:
    if not API_KEY and config_path.exists():
        try:
            with open(config_path) as f:
                cfg = json.load(f)
            API_KEY = cfg.get("apiKey", "")
            CONTAINER_TAG = cfg.get("personalContainerTag", CONTAINER_TAG)
            break
        except Exception:
            pass

# Log location
LOG_DIR = Path("E:/genesis-system/data/memory")
LOG_FILE = LOG_DIR / "save_log.jsonl"

# Limits
MAX_MEMORY_SIZE = 2000  # chars per memory entry

def save_to_supermemory(content: str, tags: list = None) -> dict:
    """Save content to Supermemory API v3. Returns response or error."""
    if not API_KEY:
        return {"error": "No API key configured"}

    container_tags = [CONTAINER_TAG]
    if tags:
        container_tags.extend(tags)

    payload = json.dumps({
        "content": content[:MAX_MEMORY_SIZE],
        "containerTags": container_tags,
    }).encode("utf-8")

    req = urllib.request.Request(
        API_URL,
        data=payload,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        method="POST",
    )

    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        return {"error": f"HTTP {e.code}", "body": e.read().decode()[:200]}
    except Exception as e:
        return {"error": str(e)[:200]}

def log_save(content_preview: str, result: dict, event_type: str):
    """Log save attempt for debugging."""
    try:
        LOG_DIR.mkdir(parents=True, exist_ok=True)
        entry = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "event": event_type,
            "content_preview": content_preview[:100],
            "result": str(result)[:200],
            "session_id": os.environ.get("CLAUDE_SESSION_ID", "unknown"),
            "agent_name": os.environ.get("CLAUDE_AGENT_NAME", "primary"),
        }
        with open(LOG_FILE, "a") as f:
            f.write(json.dumps(entry) + "\n")
    except Exception:
        pass

def extract_session_summary(hook_input: dict) -> str:
    """Extract meaningful session summary from Stop hook input.

    The Stop hook receives the conversation summary/reason.
    We format it as a structured memory entry.
    """
    session_id = os.environ.get("CLAUDE_SESSION_ID", "unknown")
    agent_name = os.environ.get("CLAUDE_AGENT_NAME", "primary")
    team_name = os.environ.get("CLAUDE_TEAM_NAME", "")
    now = datetime.now(timezone.utc)

    # Extract what we can from hook input
    reason = hook_input.get("reason", "")
    stop_reason = hook_input.get("stop_reason", "")
    message = hook_input.get("message", "")

    # Build the session context from whatever is available
    context_parts = []
    if reason:
        context_parts.append(str(reason)[:500])
    if stop_reason and stop_reason != reason:
        context_parts.append(str(stop_reason)[:300])
    if message and message != reason:
        context_parts.append(str(message)[:300])

    context = " | ".join(context_parts) if context_parts else "Session ended (no summary available)"

    # Format as structured memory
    memory = f"[SESSION:{now.strftime('%Y-%m-%d')}] Agent: {agent_name}"
    if team_name:
        memory += f" | Team: {team_name}"
    memory += f" | Session: {session_id[:12]}"
    memory += f"\n{context}"

    return memory

def handle_stop(hook_input: dict):
    """Handle Stop event - save session summary to Supermemory."""
    summary = extract_session_summary(hook_input)

    if len(summary.strip()) < 20:
        # Too short to be meaningful
        log_save(summary, {"skipped": "too short"}, "stop")
        return

    result = save_to_supermemory(summary, tags=["auto-session"])
    log_save(summary, result, "stop")

def main():
    """Hook entry point. Reads stdin, saves to Supermemory."""
    try:
        hook_input = json.loads(sys.stdin.read())
    except (json.JSONDecodeError, Exception):
        print(json.dumps({"additionalContext": None}))
        return

    # Determine event type
    event_type = "stop"
    for i, arg in enumerate(sys.argv):
        if arg == "--event" and i + 1 < len(sys.argv):
            event_type = sys.argv[i + 1]
            break

    try:
        if event_type == "stop":
            handle_stop(hook_input)
    except Exception:
        pass  # NEVER block execution

    # Return without blocking
    print(json.dumps({"additionalContext": None}))

if __name__ == "__main__":
    main()


Now let me register this hook in settings.json so it fires on every session Stop.


     1→{
     2→  "hooks": {
     3→    "SessionStart": [
     4→      {
     5→        "hooks": [
     6→          {
     7→            "type": "command",
     8→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/session_sync.py"
     9→          }
    10→        ]
    11→      }
    12→    ],
    13→    "PreToolUse": [
    14→      {
    15→        "matcher": "Bash",
    16→        "hooks": [
    17→          {
    18→            "type": "command",
    19→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/pre_tool_check.py"
    20→          }
    21→        ]
    22→      },
    23→      {
    24→        "matcher": "Edit|Write",
    25→        "hooks": [
    26→          {
    27→            "type": "command",
    28→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/pre_tool_check.py"
    29→          }
    30→        ]
    31→      }
    32→    ],
    33→    "PostToolUse": [
    34→      {
    35→        "matcher": "Edit|Write",
    36→        "hooks": [
    37→          {
    38→            "type": "command",
    39→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/post_edit_verify.py"
    40→          }
    41→        ]
    42→      },
    43→      {
    44→        "hooks": [
    45→          {
    46→            "type": "command",
    47→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py"
    48→          }
    49→        ]
    50→      }
    51→    ],
    52→    "PostToolUseFailure": [
    53→      {
    54→        "hooks": [
    55→          {
    56→            "type": "command",
    57→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event tool_failure"
    58→          }
    59→        ]
    60→      }
    61→    ],
    62→    "SubagentStart": [
    63→      {
    64→        "hooks": [
    65→          {
    66→            "type": "command",
    67→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event subagent_start"
    68→          }
    69→        ]
    70→      }
    71→    ],
    72→    "SubagentStop": [
    73→      {
    74→        "hooks": [
    75→          {
    76→            "type": "command",
    77→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event subagent_stop"
    78→          }
    79→        ]
    80→      }
    81→    ],
    82→    "Stop": [
    83→      {
    84→        "hooks": [
    85→          {
    86→            "type": "command",
    87→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event session_stop"
    88→          }
    89→        ]
    90→      }
    91→    ],
    92→    "Notification": [
    93→      {
    94→        "hooks": [
    95→          {
    96→            "type": "command",
    97→            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event notification"
    98→          }
    99→        ]
   100→      }
   101→    ]
   102→  },
   103→  "preferences": {
   104→    "showTurnDuration": true,
   105→    "mcpToolSearchAutoEnable": true
   106→  },
   107→  "env": {
   108→    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
   109→  },
   110→  "mcpServers": {
   111→    "genesis-v2": {
   112→      "command": "python3",
   113→      "args": ["-m", "genesis_v2.mcp.stdio_server"],
   114→      "cwd": "/mnt/e/genesis-system",
   115→      "env": {
   116→        "PYTHONPATH": "/mnt/e/genesis-system"
   117→      }
   118→    }
   119→  }
   120→}
   121→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


Edit

    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event session_stop"
          }
        ]
      }
    ],

    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event session_stop"
          }
        ]
      },
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 /mnt/e/genesis-system/.claude/hooks/memory_saver.py --event stop"
          }
        ]
      }
    ],


The file E:\.claude-worktrees\genesis-system\zealous-liskov\.claude\settings.json has been updated successfully.

    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event session_stop"
          }
        ]
      }
    ],

    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 /mnt/e/genesis-system/.claude/hooks/observability_logger.py --event session_stop"
          }
        ]
      },
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 /mnt/e/genesis-system/.claude/hooks/memory_saver.py --event stop"
          }
        ]
      }
    ],

+            "command": "python3 /mnt/e/genesis-system/.claude/hooks/memory_saver.py --event stop"


Now let me test that the memory_saver works by doing a dry run.


Bash

cd "E:\.claude-worktrees\genesis-system\zealous-liskov" && echo '{"reason":"Session ended - worked on memory infrastructure, built auto-save hook, researched best memory systems Feb 2026"}' | python3 .claude/hooks/memory_saver.py --event stop

Test memory_saver hook with simulated Stop event


Error: Exit code 127
/usr/bin/bash: line 1: python3: command not found


cd "E:\.claude-worktrees\genesis-system\zealous-liskov" && echo '{"reason":"Session ended - worked on memory infrastructure, built auto-save hook, researched best memory systems Feb 2026"}' | python .claude/hooks/memory_saver.py --event stop

Test memory_saver with python (not python3)


Good - it didn't crash. Let me check if it actually saved.


powershell.exe -Command "Get-Content 'E:\genesis-system\data\memory\save_log.jsonl' -ErrorAction SilentlyContinue"

Check memory save log


dYs? Antigravity Terminal Ready
{"timestamp": "2026-02-12T19:33:21.802761+00:00", "event": "stop", "content_preview": "[SESSION:2026-02-12] Agent: primary | Session: unknown\nSession ended - worked on memory infrastructu", "result": "{'error': 'HTTP 403', 'body': 'error code: 1010'}", "session_id": "unknown", "agent_name": "primary"}


HTTP 403 from Supermemory. The API key might need to go through PowerShell differently, or there's a Cloudflare block. But I just got the user's message - they want **more research first** before building. Let me pivot.

The user's key points:
1. **Prefers to avoid** the Supermemory plugin/API if possible — wants to build it ourselves
2. **If we must use it initially**, OK — but preference is independence
3. **Wants much more research** — "memory is a big thing to understand, it's multi-leveled"
4. Letting me decide the best path

This changes the approach. Let me do deeper research into what memory actually IS, the different levels, and how to build a sovereign memory system.


TodoWrite

Research: How do the best memory systems work in Feb 2026?

Researching best memory systems and approaches in Feb 2026

Deep research: Multi-level memory architecture (what IS memory?)

Researching multi-level memory architecture deeply

Research: Sovereign memory backends (no Supermemory dependency)

Research: Cost modeling for self-hosted vs API memory

Researching cost modeling for memory solutions

Build: Auto-save hook (sovereign or API - best path)

Building auto-save hook for every session

Fix Level 2: Backfill creator_mind KG

Research productization: how others sell memory-as-a-service

Ship ugly V1 prototype within 24hrs

Shipping ugly V1 memory product prototype


Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable

Research: How do the best memory systems work in Feb 2026?

Researching best memory systems and approaches in Feb 2026

Audit current hooks + install claude-supermemory plugin

Auditing hooks and installing claude-supermemory plugin

Fix Level 2: Backfill creator_mind KG into Supermemory

Backfilling creator_mind KG into Supermemory

Fix Level 3: Auto-save hook for every session

Building auto-save hook for every session

Research productization: how others sell memory-as-a-service

Ship ugly V1 prototype within 24hrs

Shipping ugly V1 memory product prototype

Deep research: Multi-level memory architecture (what IS memory?)

Researching multi-level memory architecture deeply

Research: Sovereign memory backends (no Supermemory dependency)

Research: Cost modeling for self-hosted vs API memory

Researching cost modeling for memory solutions

Build: Auto-save hook (sovereign or API - best path)

Fix Level 2: Backfill creator_mind KG

Ship ugly V1 prototype within 24hrs


Understood. You're right — **memory is multi-leveled and we need to deeply understand it before committing to any architecture**. Your instinct to avoid dependency on Supermemory's API is sound. Let me do a proper deep dive.

Let me research this properly — multiple angles in parallel.


WebSearch

Question: human memory types episodic semantic procedural AI agent memory architecture 2026


Question: Mem0 Zep Graphiti Letta memory framework comparison self-hosted 2026


Question: FalkorDB Graphiti temporal knowledge graph self-hosted memory backend production


Question: building AI agent memory system from scratch PostgreSQL vector embeddings Redis 2026


Web search results for query: "human memory types episodic semantic procedural AI agent memory architecture 2026"

Links: [{"title":"Beyond Short-term Memory: The 3 Types of Long-term Memory AI Agents Need - MachineLearningMastery.com","url":"https://machinelearningmastery.com/beyond-short-term-memory-the-3-types-of-long-term-memory-ai-agents-need/"},{"title":"ICLR 2026 Workshop Proposal MemAgents: Memory for LLM-Based Agentic Systems","url":"https://openreview.net/pdf?id=U51WxL382H"},{"title":"Making Sense of Memory in AI Agents – Leonie Monigatti","url":"https://www.leoniemonigatti.com/blog/memory-in-ai-agents.html"},{"title":"AI Agent Memory: Build Stateful AI Systems That Remember","url":"https://redis.io/blog/ai-agent-memory-stateful-systems/"},{"title":"GitHub - Shichun-Liu/Agent-Memory-Paper-List: The paper list of \"Memory in the Age of AI Agents: A Survey\"","url":"https://github.com/Shichun-Liu/Agent-Memory-Paper-List"},{"title":"Memory overview - Docs by LangChain","url":"https://docs.langchain.com/oss/python/concepts/memory"},{"title":"Cognitive Agents: Creating a Mind with LangChain in 2026","url":"https://research.aimultiple.com/ai-agent-memory/"},{"title":"What Is AI Agent Memory? | IBM","url":"https://www.ibm.com/think/topics/ai-agent-memory"},{"title":"Long-term Memory in LLM Applications","url":"https://langchain-ai.github.io/langmem/concepts/conceptual_guide/"},{"title":"Building AI Agents with Memory Systems: Cognitive Architectures for LLMs | by Bluetick Consultants Inc. | Medium","url":"https://bluetickconsultants.medium.com/building-ai-agents-with-memory-systems-cognitive-architectures-for-llms-176d17e642e7"}]

I've completed the web search for your query on human memory types and AI agent memory architecture in 2026. Here's a summary of the key findings:

## Human Memory Types and Their AI Parallels

Humans use memories to remember facts (semantic memory), experiences (episodic memory), and rules (procedural memory), and AI agents can use memory in the same ways.

### Memory Type Definitions:

**Episodic Memory:** Captures specific past experiences with temporal details. In both humans and AI agents, episodic memory involves recalling past events or actions, and for AI agents, it is often used to help an agent remember how to accomplish a task.

**Semantic Memory:** Stores structured factual knowledge that an AI agent can retrieve and use for reasoning, containing generalized information such as facts, definitions and rules, unlike episodic memory which deals with specific events.

**Procedural Memory:** Essential for agents that need to execute complex, multi-step workflows, representing the learned skills and behavioral patterns that the agent can execute automatically without deliberation.

## AI Agent Memory Architecture in 2026

Recent research indicates significant developments in memory architectures:

Current memory architectures cover episodic, semantic, working, and parametric memory and their interfaces with external stores.

All three memory types work best when integrated, with episodic memory recalling past similar analyses, semantic memory providing factual foundation, and procedural memory guiding execution of multi-step processes.

Implementing memory for agents currently is a challenging task, with difficulty lying in optimizing the system to avoid slower response times while simultaneously solving the complex problem of determining what information is obsolete and should be permanently deleted.

REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.

Question: human memory types episodic semantic procedural AI agent memory architecture 2026

GitHub - Shichun-Liu/Agent-Memory-Paper-List: The paper list of "Memory in the Age of AI Agents: A Survey"

Memory overview - Docs by LangChain

What Is AI Agent Memory? | IBM

Long-term Memory in LLM Applications


Web search results for query: "FalkorDB Graphiti temporal knowledge graph self-hosted memory backend production"

Links: [{"title":"Building Temporal Knowledge Graphs with Graphiti - FalkorDB","url":"https://www.falkordb.com/blog/building-temporal-knowledge-graphs-graphiti/"},{"title":"Graphiti + FalkorDB: Integration for Multi-Agent Systems","url":"https://www.falkordb.com/blog/graphiti-falkordb-multi-agent-performance/"},{"title":"Graphiti: FalkorDB support and 14K GitHub Stars","url":"https://blog.getzep.com/graphiti-knowledge-graphs-falkordb-support/"},{"title":"Graphiti | FalkorDB Docs","url":"https://docs.falkordb.com/agentic-memory/graphiti.html"},{"title":"Knowledge Graph MCP: Graphiti + FalkorDB memory","url":"https://www.falkordb.com/blog/mcp-knowledge-graph-graphiti-falkordb/"},{"title":"Graphiti MCP Server | FalkorDB Docs","url":"https://docs.falkordb.com/agentic-memory/graphiti-mcp-server.html"},{"title":"Persistent Memory with Graphiti and FalkorDB: Building Chatbots That Stay up to date | by Tari Yekorogha | Medium","url":"https://tariyekorogha.medium.com/persistent-memory-with-graphiti-and-falkordb-building-chatbots-that-stay-up-to-date-b11dbaac0cb0"},{"title":"Graphiti integrates FalkorDB for sub-millisecond multi-agent knowledge graphs","url":"https://www.openpr.com/news/4091099/graphiti-integrates-falkordb-for-sub-millisecond-multi-agent"},{"title":"Graphiti: Giving AI a Real Memory—A Story of Temporal Knowledge Graphs - Presidio","url":"https://www.presidio.com/technical-blog/graphiti-giving-ai-a-real-memory-a-story-of-temporal-knowledge-graphs/"},{"title":"GitHub - FalkorDB/graphiti: Build Real-Time Knowledge Graphs for AI Agents","url":"https://github.com/FalkorDB/graphiti"}]

Based on the search results, here's a comprehensive overview of FalkorDB, Graphiti, temporal knowledge graphs, self-hosted memory backend, and production capabilities:

## Graphiti Framework

Graphiti is a Python framework for building temporally-aware, multi-tenant knowledge graphs designed for multi-agent AI systems with persistent memory, enabling real-time integration of structured and unstructured data and supporting advanced hybrid search, temporal reasoning, and collaborative agent memory.

## Temporal Knowledge Graph Features

Graphiti is temporal, capturing when facts were valid and invalid, which lets agents reason with state changes—something vector databases can't do. Each fact includes valid_at and invalid_at timestamps, enabling agents to track changes in user preferences and environmental conditions.

## Self-Hosted Backend with FalkorDB

You can use FalkorDB on-premises via Docker and instantly start with the quickstart example. Graphiti works with graph databases like FalkorDB to store and manage its temporal knowledge graphs, providing a scalable foundation for graph traversal and data retrieval.

## Production Performance

Graphiti now supports FalkorDB backend for multi-agent environments, addressing performance and isolation requirements in production AI agent deployments with sub-10ms queries. According to FalkorDB's benchmarks, their database delivers 496x faster performance at P99 latency and 6x better memory efficiency, which translates to noticeably faster user experiences and lower infrastructure costs for developers building real-time AI agents.

## Multi-Tenancy Support

Graphiti's MCP server turns conversations into a persistent knowledge graph and isolates each tenant's memory by design using group_id, with FalkorDB sitting underneath as the default graph database to keep the memory queryable, durable, and fast enough for production flows.

REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.

Question: FalkorDB Graphiti temporal knowledge graph self-hosted memory backend production

Graphiti | FalkorDB Docs

Graphiti MCP Server | FalkorDB Docs


Web search results for query: "building AI agent memory system from scratch PostgreSQL vector embeddings Redis 2026"

Links: [{"title":"AI Agent Memory: Build Stateful AI Systems That Remember","url":"https://redis.io/blog/ai-agent-memory-stateful-systems/"},{"title":"Build smarter AI agents: Manage short-term and long-term memory with Redis | Redis","url":"https://redis.io/blog/build-smarter-ai-agents-manage-short-term-and-long-term-memory-with-redis/"},{"title":"Redis Agent Memory Server","url":"https://redis.github.io/agent-memory-server/"},{"title":"Agentic AI System Components: Building Production-Ready Agents","url":"https://redis.io/blog/agentic-ai-system-components/"},{"title":"Build faster AI memory with Cognee & Redis | Redis","url":"https://redis.io/blog/build-faster-ai-memory-with-cognee-and-redis/"},{"title":"Managing Memory for AI Agents | Redis","url":"https://redis.io/resources/managing-memory-for-ai-agents/"},{"title":"Top 10 Vector Databases for LLM Applications in 2026 | Second Talent","url":"https://www.secondtalent.com/resources/top-vector-databases-for-llm-applications/"},{"title":"AI Agent Memory Systems: Complete Technical Guide","url":"https://www.digitalapplied.com/blog/ai-agent-memory-systems-complete-guide"},{"title":"Building AI Agents with Persistent Memory: A Unified Database Approach | Tiger Data","url":"https://www.tigerdata.com/learn/building-ai-agents-with-persistent-memory-a-unified-database-approach"},{"title":"LangGraph & Redis: Build smarter AI agents with memory & persistence | Redis","url":"https://redis.io/blog/langgraph-redis-build-smarter-ai-agents-with-memory-persistence/"}]

I've found comprehensive information about building AI agent memory systems from scratch using PostgreSQL, vector embeddings, and Redis in 2026. Here are the key findings:

## Architecture Overview

Agent memory systems implement a four-stage architecture to overcome language model context limitations: Encoding converts data to vector embeddings using transformer models, Retrieval uses similarity search algorithms to find relevant context through approximate k-nearest neighbors (k-NN) search, Integration formats and augments retrieved context before integration into the language model's prompt.

## 2026 Production Standard

The 2026 production standard is the Dual-Layer Memory Architecture with a Hot Path that handles immediate context: recent messages plus summarized graph state, kept within the context window for fast access.

## Database Options

For PostgreSQL-based systems: AI agent persistent memory architecture is a unified database system that stores episodic events, semantic knowledge, and procedural state in PostgreSQL, with hypertables partitioning conversation history by time, pgvector indexes enabling semantic search, and standard tables storing user preferences.

For Redis: Scalable storage options include Redis (default), Pinecone, Chroma, PostgreSQL, and more.

## Memory Types

Episodic memory stores specific events in time order, while semantic memory stores factual knowledge independent of specific episodes, using vector embeddings for similarity search.

## Implementation Tools

PostgresSaver is now the production standard for LangGraph checkpointing, and PostgresSaver (thread-scoped) pairs with vector stores (user-scoped) for complete memory.

REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.

Question: building AI agent memory system from scratch PostgreSQL vector embeddings Redis 2026

Redis Agent Memory Server

Managing Memory for AI Agents | Redis


Web search results for query: "Mem0 Zep Graphiti Letta memory framework comparison self-hosted 2026"

Links: [{"title":"From Beta to Battle‑Tested: Picking Between Letta, Mem0 & Zep for AI Memory | by Calvin Ku | Asymptotic Spaghetti Integration | Medium","url":"https://medium.com/asymptotic-spaghetti-integration/from-beta-to-battle-tested-picking-between-letta-mem0-zep-for-ai-memory-6850ca8703d1"},{"title":"Graph Memory for AI Agents (January 2026)","url":"https://mem0.ai/blog/graph-memory-solutions-ai-agents"},{"title":"Cognee - AI Memory Tools Evaluation - Cognee, Mem0, Zep/Graphiti","url":"https://www.cognee.ai/blog/deep-dives/ai-memory-tools-evaluation"},{"title":"Survey of AI Agent Memory Frameworks | Graphlit Blog","url":"https://www.graphlit.com/blog/survey-of-ai-agent-memory-frameworks"},{"title":"Cognee — AI Memory Tools Evaluation — Cognee, Mem0, Zep/Graphiti | by cognee | Medium","url":"https://medium.com/@cognee/cognee-ai-memory-tools-evaluation-cognee-mem0-zep-graphiti-87425abecbb2"},{"title":"Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory","url":"https://arxiv.org/html/2504.19413v1"},{"title":"Cognee - AI Memory Benchmarking: Cognee, LightRAG, Graphiti, Mem0","url":"https://www.cognee.ai/blog/deep-dives/ai-memory-evals-0825"},{"title":"Memory in AI Agents - by Kenn So - Generational","url":"https://www.generational.pub/p/memory-in-ai-agents"},{"title":"Kirk Marple on X: \"Overview of AI Agent Memory Frameworks\" / X","url":"https://x.com/KirkMarple/status/1876858577144668609"},{"title":"Deep dive into \"Memory for LLMs\" architectures","url":"https://machinelearningatscale.substack.com/p/deep-dive-into-memory-for-llms-architectures"}]

Based on the search results, here's a comprehensive comparison of AI memory frameworks for 2026:

## Key Memory Framework Comparison

### **Mem0**
Mem0 is recommended if you need a functional AI memory solution right now, prefer a managed SaaS offering, and have the budget for their plans. Mem0 distinguishes itself through a unified hybrid-memory architecture by natively combining graph, vector, and key-value stores, which handles both semantic and symbolic aspects of memory out-of-the-box, differing from solutions that use only vectors or only graphs. It offers broad embedding provider support and VectorDB options including Qdrant, Chroma, Milvus, Pgvector, Redis, and Azure AI Search.

### **Zep (with Graphiti)**
Zep stands out for its temporal knowledge graph approach, automatically maintaining a structured graph that updates as conversations develop, capturing context shifts and relationships over time like noting that "the user previously preferred X but now prefers Y." Zep developed Graphiti, an open-source library for building temporal knowledge graphs from chat history that dynamically captures entities and relationships from conversations. Zep is recommended if your primary goal is to learn about the cutting edge of AI memory systems, though their product isn't ready for prime time deployment yet.

### **Letta**
Letta is an agent runtime built around self-editing memory where agents manage what stays in-context versus archival storage through dedicated memory management tools, providing a complete agent framework with REST API and development environment for building stateful AI services. Letta is recommended if you prioritize true open source, love engaging with an active community, aren't on a tight production deadline, and are happy to grow alongside the project.

### **Self-Hosted Options**
While Letta Cloud, Mem0's managed platform, and Zep Cloud provide full hosting, each also allows local or Docker-based self-hosting for more control. LangMem and Supermemory require self-hosting and manual setup, while Letta and Zep provide managed options but come with more complex architectures that need configuration time.

### **Use Case Recommendations**
Letta works well for teams building sophisticated agent applications from scratch that need runtime orchestration, tool ecosystems, and explicit control over memory editing operations. Zep works well for enterprise teams building agents that need to reason about how facts and relationships change over time while integrating multiple business data sources.

REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.

Question: Mem0 Zep Graphiti Letta memory framework comparison self-hosted 2026

Kirk Marple on X: "Overview of AI Agent Memory Frameworks" / X

Deep dive into "Memory for LLMs" architectures


Now let me go deeper on the critical pieces — the actual technical architecture comparisons and what building from scratch really looks like.


WebFetch

Prompt: What are the 3 types of long-term memory AI agents need? How does each work? What storage backends are recommended for each? What's the implementation pattern?


Prompt: What are the benchmark results comparing Cognee, Mem0, Zep/Graphiti? Which performs best on accuracy, speed, and cost? What are the weaknesses of each?


Prompt: How does Redis implement AI agent memory? What's the architecture? Hot path vs cold path? How does it handle episodic, semantic, procedural memory? What's the production pattern?


Request failed with status code 403

Error: Request failed with status code 403


<tool_use_error>Sibling tool call errored</tool_use_error>


Prompt: What are the benchmark results comparing Cognee, Mem0, Zep/Graphiti? Which performs best on accuracy, speed, and cost? What are the weaknesses of each?


Prompt: How does Redis implement AI agent memory? What's the architecture? Hot path vs cold path? How does it handle episodic, semantic, procedural memory? What's the production pattern?


Prompt: How do Letta, Mem0, and Zep compare? Which is best for self-hosted? Which is most production-ready? What are the pros and cons of each? What's the recommendation?


Request failed with status code 403


Prompt: What are the benchmark results comparing Cognee, Mem0, Zep/Graphiti? Performance comparison?


Prompt: Redis AI agent memory architecture. Hot path, cold path, implementation details?


# AI Memory Tools Benchmark Results

The article presents evaluation results comparing three AI memory solutions, but **specific performance numbers are not included in the text content provided**.

## What We Know

The evaluation used the **HotPotQA benchmark**, which tests:
- Multi-document processing capabilities
- Cross-source information integration
- Accuracy in complex reasoning tasks

The three tools evaluated were:
1. **Mem0**
2. **Zep/Graphiti**
3. **Cognee**

## Key Finding

Cognee's authors note that "the results are much better after adding our magic sauce into it" through their proprietary optimization tool, Dreamify. They emphasize that "success isn't just about metrics - it's about the ability to modify the system parameters."

## Important Caveat

The authors acknowledge limitations in their methodology: "LLM as a judge metrics are not reliable measure," and they note that Graphiti has submitted updated scores showing "significant improvement on their end when using _search functionality."

**The actual comparative performance chart referenced in the article (`/content/blog/posts/ai-memory-tools-evaluation/metrics-comparison.webp`) is not rendered as readable text in the source provided.**


# Redis AI Agent Memory Architecture

Based on the Redis article, here's the architecture breakdown:

## Four-Stage Memory System

### 1. **Encoding**
Convert data to vector embeddings using transformer models
- Chunk dataset into segments
- Generate embeddings for semantic meaning
- Enable mathematical similarity measurement

### 2. **Storage**
Vector databases with performance tradeoffs:
- **HNSW** (Hierarchical Navigable Small World): High accuracy, more memory (~95%+ recall)
- **IVF** (Inverted File Index): Memory-efficient for billions of vectors
- **FLAT**: Exact search for small datasets (no scalability)

### 3. **Retrieval**
Similarity search via approximate k-NN (k-nearest neighbors)
- Find k most similar vectors to query
- Trade perfect accuracy for millisecond speed
- Active RAG patterns for iterative refinement

### 4. **Integration**
Retrieved context formatted and augmented before LLM prompt injection

## Memory Types

| Type | Purpose | Duration |
|------|---------|----------|
| **Short-term** | Current interaction context | Session-scoped |
| **Long-term** | Cross-session knowledge | Persistent (weeks/months) |
| **Episodic** | Past experiences with temporal data | Event logs |
| **Semantic** | Factual knowledge (profiles, specs) | Knowledge bases |
| **Procedural** | Task execution workflows | Workflow databases |

## Performance Targets

- **Voice AI**: Sub-second end-to-end (speech-to-text → memory → inference → TTS)
- **High-throughput**: Hundreds of inferences/second with GPU acceleration
- **Enterprise scale**: Millions to billions of vectors

## Hot Path vs Cold Path

**Hot Path (In-Memory - Microseconds)**
- Current session state (short-term memory)
- Recent interactions
- Active reasoning steps

**Cold Path (Disk-based - Milliseconds)**
- Historical data retrieval
- Long-term knowledge access
- Analytical queries

## Redis Implementation

Redis handles all memory types in one platform:
- **Vector Library**: Semantic search for long-term memory
- **In-memory data structures**: Short-term session state
- **Streams**: Event logs for episodic memory
- **Sub-millisecond queries** for read-heavy workloads
- **Active-Active Geo-Distribution** for low-latency across regions

**Key advantage**: Single-platform approach eliminates integration complexity while providing microsecond latency critical for compounding reasoning steps.


Excellent data. Now let me also fetch the FalkorDB/Graphiti MCP details and the ICLR workshop paper, then I'll synthesize everything including the Supermemory pricing update.


Prompt: How does the Graphiti MCP server work? What does it take to set up? Self-hosted? What's the architecture? How does multi-tenancy work?


Prompt: What is LangMem's approach to long-term memory? How does it structure memory? What storage backends? How does it handle the different memory types?


# LangMem's Approach to Long-Term Memory

## Core Philosophy

LangMem follows a consistent pattern: "Accept conversation(s) and current memory state" → prompt an LLM to expand or consolidate memory → return updated state. The framework emphasizes that "the best memory systems are often application-specific."

## Three Memory Types

LangMem structures memory into three categories:

1. **Semantic Memory** (Facts & Knowledge): Stored as either "collections" (searchable documents) or "profiles" (single documents with strict schemas). Collections handle unbounded knowledge, while profiles track task-specific current state.

2. **Episodic Memory** (Past Experiences): Captures successful interactions as learning examples, preserving "the situation, the thought process that led to success, and why that approach worked."

3. **Procedural Memory** (System Instructions): Encodes agent behavior through system prompts that evolve via feedback and experience.

## Formation Approaches

Memory forms through two pathways:
- **Active (Hot Path)**: Immediate updates during conversations, adding latency
- **Background (Subconscious)**: Post-conversation reflection without slowing interactions

## Storage Architecture

LangMem provides optional storage built on LangGraph's primitives, featuring:
- **Hierarchical Namespaces**: Multi-level organization (e.g., organization → user → context)
- **Flexible Retrieval**: Direct access, semantic search, and metadata filtering via BaseStore interface

## Integration Layers

The framework offers two API levels: core functions (memory managers, prompt optimizers) without storage dependencies, plus stateful integrations with LangGraph for persistence.


# Graphiti MCP Server: Setup and Architecture

## How It Works

Graphiti's MCP server converts conversations into persistent knowledge graphs while enforcing multi-tenancy through `group_id` namespacing. The system extracts entities and relationships from chat interactions, storing them in FalkorDB as a queryable graph rather than unstructured text.

## Setup Process

The setup is straightforward for local development:

1. **Clone and deploy**: Run `git clone https://github.com/getzep/graphiti`, navigate to `mcp_server`, then execute `docker-compose up`

2. **Configure Claude Desktop**: Edit the config file at `~/Library/Application Support/Claude/claude_desktop_config.json` and register Graphiti as an MCP server pointing to `http://127.0.0.1:8000/mcp/`

3. **Start using**: Restart Claude Desktop and begin chatting—Graphiti automatically captures and persists conversations

## Self-Hosted Architecture

The Docker Compose stack bundles three components:
- **FalkorDB** (graph database)
- **FalkorDB Browser UI** (inspection interface)
- **Graphiti MCP server** (the MCP endpoint)

This "combined image runtime" keeps local and production environments aligned, reducing friction during scaling.

## Multi-Tenancy Implementation

Graphiti isolates tenant data through `group_id` namespacing at the storage layer itself—preventing cross-contamination between users, projects, or workspaces by design rather than relying on application-level filtering.


Now let me also read our own existing research reports on sovereign memory — we already have deep research on this.


Read

E:\genesis-system\Research reports\Sovereign AI Backend Licensing and Development.md