{
  "canonical_name": "rishimeka/genesys",
  "compilation_id": "pack_b7bd37bf8c4a4d5cba7db0aba9bbf2b9",
  "created_at": "2026-05-15T07:20:35.483047+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `pip install genesys-memory` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "pip install genesys-memory",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_ef6662f6afa440e59940c76db8844e90"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_2de816699a8f96bcd0898accf3d332ae",
    "canonical_name": "rishimeka/genesys",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/rishimeka/genesys",
    "slug": "genesys",
    "source_packet_id": "phit_4660f470a17748189a921d8736a1a1b6",
    "source_validation_id": "dval_2c0e81f2b4f64a94886a7f8bf23c34db"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 mcp_host的用户",
    "github_forks": 2,
    "github_stars": 16,
    "one_liner_en": "Open-source causal graph memory for AI agents. 89.9% on LoCoMo. MCP server with ACT-R scoring, spreading activation, and active forgetting.",
    "one_liner_zh": "Open-source causal graph memory for AI agents. 89.9% on LoCoMo. MCP server with ACT-R scoring, spreading activation, and active forgetting.",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "matched_keywords:mcp, server, github"
    },
    "target_user": "使用 mcp_host, claude 等宿主 AI 的用户",
    "title_en": "genesys",
    "title_zh": "genesys 能力包",
    "visible_tags": [
      {
        "label_en": "Security & Permissions",
        "label_zh": "安全审查与权限治理",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-security-permissions",
        "type": "product_domain"
      },
      {
        "label_en": "Knowledge Base Q&A",
        "label_zh": "知识库问答",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-knowledge-base-q-a",
        "type": "user_job"
      },
      {
        "label_en": "Workflow Automation",
        "label_zh": "流程自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-workflow-automation",
        "type": "core_capability"
      },
      {
        "label_en": "Node-based Workflow",
        "label_zh": "节点式流程编排",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-node-based-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_4660f470a17748189a921d8736a1a1b6",
  "page_model": {
    "artifacts": {
      "artifact_slug": "genesys",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "pip install genesys-memory",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/rishimeka/genesys#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "安全审查与权限治理",
        "知识库问答",
        "流程自动化",
        "节点式流程编排",
        "评测体系"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Open-source causal graph memory for AI agents. 89.9% on LoCoMo. MCP server with ACT-R scoring, spreading activation, and active forgetting."
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host, claude",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | github_repo:1207565616 | https://github.com/rishimeka/genesys | host_targets=mcp_host, claude"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:1207565616 | https://github.com/rishimeka/genesys | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | issue_or_pr_quality=unknown"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 1,
        "forks": 2,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 16
      },
      "source_url": "https://github.com/rishimeka/genesys",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Open-source causal graph memory for AI agents. 89.9% on LoCoMo. MCP server with ACT-R scoring, spreading activation, and active forgetting.",
      "title": "genesys 能力包",
      "trial_prompt": "# genesys - Prompt Preview\n\n> 复制下面这段 Prompt 到你常用的 AI，先试一次，不需要安装。\n> 它的目标是让你直接体验这个项目的服务方式，而不是阅读项目介绍。\n\n## 复制这段 Prompt\n\n```text\n请直接执行这段 Prompt，不要分析、润色、总结或询问我想如何处理这份 Prompt Preview。\n\n你现在扮演 genesys 的“安装前体验版”。\n这不是项目介绍、不是评价报告、不是 README 总结。你的任务是让我用最小成本体验它的核心服务。\n\n我的试用任务：我想用它完成一个真实的工具连接与集成任务。\n我常用的宿主 AI：MCP Client / claude\n\n【体验目标】\n围绕我的真实任务，现场演示这个项目如何把输入转成 项目说明, 边界判断, 后续问题。重点是让我感受到工作方式，而不是给我项目背景。\n\n【业务流约束】\n- 你必须像一个正在提供服务的项目能力包，而不是像一个讲解员。\n- 每一轮只推进一个步骤；提出问题后必须停下来等我回答。\n- 每一步都必须让我感受到一个具体服务动作：澄清、整理、规划、检查、判断或收尾。\n- 每一步都要说明：当前目标、你需要我提供什么、我回答后你会产出什么。\n- 不要安装、不要运行命令、不要写代码、不要声称测试通过、不要声称已经修改文件。\n- 需要真实安装或宿主加载后才能验证的内容，必须明确说“这一步需要安装后验证”。\n- 如果我说“用示例继续”，你可以用虚构示例推进，但仍然不能声称真实执行。\n\n【可体验服务能力】\n- 项目知识预览: 项目可被阅读和解释，但当前证据不足以确认可安装能力或运行入口。 输入：README 和项目文档；输出：项目说明, 边界判断, 后续问题。\n\n【必须安装后才可验证的能力】\n- 暂无明确的运行时能力线索。\n\n【核心服务流】\n请严格按这个顺序带我体验。不要一次性输出完整流程：\n1. getting-started：Getting Started with Genesys。围绕“Getting Started with Genesys”模拟一次用户任务，不展示安装或运行结果。\n2. architecture：System Architecture。围绕“System Architecture”模拟一次用户任务，不展示安装或运行结果。\n3. memory-scoring：Memory Scoring Engine。围绕“Memory Scoring Engine”模拟一次用户任务，不展示安装或运行结果。\n4. memory-lifecycle：Memory Lifecycle Management。围绕“Memory Lifecycle Management”模拟一次用户任务，不展示安装或运行结果。\n5. backends-overview：Storage Backend Comparison。围绕“Storage Backend Comparison”模拟一次用户任务，不展示安装或运行结果。\n\n【核心能力体验剧本】\n每一步都必须按“输入 -> 服务动作 -> 中间产物”执行。不要只说流程名：\n1. getting-started\n输入：用户提供的“Getting Started with Genesys”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n2. architecture\n输入：用户提供的“System Architecture”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n3. memory-scoring\n输入：用户提供的“Memory Scoring Engine”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n4. memory-lifecycle\n输入：用户提供的“Memory Lifecycle Management”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n5. backends-overview\n输入：用户提供的“Storage Backend Comparison”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n【项目服务规则】\n这些规则决定你如何服务用户。不要解释规则本身，而要在每一步执行时遵守：\n- 先确认用户任务、输入材料和成功标准，再模拟项目能力。\n- 每一步都必须形成可检查的小产物，并等待用户确认后再继续。\n- 凡是需要安装、调用工具或访问外部服务的能力，都必须标记为安装后验证。\n\n【每一步的服务约束】\n- Step 1 / getting-started：Step 1 必须围绕“Getting Started with Genesys”形成一个小中间产物，并等待用户确认。\n- Step 2 / architecture：Step 2 必须围绕“System Architecture”形成一个小中间产物，并等待用户确认。\n- Step 3 / memory-scoring：Step 3 必须围绕“Memory Scoring Engine”形成一个小中间产物，并等待用户确认。\n- Step 4 / memory-lifecycle：Step 4 必须围绕“Memory Lifecycle Management”形成一个小中间产物，并等待用户确认。\n- Step 5 / backends-overview：Step 5 必须围绕“Storage Backend Comparison”形成一个小中间产物，并等待用户确认。\n\n【边界与风险】\n- 不要声称已经安装、运行、调用 API、读写本地文件或完成真实任务。\n- 安装前预览只能展示工作方式，不能证明兼容性、性能或输出质量。\n\n【可追溯依据】\n这些路径只用于你内部校验或在我追问“依据是什么”时简要引用。不要在首次回复主动展开：\n- https://github.com/rishimeka/genesys\n- https://github.com/rishimeka/genesys#readme\n- benchmarks/README.md\n- CONTRIBUTING.md\n- LICENSE\n- .github/pull_request_template.md\n- CHANGELOG.md\n- README.md\n- pyproject.toml\n- .env.example\n- src/genesys_memory/__init__.py\n- src/genesys_memory/server.py\n\n【首次问题规则】\n- 首次三问必须先确认用户目标、成功标准和边界，不要提前进入工具、安装或实现细节。\n- 如果后续需要技术条件、文件路径或运行环境，必须等用户确认目标后再追问。\n\n首次回复必须只输出下面 4 个部分：\n1. 体验开始：用 1 句话说明你将带我体验 genesys 的核心服务。\n2. 当前步骤：明确进入 Step 1，并说明这一步要解决什么。\n3. 你会如何服务我：说明你会先改变我完成任务的哪个动作。\n4. 只问我 3 个问题，然后停下等待回答。\n\n首次回复禁止输出：后续完整流程、证据清单、安装命令、项目评价、营销文案、已经安装或运行的说法。\n\nStep 1 / brainstorming 的二轮协议：\n- 我回答首次三问后，你仍然停留在 Step 1 / brainstorming，不要进入 Step 2。\n- 第二次回复必须产出 6 个部分：澄清后的任务定义、成功标准、边界条件、\n  2-3 个可选方案、每个方案的权衡、推荐方案。\n- 第二次回复最后必须问我是否确认推荐方案；只有我明确确认后，才能进入下一步。\n- 第二次回复禁止输出 git worktree、代码计划、测试文件、命令或真实执行结果。\n\n后续对话规则：\n- 我回答后，你先完成当前步骤的中间产物并等待确认；只有我确认后，才能进入下一步。\n- 每一步都要生成一个小的中间产物，例如澄清后的目标、计划草案、测试意图、验证清单或继续/停止判断。\n- 所有演示都写成“我会建议/我会引导/这一步会形成”，不要写成已经真实执行。\n- 不要声称已经测试通过、文件已修改、命令已运行或结果已产生。\n- 如果某个能力必须安装后验证，请直接说“这一步需要安装后验证”。\n- 如果证据不足，请明确说“证据不足”，不要补事实。\n```\n",
      "voices": [
        {
          "body": "当前没有项目级社区来源；不会把未抓取讨论包装成社会证明。",
          "items": [],
          "status": "待发现 Agent 补证",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "Open-source causal graph memory for AI agents. 89.9% on LoCoMo. MCP server with ACT-R scoring, spreading activation, and active forgetting.",
      "effort": "安装已验证",
      "forks": 2,
      "icon": "link",
      "name": "genesys 能力包",
      "risk": "需复核",
      "slug": "genesys",
      "stars": 16,
      "tags": [
        "安全审查与权限治理",
        "知识库问答",
        "流程自动化",
        "节点式流程编排",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/rishimeka/genesys 项目说明书\n\n生成时间：2026-05-15 07:11:52 UTC\n\n## 目录\n\n- [Getting Started with Genesys](#getting-started)\n- [System Architecture](#architecture)\n- [Memory Scoring Engine](#memory-scoring)\n- [Memory Lifecycle Management](#memory-lifecycle)\n- [Nodes and Edges Data Models](#nodes-edges)\n- [Graph Traversal and Causal Reasoning](#graph-traversal)\n- [Storage Backend Comparison](#backends-overview)\n- [Storage Provider Implementation](#storage-implementation)\n- [MCP Tools Reference](#mcp-tools)\n- [Configuration Guide](#configuration)\n\n<a id='getting-started'></a>\n\n## Getting Started with Genesys\n\n### 相关页面\n\n相关主题：[Configuration Guide](#configuration), [Storage Backend Comparison](#backends-overview)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n- [src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [server.json](https://github.com/rishimeka/genesys/blob/main/server.json)\n</details>\n\n# Getting Started with Genesys\n\n## Overview\n\nGenesys is an **intelligence layer for AI memory** — a scoring engine, causal graph, and lifecycle manager for AI agent memory. It provides persistent memory capabilities with intelligent forgetting, ensuring AI systems maintain context across sessions without unbounded memory growth.\n\nThe system speaks MCP (Model Context Protocol) natively, making it compatible with Claude Code, Claude Desktop, and any MCP-compatible AI client.\n\n**Key capabilities:**\n\n- Multi-force memory scoring (relevance × connectivity × reactivation)\n- Causal graph relationships between memories\n- Intelligent forgetting — memories decay and are pruned when irrelevant\n- Core memory promotion for structurally important information\n- Multiple storage backends (in-memory, Postgres, Obsidian, FalkorDB)\n- Hybrid retrieval (vector + keyword + graph spreading activation)\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Architecture Overview\n\nGenesys Memory is organized into several core modules:\n\n```\nsrc/genesys_memory/\n├── engine/             # Scoring, transitions, forgetting, reactivation\n│   ├── config.py       # All tunable thresholds (env-configurable)\n│   ├── scoring.py      # Three-force multiplicative decay scoring\n│   ├── transitions.py  # Status FSM (ACTIVE -> DORMANT -> FADING -> PRUNED)\n│   ├── forgetting.py   # Conjunctive active forgetting\n│   └── reactivation.py # BFS cascade reactivation\n├── core_memory/        # Core promotion logic (graph-derived)\n├── storage/            # Storage provider abstractions + implementations\n│   ├── base.py         # Abstract interfaces (GraphStorageProvider, etc.)\n│   └── memory.py       # In-memory implementation\n└── mcp/                # MCP protocol tools and server\n    └── tools.py        # MCP tool implementations\n```\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n### Memory Lifecycle State Machine\n\nMemories progress through defined states with configurable transitions:\n\n```mermaid\ngraph LR\n    STORE[STORE] --> ACTIVE[ACTIVE]\n    ACTIVE --> DORMANT[DORMANT]\n    DORMANT --> FADING[FADING]\n    FADING --> PRUNED[PRUNED]\n    ACTIVE -->|reactivation| ACTIVE\n    DORMANT -->|reactivation| ACTIVE\n    FADING -->|reactivation| DORMANT\n    \n    style PRUNED fill:#ff6b6b\n    style ACTIVE fill:#51cf66\n    style DORMANT fill:#fcc419\n```\n\n### Memory Scoring Formula\n\nEvery memory is scored by three forces multiplied together:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n| Force | Description |\n|-------|-------------|\n| **Relevance** | Decays over time. Old memories fade unless reinforced. |\n| **Connectivity** | Rewards memories with many causal links. Hub memories survive. |\n| **Reactivation** | Boosts memories that keep getting recalled. Frequency matters. |\n\nBecause the formula is multiplicative, a memory must score on **all three axes** to survive. A highly connected but never-accessed memory still decays.\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Installation\n\n### Prerequisites\n\n- Python 3.11+\n- pip or uv package manager\n\n### Package Installation\n\nGenesys Memory is published as `genesys-memory` on PyPI:\n\n```bash\npip install genesys-memory\n```\n\n### Backend-Specific Installation\n\nDepending on your chosen storage backend, install with additional dependencies:\n\n| Backend | Install Command |\n|---------|-----------------|\n| In-memory (default) | `pip install genesys-memory` |\n| Postgres + pgvector | `pip install 'genesys-memory[postgres]'` |\n| Obsidian Vault | `pip install 'genesys-memory[obsidian]'` |\n| FalkorDB | `pip install 'genesys-memory[falkordb]'` |\n| Local embeddings (no API key) | `pip install 'genesys-memory[local]'` |\n\n### Full Installation with All Backends\n\n```bash\npip install 'genesys-memory[postgres,obsidian,local]'\n```\n\n### Development Installation\n\n```bash\ngit clone https://github.com/rishimeka/genesys.git\ncd genesys\npip install -e '.[dev]'\n```\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Configuration\n\n### Environment Variables\n\nCopy the example configuration:\n\n```bash\ncp .env.example .env\n```\n\nConfigure the following variables based on your setup:\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `OPENAI_API_KEY` | Unless `GENESYS_EMBEDDER=local` | — | OpenAI API key for embeddings |\n| `ANTHROPIC_API_KEY` | No | — | Anthropic API key for LLM memory processing |\n| `GENESYS_BACKEND` | No | `memory` | Storage backend: `memory`, `postgres`, `obsidian`, `falkordb` |\n| `GENESYS_EMBEDDER` | No | `openai` | Embedding provider: `openai` or `local` |\n| `DATABASE_URL` | If postgres | — | Postgres connection string |\n| `OBSIDIAN_VAULT_PATH` | If obsidian | — | Path to your Obsidian vault |\n| `FALKORDB_HOST` | If falkordb | `localhost` | FalkorDB host |\n| `GENESYS_USER_ID` | No | — | Default user ID for single-tenant mode |\n| `GENESYS_PERSIST_PATH` | No | — | Path for state persistence (e.g., `.genesys_state.json`) |\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Storage Backends\n\n| Backend | Use Case | Dependencies |\n|---------|----------|--------------|\n| `memory` | Zero deps, try it out | Built-in |\n| `postgres` + pgvector | Persistent, scalable | Postgres + Docker |\n| `obsidian` | Local-first knowledge base | Obsidian vault |\n| `falkordb` | Graph-native traversal | FalkorDB (Redis-based) |\n\n---\n\n## Quick Start: In-Memory Backend\n\nThe in-memory backend requires no external services — ideal for testing and development.\n\n### 1. Create Configuration\n\n```bash\ncp .env.example .env\n```\n\nEdit `.env`:\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=memory\n```\n\n### 2. Start the Server\n\n```bash\nuvicorn genesys.api:app --port 8000\n```\n\n### 3. Persist State (Optional)\n\nTo persist memory across restarts:\n\n```env\nGENESYS_PERSIST_PATH=.genesys_state.json\n```\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Option 1: Postgres + pgvector (Production)\n\nFor persistent, scalable storage with vector search capabilities.\n\n### 1. Install Dependencies\n\n```bash\npip install 'genesys-memory[postgres]'\n```\n\n### 2. Configure Environment\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\n```\n\n### 3. Start Infrastructure\n\n```bash\ndocker compose up -d postgres\nalembic upgrade head\n```\n\n### 4. Start the Server\n\n```bash\nGENESYS_BACKEND=postgres uvicorn genesys.api:app --port 8000\n```\n\n> **Give this to Claude to set it up for you:**\n> *\"Install genesys-memory[postgres], start a Postgres container with pgvector using docker compose, run alembic migrations, create a .env with my OpenAI key and DATABASE_URL, start the server with GENESYS_BACKEND=postgres, and connect it as an MCP server.\"*\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Option 2: Obsidian Vault (Local-First)\n\nTurn your Obsidian vault into a Genesys memory store. Markdown files become memory nodes, `[[wikilinks]]` become causal edges.\n\n### 1. Install Dependencies\n\n```bash\npip install 'genesys-memory[obsidian]'\n```\n\n### 2. Configure Environment\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=obsidian\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n```\n\n> If `OBSIDIAN_VAULT_PATH` is not set, Genesys auto-detects by looking for `.obsidian/` in `~/Documents/personal`, `~/Documents/Obsidian`, and `~/obsidian`.\n\n### 3. Start the Server\n\n```bash\nuvicorn genesys.api:app --port 8000\n```\n\nOn first start, Genesys indexes all `.md` files in the vault and generates embeddings. A file watcher re-indexes incrementally when you edit notes.\n\n### 4. Fully Local (No API Keys)\n\nFor zero external dependencies, use local embeddings:\n\n```bash\npip install 'genesys-memory[obsidian,local]'\n```\n\n```env\nGENESYS_BACKEND=obsidian\nGENESYS_EMBEDDER=local\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n# No OPENAI_API_KEY needed\n```\n\nThis uses `all-MiniLM-L6-v2` (384-dim) via `sentence-transformers` for embeddings. The model is downloaded on first use (~80 MB).\n\n> **Give this to Claude to set it up for you:**\n> *\"Install genesys-memory[obsidian,local], create a .env with GENESYS_BACKEND=obsidian, GENESYS_EMBEDDER=local, and OBSIDIAN_VAULT_PATH to my vault at [YOUR_VAULT_PATH], start the server on port 8000, and connect it as an MCP server. No API keys needed.\"*\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Option 3: FalkorDB (Graph-Native)\n\nUses FalkorDB (Redis-based graph database) for native graph traversal.\n\n### 1. Install Dependencies\n\n```bash\npip install 'genesys-memory[falkordb]'\n```\n\n### 2. Configure Environment\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=falkordb\nFALKORDB_HOST=localhost\n```\n\n### 3. Start Infrastructure\n\n```bash\ndocker compose up -d falkordb\n```\n\n### 4. Start the Server\n\n```bash\nuvicorn genesys.api:app --port 8000\n```\n\n> **Give this to Claude to set it up for you:**\n> *\"Install genesys-memory[falkordb], start a FalkorDB container using docker compose, create a .env with my OpenAI key and GENESYS_BACKEND=falkordb, start the server on port 8000, and connect it as an MCP server.\"*\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Connecting to AI Clients\n\n### Claude Code\n\n```bash\nclaude mcp add --transport http genesys http://localhost:8000/mcp\n```\n\n### Claude Desktop\n\nAdd to your `claude_desktop_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"genesys\": {\n      \"url\": \"http://localhost:8000/mcp\"\n    }\n  }\n}\n```\n\n### Any MCP Client\n\nPoint your client at the MCP endpoint:\n\n```\nhttp://localhost:8000/mcp\n```\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## MCP Tools Reference\n\nGenesys provides the following MCP tools for memory operations:\n\n| Tool | Description |\n|------|-------------|\n| `memory_store` | Store a new memory, optionally linking to related memories |\n| `memory_recall` | Recall memories by natural language query (vector + graph) |\n| `memory_search` | Search memories with filters (status, date range, keyword) |\n| `memory_traverse` | Walk the causal graph from a given memory node |\n| `memory_explain` | Explain why a memory exists and its causal chain |\n| `memory_stats` | Get memory system statistics |\n| `pin_memory` | Pin a memory so it's never forgotten |\n| `unpin_memory` | Unpin a previously pinned memory |\n| `delete_memory` | Permanently delete a memory |\n| `list_core_memories` | List core memories, optionally filtered by category |\n| `set_core_preferences` | Set user preferences for core memory categories |\n\n### Tool Schemas\n\n#### memory_store\n\n```json\n{\n  \"name\": \"memory_store\",\n  \"description\": \"Store a new memory node\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"content\"],\n    \"properties\": {\n      \"content\": {\"type\": \"string\"},\n      \"related_to\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n      \"category\": {\"type\": \"string\"}\n    }\n  }\n}\n```\n\n#### memory_recall\n\n```json\n{\n  \"name\": \"memory_recall\",\n  \"description\": \"Recall memories using hybrid search (vector + keyword + graph spreading activation)\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"query\"],\n    \"properties\": {\n      \"query\": {\"type\": \"string\"},\n      \"k\": {\"type\": \"integer\", \"default\": 10},\n      \"max_results\": {\"type\": \"integer\"}\n    }\n  }\n}\n```\n\n#### memory_search\n\n```json\n{\n  \"name\": \"memory_search\",\n  \"description\": \"Filtered vector search by status, category, date, or entity\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"query\"],\n    \"properties\": {\n      \"query\": {\"type\": \"string\"},\n      \"filters\": {\"type\": \"object\"},\n      \"k\": {\"type\": \"integer\", \"default\": 10}\n    }\n  }\n}\n```\n\n#### memory_traverse\n\n```json\n{\n  \"name\": \"memory_traverse\",\n  \"description\": \"Traverse the memory graph from a starting node\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"node_id\"],\n    \"properties\": {\n      \"node_id\": {\"type\": \"string\"},\n      \"depth\": {\"type\": \"integer\", \"default\": 2},\n      \"edge_types\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n    }\n  }\n}\n```\n\n#### memory_explain\n\n```json\n{\n  \"name\": \"memory_explain\",\n  \"description\": \"Explain a memory's score breakdown\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"node_id\"],\n    \"properties\": {\n      \"node_id\": {\"type\": \"string\"}\n    }\n  }\n}\n```\n\n资料来源：[src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n---\n\n## Memory Node Data Model\n\nEach memory is represented as a `MemoryNode` with the following structure:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    \n    # Content\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    content_ref: str | None = None\n    embedding: list[float] | None = None\n    \n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern\n    irrelevance_counter: int = 0\n    \n    # Provenance\n    source_agent: str = \"claude\"\n    source_session: str = \"\"\n    \n    # Classification\n    entity_refs: list[str] = Field(default_factory=list)\n    category: str | None = None\n    \n    # Stability\n    stability: float = 1.0\n    \n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n    \n    # Reactivation history\n    reactivation_timestamps: list[datetime] = Field(default_factory=list)\n```\n\n资料来源：[src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n---\n\n## Memory Retrieval Flow\n\nThe recall operation uses a hybrid approach combining vector similarity, keyword matching, and graph spreading activation:\n\n```mermaid\ngraph TD\n    Query[User Query] --> Embed[Generate Embedding]\n    Embed --> VectorSearch[Vector Similarity Search]\n    Query --> KeywordSearch[Keyword Search]\n    VectorSearch --> Combine[Hybrid Ranking]\n    KeywordSearch --> Combine\n    Combine --> GraphSpread[Graph Spreading Activation]\n    GraphSpread --> Results[Ranked Memories]\n```\n\n资料来源：[src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n---\n\n## Development and Testing\n\n### Code Style\n\n- **Python 3.11+**, async-first\n- **Linting**: `ruff check src/` (config in `pyproject.toml`, line length 120)\n- **Type checking**: `mypy src/genesys_memory --ignore-missing-imports`\n- **Formatting**: Type hints throughout, minimal comments\n\n### Running Tests\n\n```bash\n# Run all unit tests\npytest tests/ -v\n\n# With coverage\npytest tests/ -v --cov=src/genesys_memory --cov-report=term-missing\n```\n\nTests are in `tests/` and use `pytest-asyncio` (auto mode).\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n---\n\n## Security\n\nGenesys follows a responsible disclosure policy for security vulnerabilities:\n\n| Version | Supported |\n|---------|-----------|\n| 0.3.x   | Yes       |\n| < 0.3   | No        |\n\nTo report a security vulnerability, use [GitHub's security advisory feature](https://github.com/rishimeka/genesys/security/advisories/new). **Do not open a public issue.**\n\n资料来源：[SECURITY.md](https://github.com/rishimeka/genesys/blob/main/SECURITY.md)\n\n---\n\n## License\n\nGenesys is open source under the [GNU Affero General Public License v3.0](LICENSE).\n\n> **Note:** Genesys releases prior to v0.3.6 were documented as Apache 2.0 in error. The LICENSE file has always contained the AGPLv3 text. From v0.3.6 onward, all documentation correctly references AGPL-3.0-or-later with a Contributor License Agreement.\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Contributing\n\nContributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. Look for issues labeled `good first issue` for scoped, well-defined tasks suitable for new contributors.\n\nAll contributors must agree to the [Contributor License Agreement](CLA.md) before their code can be merged.\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n---\n\n<a id='architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Memory Scoring Engine](#memory-scoring), [Memory Lifecycle Management](#memory-lifecycle), [Nodes and Edges Data Models](#nodes-edges)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/__init__.py)\n- [src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n- [src/genesys_memory/engine/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/__init__.py)\n- [src/genesys_memory/storage/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/__init__.py)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [server.json](https://github.com/rishimeka/genesys/blob/main/server.json)\n</details>\n\n# System Architecture\n\n## Overview\n\nGenesys is a scoring engine, causal graph, and lifecycle manager for AI agent memory. It implements a sophisticated memory management system that enables AI agents to store, retrieve, and intelligently forget information over time. The system speaks MCP (Model Context Protocol) natively, allowing seamless integration with Claude Desktop and Claude Code.\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## High-Level Architecture\n\nThe Genesys system is organized into several interconnected layers:\n\n```mermaid\ngraph TB\n    subgraph \"Client Layer\"\n        ClaudeDesktop[\"Claude Desktop\"]\n        ClaudeCode[\"Claude Code\"]\n        MCPSDK[\"MCP SDK\"]\n    end\n    \n    subgraph \"API Layer\"\n        Server[\"MCP Server (stdio)\"]\n        Tools[\"MCP Tools\"]\n    end\n    \n    subgraph \"Core Engine\"\n        Scoring[\"Scoring Engine\"]\n        Lifecycle[\"Lifecycle Manager\"]\n        LLMProvider[\"LLM Provider\"]\n    end\n    \n    subgraph \"Storage Layer\"\n        MemoryBackend[\"In-Memory\"]\n        Postgres[\"Postgres + pgvector\"]\n        Obsidian[\"Obsidian Vault\"]\n        FalkorDB[\"FalkorDB\"]\n    end\n    \n    ClaudeDesktop & ClaudeCode --> MCPSDK\n    MCPSDK --> Server\n    Server --> Tools\n    Tools --> Scoring\n    Scoring --> Lifecycle\n    Scoring --> LLMProvider\n    Lifecycle --> MemoryBackend & Postgres & Obsidian & FalkorDB\n```\n\n**资料来源：** [server.json:1-30](https://github.com/rishimeka/genesys/blob/main/server.json) | [src/genesys_memory/server.py:1-20](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n## Component Architecture\n\n### MCP Server Layer\n\nThe MCP Server is the primary interface for client applications. It uses stdio transport for communication, making it suitable for desktop integration.\n\n| Component | Description | Source |\n|-----------|-------------|--------|\n| `app` | Main MCP Server instance | [server.py:20](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py) |\n| `providers` | Storage and tool providers | [server.py:24](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py) |\n| `_TOOL_DISPATCH` | Tool method routing table | [server.py:30-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py) |\n\nThe server initializes providers and tools via `get_providers()`:\n\n```python\nproviders = get_providers()\ntools = providers.tools\n```\n\n**资料来源：** [src/genesys_memory/server.py:23-27](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n### MCP Tools Interface\n\nThe MCP protocol exposes a set of tools that provide the primary interface for memory operations:\n\n| Tool | Description | Required Args |\n|------|-------------|---------------|\n| `memory_store` | Store a new memory with optional causal links | `content` |\n| `memory_recall` | Hybrid search using vector + keyword + graph | `query` |\n| `memory_search` | Filtered search by status, category, date | `query` |\n| `memory_traverse` | Graph traversal from a starting node | `node_id` |\n| `memory_explain` | Explain memory score breakdown | `node_id` |\n| `memory_stats` | Get graph statistics | none |\n| `pin_memory` | Pin memory to core status | `node_id` |\n| `unpin_memory` | Unpin and re-evaluate | `node_id` |\n| `delete_memory` | Permanently delete memory | `node_id` |\n| `list_core_memories` | List core memories by category | `category` (optional) |\n| `set_core_preferences` | Configure core memory categories | `auto`, `approval`, `excluded` |\n\n**资料来源：** [src/genesys_memory/server.py:7-80](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py) | [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Storage Layer\n\nGenesys supports multiple storage backends through a provider abstraction:\n\n```mermaid\ngraph LR\n    subgraph \"Storage Providers\"\n        Memory[\"MemoryProvider\"]\n        Postgres[\"PostgresProvider\"]\n        Obsidian[\"ObsidianProvider\"]\n        FalkorDB[\"FalkorDBProvider\"]\n    end\n    \n    subgraph \"Capabilities\"\n        Cache[\"CacheProvider\"]\n        Embedding[\"EmbeddingProvider\"]\n        EventBus[\"EventBusProvider\"]\n        Graph[\"GraphStorageProvider\"]\n    end\n    \n    Memory & Postgres & Obsidian & FalkorDB --> Cache\n    Memory & Postgres & Obsidian & FalkorDB --> Embedding\n    Memory & Postgres & Obsidian & FalkorDB --> Graph\n    Memory & Postgres & Obsidian & FalkorDB --> EventBus\n```\n\n#### Backend Comparison\n\n| Backend | Install | Use Case | Scalability |\n|---------|---------|----------|-------------|\n| `memory` | Built-in | Zero deps, try it out | Low |\n| `postgres` + pgvector | `genesys-memory[postgres]` | Persistent, scalable | High |\n| Obsidian vault | `genesys-memory[obsidian]` | Local-first knowledge base | Medium |\n| FalkorDB | `genesys-memory[falkordb]` | Graph-native traversal | High |\n\n#### Configuration Options\n\n| Variable | Required | Description |\n|----------|----------|-------------|\n| `OPENAI_API_KEY` | Unless `GENESYS_EMBEDDER=local` | Embeddings provider |\n| `ANTHROPIC_API_KEY` | No | LLM memory processing |\n| `GENESYS_BACKEND` | No | `memory`, `postgres`, `obsidian`, `falkordb` |\n| `GENESYS_EMBEDDER` | No | `openai` or `local` (sentence-transformers) |\n| `DATABASE_URL` | If postgres | Postgres connection string |\n| `OBSIDIAN_VAULT_PATH` | If obsidian | Path to Obsidian vault |\n| `FALKORDB_HOST` | If falkordb | FalkorDB host (default: `localhost`) |\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Data Models\n\n### MemoryNode\n\nThe `MemoryNode` is the core data structure representing a single memory:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    content_ref: str | None = None\n    embedding: list[float] | None = None\n    \n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern\n    irrelevance_counter: int = 0\n    \n    # Stability (spaced repetition)\n    stability: float = 1.0\n    \n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n```\n\n**资料来源：** [src/genesys_memory/models/node.py:6-40](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n### MemoryEdge\n\nRelationships between memories are represented as edges with metadata:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `edge_type` | `EdgeType` | `caused_by`, `supports`, `derived_from` |\n| `confidence` | `float` | 0.0 to 1.0 |\n| `reason` | `str` | Explanation of relationship |\n\n**资料来源：** [src/genesys_memory/engine/llm_provider.py:1-30](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n## Scoring Engine\n\n### Memory Scoring Formula\n\nEvery memory is scored by three forces multiplied together:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n- **Relevance**: Decays over time. Old memories fade unless reinforced\n- **Connectivity**: Rewards memories with many causal links (hub memories survive)\n- **Reactivation**: Boosts frequently accessed memories\n\nBecause the formula is multiplicative, a memory must score on **all three axes** to survive. A highly connected but never-accessed memory still decays.\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### LLM Provider for Causal Relationships\n\nThe LLM Provider identifies causal relationships between new memories and existing ones:\n\n```mermaid\ngraph LR\n    NewMemory[\"New Memory\"] --> LLMPrompt[\"LLM Prompt\"]\n    ExistingMemories[\"Existing Memories\"] --> LLMPrompt\n    LLMPrompt --> LLM[\"LLM API\"]\n    LLM --> Relationships[\"Causal Edges<br/>confidence > 0.6\"]\n```\n\nThe LLM processes:\n- `target_id`: ID of the existing memory\n- `edge_type`: `caused_by`, `supports`, or `derived_from`\n- `confidence`: 0.0 to 1.0\n- `reason`: Brief explanation\n\n**资料来源：** [src/genesys_memory/engine/llm_provider.py:10-30](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n## Memory Lifecycle\n\n### State Machine\n\n```mermaid\ngraph LR\n    STORE[\"STORE\"] --> ACTIVE[\"ACTIVE\"]\n    ACTIVE --> DORMANT[\"DORMANT\"]\n    DORMANT --> FADING[\"FADING\"]\n    FADING --> PRUNED[\"PRUNED\"]\n    \n    ACTIVE -.->|reactivation| ACTIVE\n    DORMANT -.->|reactivation| ACTIVE\n    FADING -.->|reactivation| ACTIVE\n    \n    PRUNED -.->|never| REAPPEAR[\"REAPPEAR\"]\n```\n\n### Lifecycle Rules\n\n| State | Description | Transition Condition |\n|-------|-------------|---------------------|\n| `STORE` | Newly created memory | Initial state |\n| `ACTIVE` | Frequently accessed, high score | Score > threshold |\n| `DORMANT` | Low access, moderate decay | Score declining |\n| `FADING` | Near-zero score | Score approaching 0 |\n| `PRUNED` | Permanently deleted | Score = 0, orphan, not pinned |\n\n### Core Memory Promotion\n\nMemories can be promoted to **core** status — structurally important memories that are:\n- Auto-pinned on promotion\n- Never pruned automatically\n- Assigned a `promotion_reason`\n\n**资料来源：** [src/genesys_memory/models/node.py:35-38](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py) | [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Authentication & Authorization\n\n### Multi-User Mode\n\nThe system supports multi-user operation with organization-level access control:\n\n```python\ndef _caller_owns_node(node: MemoryNode) -> bool:\n    uid = _caller_uid()\n    if uid is None:\n        raise PermissionError(\"current_user_id not set\")\n    role = current_user_role.get(None)\n    if role == \"admin\" and node.org_id in current_org_ids.get([]):\n        return True\n    return node.original_user_id == uid\n```\n\n**资料来源：** [src/genesys_memory/mcp/tools.py:20-35](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n\n### Visibility Levels\n\n| Level | Description | Access |\n|-------|-------------|--------|\n| `private` | User-only | Owner only |\n| `org` | Organization-wide | Org members |\n| `public` | All users | Read access |\n\n**资料来源：** [src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n\n## Tool Dispatch Architecture\n\nThe tool dispatch system maps MCP tool names to internal methods:\n\n```python\n_TOOL_DISPATCH: dict[str, tuple[Any, ...]] = {\n    \"memory_store\": (tools.memory_store, [\"content\"], {\"source_session\": \"\", \"related_to\": None, \"visibility\": \"private\", \"org_id\": None}),\n    \"memory_recall\": (tools.memory_recall, [\"query\"], {\"k\": 10, \"max_results\": None}),\n    \"memory_search\": (tools.memory_search, [\"query\"], {\"filters\": None, \"k\": 10}),\n    \"memory_traverse\": (tools.memory_traverse, [\"node_id\"], {\"depth\": 2, \"edge_types\": None}),\n    \"memory_explain\": (tools.memory_explain, [\"node_id\"], {}),\n    \"pin_memory\": (tools.pin_memory, [\"node_id\"], {}),\n    \"unpin_memory\": (tools.unpin_memory, [\"node_id\"], {}),\n    \"list_core_memories\": (tools.list_core_memories, [], {\"category\": None}),\n    \"delete_memory\": (tools.delete_memory, [\"node_id\"], {}),\n    \"memory_stats\": (tools.memory_stats, [], {}),\n    \"set_core_preferences\": (tools.set_core_preferences, [], {}),\n}\n```\n\nEach entry contains:\n1. The method to call\n2. Required argument names\n3. Optional arguments with default values\n\n**资料来源：** [src/genesys_memory/server.py:30-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n## Deployment Topologies\n\n### Development Mode (In-Memory)\n\n```bash\npip install genesys-memory\ncp .env.example .env\nuvicorn genesys.api:app --port 8000\n```\n\nSuitable for local development with zero infrastructure.\n\n### Production Mode (Postgres)\n\n```bash\npip install 'genesys-memory[postgres]'\ndocker compose up -d postgres\nalembic upgrade head\nGENESYS_BACKEND=postgres uvicorn genesys.api:app --port 8000\n```\n\n### Claude Desktop Integration\n\n```json\n{\n  \"mcpServers\": {\n    \"genesys\": {\n      \"url\": \"http://localhost:8000/mcp\"\n    }\n  }\n}\n```\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Performance Characteristics\n\n### Benchmark Results (LoCoMo Benchmark)\n\n| Category | J-Score |\n|----------|---------|\n| Single-hop | 94.3% |\n| Temporal | 87.5% |\n| Multi-hop | 69.8% |\n| Open-domain | 91.7% |\n| **Overall** | **89.9%** |\n\nCompared to alternatives:\n- Mem0: 67.1%\n- Zep: 75.1%\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Dependencies\n\n### Core Requirements\n\n| Package | Purpose |\n|---------|---------|\n| `mcp` | Model Context Protocol server |\n| `pydantic` | Data validation |\n| `fastapi` | API framework |\n| `uvicorn` | ASGI server |\n\n### Optional Dependencies\n\n| Extra | Packages |\n|-------|----------|\n| `postgres` | `psycopg2-binary`, `alembic`, `asyncpg` |\n| `obsidian` | `python-dotenv` |\n| `local` | `sentence-transformers` |\n\n**资料来源：** [CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md) | [server.json](https://github.com/rishimeka/genesys/blob/main/server.json)\n\n---\n\n<a id='memory-scoring'></a>\n\n## Memory Scoring Engine\n\n### 相关页面\n\n相关主题：[Memory Lifecycle Management](#memory-lifecycle)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/engine/transitions.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n- [src/genesys_memory/engine/config.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/config.py)\n- [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n</details>\n\n# Memory Scoring Engine\n\n## Overview\n\nThe Memory Scoring Engine is the core intelligence layer of Genesys that determines which memories survive, decay, or get promoted to core status. It implements a multiplicative scoring formula that evaluates memories across three dimensions: relevance, connectivity, and reactivation frequency.\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Architecture\n\n### Core Components\n\nThe scoring engine consists of several interconnected modules:\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| Scoring Calculator | `engine/scoring.py` | Computes the decay score for each memory node |\n| Configuration | `engine/config.py` | Defines thresholds and env-configurable parameters |\n| Reactivation Handler | `engine/reactivation.py` | Tracks and updates memory access patterns |\n| Transition Engine | `engine/transitions.py` | Evaluates and executes state transitions |\n| LLM Provider | `engine/llm_provider.py` | LLM-based consolidation and contradiction detection |\n\n资料来源：[engine/transitions.py:1-15](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\n### Scoring Formula\n\nThe decay score is calculated as the product of three independent factors:\n\n```mermaid\ngraph TD\n    A[Memory Node] --> B[Relevance Score]\n    A --> C[Connectivity Score]\n    A --> D[Reactivation Score]\n    B --> E[decay_score]\n    C --> E\n    D --> E\n    E --> F{decay_score > threshold?}\n```\n\n1. **Relevance**: Decays over time. Old memories fade unless reinforced through recall or context reactivation.\n2. **Connectivity**: Rewards memories with many causal links. Hub memories (highly connected nodes) survive longer.\n3. **Reactivation**: Boosts memories that are repeatedly accessed. Frequency of recall matters.\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Multiplicative Nature\n\nBecause the formula is multiplicative, a memory must score on **all three** axes to survive:\n\n| Scenario | Relevance | Connectivity | Reactivation | Result |\n|----------|-----------|--------------|--------------|--------|\n| High connections, never accessed | ✓ | ✓ | ✗ | Memory decays |\n| Frequently recalled, no links | ✓ | ✗ | ✓ | Memory fades |\n| Old but connected and active | ✗ | ✓ | ✓ | May survive |\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Memory Node Data Model\n\nEach memory node stores scoring-related metrics:\n\n```python\nclass MemoryNode(BaseModel):\n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern = ReactivationPattern.SINGLE\n    irrelevance_counter: int = 0\n    \n    # Stability (increases on successful retrieval, per spaced repetition)\n    stability: float = 1.0\n    \n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Core memory flags\n    pinned: bool = False\n    promotion_reason: str | None = None\n```\n\n资料来源：[src/genesys_memory/models/node.py:20-40](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n### Scoring Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `decay_score` | `float` | Combined score (0.0 to 1.0), product of all factors |\n| `causal_weight` | `int` | Number of incoming/outgoing causal edges |\n| `reactivation_count` | `int` | Total times memory was successfully recalled |\n| `reactivation_pattern` | `ReactivationPattern` | Pattern type: SINGLE, SPIKE, or CONSOLIDATED |\n| `irrelevance_counter` | `int` | Consecutive failed relevance matches |\n| `stability` | `float` | Retrieval success rate (spaced repetition factor) |\n| `pinned` | `bool` | If True, memory is exempt from pruning |\n\n资料来源：[src/genesys_memory/models/node.py:25-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n## State Transitions\n\n### Lifecycle States\n\n```mermaid\nstateDiagram-v2\n    [*] --> STORE: Store new memory\n    STORE --> ACTIVE: Edge formed (consolidation)\n    ACTIVE --> DORMANT: Low reactivation\n    DORMANT --> ACTIVE: Reactivation\n    DORMANT --> FADING: Extended inactivity\n    FADING --> ACTIVE: Reactivation\n    FADING --> PRUNED: Score reaches 0 OR orphaned\n    ACTIVE --> CORE: Promotion evaluation\n    CORE --> [*]: Manual unpin\n```\n\n### Transition Evaluation\n\nThe transition engine evaluates all non-core, non-pruned nodes:\n\n```python\nasync def evaluate_transitions(\n    graph: GraphStorageProvider,\n    embeddings: EmbeddingProvider,\n    llm: LLMProvider,\n    context_embedding: list[float] | None = None,\n    context_entities: list[str] | None = None,\n) -> list[dict[str, Any]]:\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:15-23](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\n### Transition Rules\n\n| From State | To State | Trigger Condition |\n|------------|----------|-------------------|\n| TAGGED | ACTIVE | Node has edges (consolidation signal) |\n| ACTIVE | DORMANT | Low reactivation + relevance drops |\n| DORMANT | ACTIVE | Successful reactivation recall |\n| DORMANT | FADING | Extended inactivity period |\n| FADING | PRUNED | `decay_score = 0` or orphaned + not pinned |\n\n资料来源：[src/genesys_memory/engine/transitions.py:25-40](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\n### Tagged Memory Expiration\n\nTagged memories auto-expire after 24 hours if no connections form:\n\n```python\n# Auto-expire tagged memories after 24h with no connections\nage_hours = (datetime.now(timezone.utc) - node.created_at).total_seconds() / 3600\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:40-41](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\n## Reactivation Patterns\n\nReactivation tracks how memories are accessed over time:\n\n| Pattern | Description | Effect on Score |\n|---------|-------------|-----------------|\n| `SINGLE` | Single retrieval event | Baseline reactivation boost |\n| `SPIKE` | Burst of retrievals | Stronger boost, may indicate importance |\n| `CONSOLIDATED` | Regular spaced retrieval | Maximum stability increase |\n\n资料来源：[src/genesys_memory/models/node.py:30](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n## Core Memory Promotion\n\nMemories can be promoted to **core status** — structurally important memories that are:\n- Auto-pinned on promotion\n- Never pruned\n- Automatically identified based on graph centrality\n\n```mermaid\ngraph LR\n    A[High Causal Weight] --> B{Evaluate Core<br/>Promotion}\n    C[Category Match] --> B\n    D[User Annotation] --> B\n    B --> E[Pin Memory]\n    E --> F[Mark as Core]\n```\n\nMemories eligible for core promotion must:\n1. Have high causal weight (hub nodes)\n2. Match configured category patterns\n3. Not be manually excluded\n\n资料来源：[src/genesys_memory/mcp/tools.py:35-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n\n## Configuration\n\nEngine thresholds are environment-configurable and should not be hardcoded:\n\n| Parameter | Source | Default | Description |\n|-----------|--------|---------|-------------|\n| Decay rates | `engine/config.py` | Environment | Time-based relevance decay |\n| Causal thresholds | `engine/config.py` | Environment | Min connections for hub status |\n| Reactivation boost | `engine/config.py` | Environment | Multiplier for recall events |\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n## LLM Integration\n\nThe scoring engine uses LLM providers for advanced operations:\n\n### Consolidation\n\nCombines episodic memories into coherent summaries:\n\n```python\nasync def consolidate(self, episodic_memories: list[str]) -> str:\n    memories_text = \"\\n\".join(f\"- {m}\" for m in episodic_memories)\n    # LLM generates consolidated summary\n```\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:45-50](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n### Causal Link Detection\n\nAutomatically identifies relationships between memories:\n\n```python\nasync def identify_causal_relationships(\n    new_memory: str,\n    existing_memories: list[tuple[str, str]]\n) -> list[tuple[str, EdgeType, float, str | None]]:\n```\n\nEdge types detected:\n- `caused_by` — Causal dependency\n- `supports` — Supporting evidence\n- `derived_from` — Extracted from source\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:15-35](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n### Confidence Threshold\n\nOnly relationships with confidence > 0.6 are included:\n\n```\n\"Only include relationships with confidence > 0.6.\"\n```\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:25](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n## MCP Tools for Scoring\n\n| Tool | Function | Scoring Impact |\n|------|----------|----------------|\n| `memory_recall` | Hybrid search (vector + keyword + graph) | Updates `last_reactivated_at`, increments `reactivation_count` |\n| `memory_traverse` | Graph walk from node | May boost connectivity scores |\n| `memory_explain` | Score breakdown analysis | Read-only |\n| `pin_memory` | Manual core promotion | Sets `pinned=True`, exempts from pruning |\n| `unpin_memory` | Remove core status | Re-evaluates core eligibility |\n\n资料来源：[src/genesys_memory/server.py:10-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n## Engine Workflow\n\n```mermaid\ngraph TD\n    A[Memory Store Request] --> B{Parse & Validate}\n    B -->|Valid| C[Generate Embedding]\n    B -->|Invalid| Z[Reject]\n    C --> D[LLM: Identify Causal Links]\n    D --> E[Graph: Create Node + Edges]\n    E --> F[Initial Scoring]\n    F --> G[Evaluate Transitions]\n    G --> H{Transition Needed?}\n    H -->|Yes| I[Update State]\n    H -->|No| J[Index for Retrieval]\n    I --> J\n    J --> K[Return to Client]\n    \n    L[Recall Query] --> M[Vector Search]\n    M --> N[Graph Spreading Activation]\n    N --> O[Rank by decay_score]\n    O --> P[Update Reactivation Metrics]\n    P --> Q[Return Ranked Results]\n```\n\n## Benchmark Performance\n\nThe scoring engine was evaluated on the [LoCoMo](https://arxiv.org/abs/2402.06397) benchmark:\n\n| Category | J-Score |\n|----------|---------|\n| Single-hop | 94.3% |\n| Temporal | 87.5% |\n| Multi-hop | 69.8% |\n| Open-domain | 91.7% |\n| **Overall** | **89.9%** |\n\nCompared against:\n- Mem0: 67.1%\n- Zep: 75.1%\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Testing\n\nThe scoring engine modules are tightly coupled. When modifying scoring, transitions, or forgetting logic, run the full test suite:\n\n```bash\n# Run all unit tests\npytest tests/ -v\n\n# With coverage\npytest tests/ -v --cov=src/genesys_memory --cov-report=term-missing\n```\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n---\n\n<a id='memory-lifecycle'></a>\n\n## Memory Lifecycle Management\n\n### 相关页面\n\n相关主题：[Memory Scoring Engine](#memory-scoring), [Nodes and Edges Data Models](#nodes-edges)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/engine/transitions.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n</details>\n\n# Memory Lifecycle Management\n\nMemory Lifecycle Management is the core intelligence layer of Genesys that governs how memories are created, scored, transitioned between states, consolidated, and ultimately forgotten. It provides an intelligent forgetting mechanism that goes beyond simple time-based decay by evaluating memories through a multiplicative scoring formula that considers relevance, connectivity, and reactivation patterns.\n\n## Overview\n\nGenesys implements an active memory management system where memories are not passive storage entries but dynamic entities governed by lifecycle rules. Every memory in the system follows a deterministic path from creation through potential promotion or eventual pruning.\n\nThe lifecycle management system consists of several interconnected components:\n\n| Component | Purpose |\n|-----------|---------|\n| **Transitions Engine** | Evaluates and executes status changes between memory states |\n| **Scoring Engine** | Calculates decay scores using relevance, connectivity, and reactivation |\n| **Consolidation Engine** | Processes episodic memories and forms causal relationships |\n| **Forgetting Engine** | Handles pruning of low-value, orphaned memories |\n| **Promotion System** | Manages core memory designation and pinning |\n\n资料来源：[src/genesys_memory/engine/transitions.py:1-20]()\n\n## Memory States\n\nMemories exist in one of several distinct states, defined by the `MemoryStatus` enum. Each state represents a different phase in the memory's lifecycle with specific behavioral characteristics.\n\n```mermaid\ngraph TD\n    STORED[\"STORE (New)\"] --> ACTIVE[\"ACTIVE\"]\n    ACTIVE --> DORMANT[\"DORMANT\"]\n    DORMANT --> FADING[\"FADING\"]\n    FADING --> PRUNED[\"PRUNED\"]\n    \n    ACTIVE -.-> REACTIVATION[\"reactivation\"]\n    REACTIVATION -.-> ACTIVE\n    \n    FADING -.->|score=0, orphan, not pinned| PRUNED\n    \n    STYLED_STORE{{\"Created - waiting for consolidation\"}}\n    STYLED_ACTIVE{{\"In use - scored and tracked\"}}\n    STYLED_DORMANT{{\"Low usage - may be accessed\"}}\n    STYLED_FADING{{\"About to be forgotten\"}}\n    STYLED_PRUNED{{\"Permanently deleted\"}}\n```\n\n### State Definitions\n\n| State | Description | Auto-transition |\n|-------|-------------|------------------|\n| `TAGGED` | Newly created, awaiting consolidation signal | 24h timeout → PRUNED |\n| `ACTIVE` | Currently relevant, regularly scored | Decay → DORMANT |\n| `DORMANT` | Infrequently accessed, reduced priority | Further decay → FADING |\n| `FADING` | Pending deletion, low score | score=0 → PRUNED |\n| `PRUNED` | Permanently deleted | None |\n\n资料来源：[src/genesys_memory/models/enums.py]() (MemoryStatus enum referenced in transitions.py)\n\n### State Transition Rules\n\nThe transition engine evaluates non-core, non-pruned nodes for status changes. The evaluation follows these rules:\n\n1. **Tagged → Active**: Promote when the node has formed causal edges (consolidation signal received)\n2. **Active → Dormant**: When reactivation count drops below threshold\n3. **Dormant → Fading**: When decay score falls to critical levels\n4. **Fading → Pruned**: Only when `score=0`, node is an orphan, and not pinned\n\n```python\n# From transitions.py - key evaluation logic\nasync def evaluate_transitions(\n    graph: GraphStorageProvider,\n    embeddings: EmbeddingProvider,\n    llm: LLMProvider,\n    context_embedding: list[float] | None = None,\n    context_entities: list[str] | None = None,\n) -> list[dict[str, Any]]:\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:18-25]()\n\n## The Scoring System\n\nEvery memory is scored by three forces multiplied together, forming the core intelligence of the lifecycle management system:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n### Scoring Components\n\n| Component | Description | Behavior |\n|-----------|-------------|----------|\n| **Relevance** | Time-based decay factor | Old memories fade unless reinforced |\n| **Connectivity** | Causal graph weight | Rewards memories with many causal links; hub memories survive |\n| **Reactivation** | Access frequency | Boosts memories that keep being recalled |\n\nBecause the formula is multiplicative, a memory must score on **all three axes** to survive. A highly connected but never-accessed memory still decays. A frequently recalled but causally orphaned memory still fades.\n\n```mermaid\ngraph LR\n    subgraph \"Score Factors\"\n        R[Relevance]\n        C[Connectivity]\n        A[Reactivation]\n    end\n    \n    R --> MULT[\"×\"]\n    C --> MULT\n    A --> MULT\n    MULT --> SCORE[decay_score]\n    \n    SCORE -->|high| SURVIVE[\"SURVIVE\"]\n    SCORE -->|zero| PRUNE[\"PRUNED\"]\n```\n\n资料来源：[src/genesys_memory/engine/scoring.py]() (referenced in transitions.py)\n\n## Memory Node Data Model\n\nEach memory in the system is represented by a `MemoryNode` that tracks all lifecycle-relevant attributes:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern = ReactivationPattern.SINGLE\n    \n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n    \n    # Stability\n    stability: float = 1.0\n```\n\n资料来源：[src/genesys_memory/models/node.py:14-45]()\n\n### Key Lifecycle Fields\n\n| Field | Type | Purpose |\n|-------|------|---------|\n| `decay_score` | `float` | Current composite score (0.0 to 1.0) |\n| `causal_weight` | `int` | Number of causal connections |\n| `reactivation_count` | `int` | Number of successful recalls |\n| `reactivation_pattern` | `ReactivationPattern` | SINGLE, REPEATED, or CONSOLIDATED |\n| `stability` | `float` | Increases on successful retrieval (spaced repetition) |\n| `pinned` | `bool` | Core memory flag - never pruned |\n| `irrelevance_counter` | `int` | Consecutive low-relevance evaluations |\n\n## MCP Tools for Lifecycle Management\n\nThe MCP server exposes tools for programmatic lifecycle management:\n\n| Tool | Description |\n|------|-------------|\n| `memory_explain` | Explain why a memory exists and its causal chain |\n| `pin_memory` | Pin a memory so it's never forgotten |\n| `unpin_memory` | Unpin a previously pinned memory |\n| `list_core_memories` | List core memories, optionally filtered by category |\n| `memory_stats` | Get memory system statistics |\n| `promote_to_org` | Promote a private memory to org visibility |\n\n资料来源：[src/genesys_memory/server.py:40-90]()\n\n### Core Preferences Configuration\n\nUsers can configure automatic core memory behavior:\n\n```python\nTool(name=\"set_core_preferences\", description=\"Configure core memory category preferences.\", inputSchema={\n    \"type\": \"object\",\n    \"properties\": {\n        \"auto\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n        \"approval\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n        \"excluded\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n    },\n})\n```\n\n资料来源：[src/genesys_memory/server.py:80-90]()\n\n## Engine Thresholds\n\nThe lifecycle behavior is controlled through configurable thresholds defined in `engine/config.py`. These thresholds govern transition points and scoring calculations.\n\n| Threshold | Default | Description |\n|-----------|---------|-------------|\n| Active→Dormant decay | Configurable | Score threshold for dormancy |\n| Dormant→Fading decay | Configurable | Score threshold for fading |\n| Orphan detection | 0 edges | Nodes with no causal connections |\n| Reactivation boost | Configurable | Multiplier for recalled memories |\n\n> **Note:** Engine thresholds are environment-configurable. Do not hardcode magic numbers in engine files.\n\n资料来源：[src/genesys_memory/engine/config.py]() (referenced in CONTRIBUTING.md)\n\n## Consolidation and Causal Edge Formation\n\nWhen new memories are stored, the LLM provider analyzes relationships with existing memories to form causal edges:\n\n```python\nasync def identify_causal_relationships(\n    self,\n    new_memory: str,\n    existing_memories: list[tuple[str, str]],\n) -> list[tuple[str, EdgeType, float, str | None]]:\n```\n\nThe provider identifies three types of causal relationships:\n\n| Edge Type | Description |\n|-----------|-------------|\n| `caused_by` | Causal dependency |\n| `supports` | Supporting evidence |\n| `derived_from` | Information lineage |\n\nRelationships are only created when confidence exceeds 0.6.\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:30-60]()\n\n## Reactivation Patterns\n\nMemories track how they are reactivated, which affects scoring:\n\n| Pattern | Description |\n|---------|-------------|\n| `SINGLE` | Occasional single recall |\n| `REPEATED` | Frequently recalled |\n| `CONSOLIDATED` | Formed connections during consolidation |\n\nReactivation history is stored as timestamps in `reactivation_timestamps`, allowing the system to implement spaced repetition principles where successful retrievals increase memory stability.\n\n资料来源：[src/genesys_memory/models/node.py:35-40]()\n\n## Permissions and Ownership\n\nLifecycle management respects multi-tenant permissions:\n\n```python\ndef _caller_owns_node(node: MemoryNode) -> bool:\n    \"\"\"Check if the current caller is the original owner of a node.\"\"\"\n    uid = _caller_uid()\n    if uid is None:\n        raise PermissionError(\"current_user_id not set — cannot verify ownership\")\n    role = current_user_role.get(None)\n    if role == \"admin\" and node.org_id and node.org_id in current_org_ids.get([]):\n        return True\n    if node.original_user_id:\n        return node.original_user_id == uid\n    return True\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:25-38]()\n\n## Benchmark Performance\n\nThe lifecycle management system was evaluated on the [LoCoMo](https://arxiv.org/abs/2402.06397) benchmark:\n\n| Category | J-Score |\n|----------|---------|\n| Single-hop | 94.3% |\n| Temporal | 87.5% |\n| Multi-hop | 69.8% |\n| Open-domain | 91.7% |\n| **Overall** | **89.9%** |\n\nFor comparison, Mem0 scored 67.1% and Zep scored 75.1% on the same benchmark.\n\n---\n\n<a id='nodes-edges'></a>\n\n## Nodes and Edges Data Models\n\n### 相关页面\n\n相关主题：[Graph Traversal and Causal Reasoning](#graph-traversal), [Storage Provider Implementation](#storage-implementation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/edge.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/edge.py)\n- [src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n- [src/genesys_memory/models/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/__init__.py)\n- [src/genesys_memory/engine/consolidation.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/consolidation.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [src/genesys_memory/engine/transitions.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n</details>\n\n# Nodes and Edges Data Models\n\nThe Nodes and Edges data models form the foundational graph structure of the Genesys memory system. Every piece of information stored in Genesys is represented as a node within a causal graph, with relationships between memories expressed through typed edges. This graph-native approach enables sophisticated memory operations including traversal, causal reasoning, and intelligent forgetting based on connectivity patterns.\n\n## Overview\n\nThe data model architecture consists of two primary entities:\n\n- **MemoryNode**: Represents an individual memory with content, metadata, embedding vectors, and lifecycle state\n- **MemoryEdge**: Represents a typed, weighted relationship between two memory nodes\n\nTogether, these constructs enable the causal graph that powers Genesys's memory intelligence layer. The graph structure supports operations like vector similarity search, causal traversal, and the multiplicative scoring formula that determines memory survival.\n\n## MemoryNode Model\n\nThe `MemoryNode` class represents the core unit of memory storage in the Genesys system. Each node encapsulates both the semantic content of a memory and its operational metadata.\n\n### Core Attributes\n\n```python\n@dataclass\nclass MemoryNode:\n    id: UUID\n    status: MemoryStatus\n    content_summary: str\n    content_full: str\n    embedding: list[float]\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    entity_refs: list[str]\n    # Additional fields from source code\n    original_user_id: Optional[str] = None\n    org_id: Optional[str] = None\n    visibility: Visibility = Visibility.PRIVATE\n    is_pinned: bool = False\n    category: Optional[str] = None\n```\n\n### Attribute Descriptions\n\n| Attribute | Type | Description |\n|-----------|------|-------------|\n| `id` | `UUID` | Unique identifier for the memory node |\n| `status` | `MemoryStatus` | Current lifecycle state (ACTIVE, TAGGED, DORMANT, etc.) |\n| `content_summary` | `str` | Concise summary of the memory content |\n| `content_full` | `str` | Complete memory content |\n| `embedding` | `list[float]` | Vector representation for similarity search |\n| `created_at` | `datetime` | Timestamp when the memory was created |\n| `last_accessed_at` | `datetime` | Timestamp of most recent access |\n| `last_reactivated_at` | `datetime` | Timestamp of most recent recall operation |\n| `entity_refs` | `list[str]` | References to entities mentioned in the memory |\n| `original_user_id` | `str` | User who originally created the memory |\n| `org_id` | `str` | Organization ID for org-scoped memories |\n| `visibility` | `Visibility` | Access level (PRIVATE, ORG, PUBLIC) |\n| `is_pinned` | `bool` | Whether memory is protected from pruning |\n| `category` | `str` | Optional categorization for filtering |\n\n### MemoryStatus Enum\n\nThe lifecycle state of a memory node is governed by the `MemoryStatus` enum, which defines the progression from creation through potential pruning.\n\n资料来源：[src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n\n```python\nclass MemoryStatus(Enum):\n    SEMANTIC = \"semantic\"    # LLM-consolidated abstract memory\n    ACTIVE = \"active\"        # Frequently accessed, high relevance\n    TAGGED = \"tagged\"        # Newly created, not yet consolidated\n    DORMANT = \"dormant\"      # Decaying relevance, low access\n    FADING = \"fading\"        # Near-pruning threshold\n    PRUNED = \"pruned\"        # Permanently removed\n```\n\n### Lifecycle State Transitions\n\n```mermaid\ngraph TD\n    TAGGED[TAGGED] -->|consolidation signal| ACTIVE[ACTIVE]\n    TAGGED -->|24h no connections| PRUNED[PRUNED]\n    ACTIVE -->|decay score drops| DORMANT[DORMANT]\n    DORMANT -->|reactivation| ACTIVE\n    DORMANT -->|score continues declining| FADING[FADING]\n    FADING -->|score = 0| PRUNED\n    FADING -->|reactivation| DORMANT\n    TAGGED -->|LLM consolidation| SEMANTIC[SEMANTIC]\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:1-50](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\nThe transition engine evaluates nodes for state changes based on:\n\n1. **Consolidation signals**: Tagged nodes with formed edges promote to active\n2. **Decay scoring**: Low scores trigger transitions toward dormant and fading states\n3. **Reactivation**: Recall operations boost nodes back toward active status\n\n## MemoryEdge Model\n\nThe `MemoryEdge` class represents relationships between memory nodes, enabling the causal graph structure that powers Genesys's understanding of memory interconnectedness.\n\n### Core Attributes\n\n```python\n@dataclass\nclass MemoryEdge:\n    source_id: UUID\n    target_id: UUID\n    type: EdgeType\n    weight: float\n    reason: Optional[str] = None\n    created_by: Optional[str] = None\n```\n\n### Attribute Descriptions\n\n| Attribute | Type | Description |\n|-----------|------|-------------|\n| `source_id` | `UUID` | ID of the memory node where the edge originates |\n| `target_id` | `UUID` | ID of the memory node where the edge points |\n| `type` | `EdgeType` | Semantic relationship type |\n| `weight` | `float` | Connection strength (0.0 to 1.0) |\n| `reason` | `str` | Explanation of why the relationship exists |\n| `created_by` | `str` | Provenance: \"user_explicit\", \"auto_link\", or LLM-generated |\n\n### EdgeType Enum\n\nThe relationship semantics between memory nodes are defined by the `EdgeType` enum, which categorizes different kinds of causal and associative connections.\n\n资料来源：[src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n\n```python\nclass EdgeType(Enum):\n    CAUSED_BY = \"caused_by\"       # Causal relationship: source caused target\n    SUPPORTS = \"supports\"         # Evidential: source supports/validates target\n    DERIVED_FROM = \"derived_from\" # Created from: source derived from target\n    RELATED_TO = \"related_to\"     # Semantic similarity\n```\n\n### Edge Relationship Types\n\n| Edge Type | Direction | Semantics | Typical Weight |\n|-----------|-----------|-----------|----------------|\n| `CAUSED_BY` | source → target | Source memory caused/influenced target | 0.7 |\n| `SUPPORTS` | source → target | Source provides evidence for target | 0.8 |\n| `DERIVED_FROM` | source → target | Source is abstracted from target | 0.7 |\n| `RELATED_TO` | bidirectional | Semantic similarity connection | 0.3-1.0 |\n\n## Graph Data Flow\n\nThe interaction between nodes and edges creates the causal graph that powers Genesys's memory operations.\n\n```mermaid\ngraph LR\n    subgraph MemoryNode[MemoryNode]\n        N1[Content + Embedding]\n        N2[Status + Timestamps]\n        N3[Entity References]\n    end\n    \n    subgraph MemoryEdge[MemoryEdge]\n        E1[Source → Target]\n        E2[Type + Weight]\n        E3[Reason + Provenance]\n    end\n    \n    N1 -->|links| E1\n    N2 -->|determines| E1\n    N3 -->|informs| E2\n```\n\n## Memory Storage Operations\n\nThe storage layer implements the `GraphStorageProvider` interface to persist and query nodes and edges across different backend options.\n\n### Node Creation\n\nWhen storing a new memory, the system performs the following operations:\n\n1. Generate embedding vector via the configured `EmbeddingProvider`\n2. Create the `MemoryNode` with initial `TAGGED` status\n3. Create explicit `CAUSED_BY` edges for related memories\n4. Auto-link to semantically similar existing memories via vector search\n\n资料来源：[src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n\n```python\n# Auto-link to semantically similar existing memories\nif embedding:\n    similar = await self.graph.vector_search(embedding, k=4, org_ids=org_ids)\n    for other_node, score in similar:\n        if score < 0.3:\n            continue\n        edge = MemoryEdge(\n            source_id=node.id,\n            target_id=other_node.id,\n            type=EdgeType.RELATED_TO,\n            weight=round(score, 4),\n            reason=f\"cosine similarity {score:.3f}\",\n            created_by=\"auto_link\",\n        )\n        await self.graph.create_edge(edge)\n```\n\n### Consolidation Operations\n\nThe consolidation engine creates `SEMANTIC` nodes from related episodic memories, establishing `DERIVED_FROM` edges to track the abstraction chain.\n\n资料来源：[src/genesys_memory/engine/consolidation.py:200](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/consolidation.py)\n\n```python\n# Create DERIVED_FROM edges\nfor source_node in matching:\n    edge = MemoryEdge(\n        source_id=semantic_node.id,\n        target_id=source_node.id,\n        type=EdgeType.DERIVED_FROM,\n        weight=0.7,\n    )\n    await graph.create_edge(edge)\n```\n\n## Visibility and Access Control\n\nMemory nodes support three visibility levels that govern cross-user and cross-organization access:\n\n```python\nclass Visibility(Enum):\n    PRIVATE = \"private\"   # Only visible to original user\n    ORG = \"org\"           # Visible to organization members\n    PUBLIC = \"public\"     # Visible to all users\n```\n\n### Org Boundary Rules\n\nWhen a memory has `ORG` visibility:\n\n- Edges can only connect to other `ORG` nodes within the same organization\n- Private nodes cannot link to org-scoped nodes\n- This isolation ensures data governance compliance\n\n## ReactivationPattern Enum\n\nThe reactivation behavior tracking is defined by the `ReactivationPattern` enum, which captures how memories are accessed and reinforced over time.\n\n```python\nclass ReactivationPattern(Enum):\n    # Patterns for tracking memory access patterns\n    EXPLICIT = \"explicit\"      # Direct recall request\n    IMPLICIT = \"implicit\"      # Accessed via graph traversal\n    CONSOLIDATED = \"consolidated\"  # Incorporated into semantic memory\n```\n\n## Integration with MCP Tools\n\nThe MCP server exposes tools that operate on the nodes and edges data models:\n\n| MCP Tool | Operation | Data Model Impact |\n|----------|-----------|-------------------|\n| `memory_store` | Store new memory | Creates node + edges |\n| `memory_recall` | Recall by query | Updates `last_reactivated_at` |\n| `memory_traverse` | Graph walk | Reads nodes + edges |\n| `memory_explain` | Score breakdown | Reads node + connected edges |\n| `pin_memory` | Protect from pruning | Sets `is_pinned=True` |\n| `delete_memory` | Remove memory | Deletes node + all edges |\n\n## Scoring Formula Integration\n\nThe nodes and edges data models directly support the multiplicative scoring formula:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n- **Relevance**: Derived from `created_at` and `last_accessed_at` timestamps\n- **Connectivity**: Calculated from edge weights connected to the node\n- **Reactivation**: Boosted when `last_reactivated_at` is recent\n\nThe graph structure enables the connectivity calculation by summing weighted edges, while timestamps on nodes track relevance and reactivation factors.\n\n## Storage Backend Options\n\nThe nodes and edges data models are abstracted behind the `GraphStorageProvider` interface, enabling multiple backend options:\n\n| Backend | Description | Use Case |\n|---------|-------------|----------|\n| `memory` | In-memory Python dict/list | Development, testing |\n| `postgres` | PostgreSQL with pgvector | Production, scalable |\n| `obsidian` | SQLite sidecar in vault | Local-first knowledge base |\n| `falkordb` | Redis-based graph database | Graph-native traversal |\n\n## Summary\n\nThe Nodes and Edges data models provide the structural foundation for Genesys's causal graph memory system. `MemoryNode` captures the content, state, and metadata of individual memories, while `MemoryEdge` expresses the typed, weighted relationships between them. Together with the lifecycle states defined in `MemoryStatus` and relationship semantics in `EdgeType`, these models enable sophisticated memory operations including intelligent forgetting, causal reasoning, and semantic consolidation.\n\n资料来源：[src/genesys_memory/models/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/__init__.py)\n\n---\n\n<a id='graph-traversal'></a>\n\n## Graph Traversal and Causal Reasoning\n\n### 相关页面\n\n相关主题：[Nodes and Edges Data Models](#nodes-edges), [MCP Tools Reference](#mcp-tools)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/engine/contradiction.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/contradiction.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [src/genesys_memory/engine/transitions.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n- [src/genesys_memory/engine/consolidation.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/consolidation.py)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n- [src/genesys_memory/storage/memory.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/memory.py)\n</details>\n\n# Graph Traversal and Causal Reasoning\n\nGenesys implements a sophisticated graph-based memory system where memories are interconnected through causal relationships. This design enables the system to traverse memory networks, explain why memories exist, detect contradictions, and intelligently consolidate related information.\n\n## Architecture Overview\n\nThe graph traversal and causal reasoning system consists of several interconnected components that work together to maintain a living memory network.\n\n```mermaid\ngraph TB\n    subgraph \"Graph Layer\"\n        TRAVERSE[memory_traverse]\n        EXPLAIN[memory_explain]\n        CAUSAL[Causal Chain Resolution]\n    end\n    \n    subgraph \"Engine Layer\"\n        CONTRADICT[Contradiction Detection]\n        CONSOLIDATE[Memory Consolidation]\n        TRANSITIONS[Status Transitions]\n        LLM_PROC[LLM Provider]\n    end\n    \n    subgraph \"Storage Layer\"\n        GRAPH[GraphStorageProvider]\n        VECTOR[Vector Search]\n    end\n    \n    TRAVERSE --> GRAPH\n    EXPLAIN --> CAUSAL\n    CAUSAL --> GRAPH\n    CONTRADICT --> VECTOR\n    CONTRADICT --> LLM_PROC\n    CONSOLIDATE --> LLM_PROC\n    TRANSITIONS --> GRAPH\n    GRAPH --> VECTOR\n```\n\n## Causal Chain Resolution\n\nCausal chains represent the lineage and relationships between memories. Each memory can have upstream causes (memories that influenced it) and downstream effects (memories it influenced).\n\n### How Causal Chains Work\n\nWhen a memory is stored or recalled, the system resolves its causal context by fetching neighboring nodes in both directions. The causal chain is limited to the top 5 most relevant upstream and downstream nodes to maintain performance while providing meaningful context.\n\n```mermaid\ngraph LR\n    A[Memory A] -->|caused_by| B[Memory B]\n    B -->|caused_by| C[Memory C]\n    C -->|caused_by| D[Memory D]\n    \n    style A fill:#e1f5fe\n    style D fill:#ffcdd2\n```\n\n### Causal Chain Data Structure\n\nWhen explaining a memory, the system builds a structured response containing:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Memory node UUID |\n| `summary` | string | Content summary of the memory |\n| `direction` | string | \"upstream\" or \"downstream\" |\n| `causal_chain` | array | Ordered list from origin to target |\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-1]()\n\n### Implementation Details\n\nThe causal chain resolution iterates through upstream and downstream nodes, collecting their summaries and preventing duplicates via a `seen_causal` set:\n\n```python\nseen_causal: set[str] = set()\nfor n in upstream[:5]:\n    nid_str = str(n.id)\n    if nid_str not in seen_causal:\n        causal_basis.append({\"id\": nid_str, \"summary\": n.content_summary, \"direction\": \"upstream\"})\n        seen_causal.add(nid_str)\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-1]()\n\n## Memory Traversal\n\nThe `memory_traverse` MCP tool enables walking the causal graph from any given memory node. This is fundamental for understanding memory context and retrieving related information.\n\n### Traversal Workflow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCP as MCP Server\n    participant Graph as GraphStorageProvider\n    participant Vector as Vector Search\n    \n    Client->>MCP: memory_traverse(node_id, direction)\n    MCP->>Graph: get_causal_chain(node_id, direction)\n    Graph->>Vector: vector_search(embedding, k)\n    Vector-->>Graph: similar nodes\n    Graph-->>MCP: causal chain nodes\n    MCP->>MCP: format_response(nodes)\n    MCP-->>Client: formatted traversal result\n```\n\n### Traversal Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `node_id` | string | required | Starting memory node ID |\n| `direction` | string | \"both\" | \"upstream\", \"downstream\", or \"both\" |\n| `max_depth` | integer | 3 | Maximum traversal depth |\n| `k` | integer | 5 | Number of nodes per level |\n\n### Edge Types in Traversal\n\nThe system maintains several edge types that govern traversal behavior:\n\n| Edge Type | Semantics | Created By |\n|-----------|-----------|------------|\n| `CAUSED_BY` | Upstream dependency | User or LLM |\n| `SUPPORTS` | Reinforcing relationship | LLM inference |\n| `DERIVED_FROM` | Consolidation origin | Consolidation engine |\n| `CONTRADICTS` | Conflicting memory | Contradiction detection |\n| `RELATED_TO` | Semantic similarity | Auto-linking |\n\n资料来源：[src/genesys_memory/engine/contradiction.py:1-1]()\n\n## Auto-Linking Mechanism\n\nWhen memories are stored, the system automatically links them to semantically similar existing memories. This creates the underlying graph structure that enables traversal.\n\n### Auto-Linking Process\n\n1. After storing a new memory, generate its embedding\n2. Perform vector search for top-K similar memories (k=4)\n3. Filter by similarity threshold (0.3 minimum score)\n4. Create `RELATED_TO` edges for qualifying matches\n\n```mermaid\ngraph TD\n    A[New Memory] --> B[Generate Embedding]\n    B --> C[Vector Search]\n    C --> D{score >= 0.3?}\n    D-->|No| E[Skip]\n    D-->|Yes| F{Cross-org?}\n    F-->|Yes| E\n    F-->|No| G{Edge exists?}\n    G-->|Yes| E\n    G-->|No| H[Create RELATED_TO edge]\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-1]()\n\n### Auto-Link Constraints\n\nThe auto-linking mechanism enforces organizational boundaries:\n\n- Org-scoped memories (`visibility=ORG`) can only link to nodes with matching `org_id`\n- Cross-organization linking is prohibited\n- Duplicate edges are prevented via existence check\n\n```python\nif vis == Visibility.ORG:\n    if other_node.visibility != Visibility.ORG or other_node.org_id != org_id:\n        continue\nalready = await self.graph.edge_exists(node_id, str(other_node.id), EdgeType.RELATED_TO)\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-1]()\n\n## Contradiction Detection\n\nThe contradiction detection system identifies conflicting memories and creates appropriate edges to track them.\n\n### Detection Pipeline\n\n```mermaid\ngraph LR\n    A[New Memory] --> B[Vector Search]\n    B --> C{Similarity > 0.85?}\n    C-->|No| D[Skip]\n    C-->|Yes| E[LLM Confirmation]\n    E --> F{Confirmed?}\n    F-->|No| D\n    F-->|Yes| G[Create CONTRADICTS edge]\n```\n\n### Detection Algorithm\n\nThe contradiction detection follows a two-stage approach:\n\n1. **Vector Search Stage**: Find highly similar candidates (>0.85 similarity)\n2. **LLM Confirmation Stage**: Use language model to verify actual contradiction\n\n```python\ncandidates = await graph.vector_search(new_node.embedding, k=20)\nfor candidate_node, sim_score in candidates:\n    similarity = 1.0 - sim_score if sim_score <= 1.0 else sim_score\n    if similarity < 0.85:\n        continue\n    is_contradiction, confidence, _ = await llm.check_contradiction(...)\n```\n\n资料来源：[src/genesys_memory/engine/contradiction.py:1-1]()\n\n### LLM Contradiction Check\n\nThe LLM provider compares the content of both memories and determines if they truly contradict:\n\n```python\nprompt = f\"\"\"Compare these two memories and determine if they contradict each other:\n\nMemory A: {content_a}\n\nMemory B: {content_b}\n\nRespond with JSON: {{\"contradicts\": bool, \"confidence\": 0.0-1.0, \"reason\": \"...\"}}\"\"\"\n```\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:1-1]()\n\n## Causal Relationship Identification\n\nThe LLM provider can identify causal relationships between a new memory and existing memories, creating appropriate causal edges.\n\n### Relationship Types\n\n| Type | Confidence Threshold | Description |\n|------|---------------------|-------------|\n| `caused_by` | > 0.6 | Direct causation |\n| `supports` | > 0.6 | Reinforcing evidence |\n| `derived_from` | > 0.6 | Semantic extraction |\n\n### Identification Process\n\n```python\nprompt = (\n    \"Given a new memory and a list of existing memories, identify causal relationships.\\n\\n\"\n    f\"New memory: {new_memory}\\n\\nExisting memories:\\n{mem_lines}\\n\\n\"\n    \"For each causal relationship found, specify:\\n\"\n    \"- target_id: the ID of the existing memory\\n\"\n    '- edge_type: one of \"caused_by\", \"supports\", \"derived_from\"\\n'\n    \"- confidence: 0.0 to 1.0\\n\"\n    \"- reason: brief explanation\\n\\n\"\n    \"Only include relationships with confidence > 0.6.\"\n)\n```\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:1-1]()\n\n## Memory Consolidation\n\nConsolidation converts episodic (short-lived) memories into semantic (long-term) representations, creating `DERIVED_FROM` edges to track the source memories.\n\n### Consolidation Workflow\n\n```mermaid\ngraph TD\n    A[Episodic Memories] --> B[Fetch Content]\n    B --> C[LLM Consolidation]\n    C --> D[Generate Summary]\n    D --> E[Create Semantic Node]\n    E --> F[Create DERIVED_FROM Edges]\n    F --> G[Update Graph]\n```\n\n### Semantic Node Creation\n\nThe consolidation engine:\n\n1. Collects episodic memory contents\n2. Sends to LLM for summarization\n3. Generates new embedding for consolidated content\n4. Creates semantic memory node with `DERIVED_FROM` edges\n\n```python\nsummary = await llm.consolidate([m.content_full or m.content_summary for m in matching])\nembedding = await embeddings.embed(consolidated_text)\n\nsemantic_node = MemoryNode(\n    status=MemoryStatus.SEMANTIC,\n    content_summary=summary,\n    content_full=consolidated_text,\n    embedding=embedding,\n    ...\n)\n\nfor source_node in matching:\n    edge = MemoryEdge(\n        source_id=semantic_node.id,\n        target_id=source_node.id,\n        type=EdgeType.DERIVED_FROM,\n        weight=0.7,\n    )\n    await graph.create_edge(edge)\n```\n\n资料来源：[src/genesys_memory/engine/consolidation.py:1-1]()\n\n## Status Transitions Based on Graph Activity\n\nThe transition engine evaluates memories for promotion based on their graph connectivity.\n\n### Tagged → Active Promotion\n\nMemories in `TAGGED` status are promoted to `ACTIVE` when they form connections in the causal graph:\n\n```python\ntagged_nodes = await graph.get_nodes_by_status(MemoryStatus.TAGGED)\nfor node in tagged_nodes:\n    if node.visibility == Visibility.ORG:\n        continue\n    if not await graph.is_orphan(str(node.id)):\n        await graph.update_node(str(node.id), {\"status\": MemoryStatus.ACTIVE})\n        transitions.append({\n            \"node_id\": str(node.id),\n            \"old\": \"tagged\",\n            \"new\": \"active\",\n            \"reason\": \"consolidation signal: edge formed\",\n        })\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:1-1]()\n\n### Orphan Expiration\n\nTagged memories that remain disconnected for 24 hours are automatically expired:\n\n```python\nage_hours = (datetime.now(timezone.utc) - node.created_at).total_seconds() / 3600\nif age_hours > 24:\n    await graph.update_node(str(node.id), {\"status\": MemoryStatus.FADING})\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:1-1]()\n\n## Graph Storage Provider\n\nThe storage layer implements efficient graph operations with per-user isolation and edge indexing.\n\n### In-Memory Graph Implementation\n\nThe `InMemoryGraphProvider` provides graph storage with performance optimizations:\n\n```python\nclass InMemoryGraphProvider:\n    \"\"\"GraphStorageProvider backed by plain dicts with per-user isolation.\"\"\"\n    \n    # Edge indexes: {user_id: {node_id: [edges]}}\n    _idx_by_source: dict[str, dict[str, list[MemoryEdge]]] = {}\n    _idx_by_target: dict[str, dict[str, list[MemoryEdge]]] = {}\n```\n\n资料来源：[src/genesys_memory/storage/memory.py:1-1]()\n\n### Performance Characteristics\n\n| Operation | Complexity | Notes |\n|-----------|------------|-------|\n| Edge lookup by source | O(degree) | Indexed by `_idx_by_source` |\n| Edge lookup by target | O(degree) | Indexed by `_idx_by_target` |\n| Is orphan check | O(degree) | Uses edge indexes |\n| Full graph scan | O(total_edges) | Only for full traversals |\n\n### Persistence Support\n\nThe in-memory provider supports JSON persistence for survival across process restarts:\n\n```python\ndef __init__(self, persist_path: str | None = None):\n    self._persist_path = Path(persist_path) if persist_path else None\n    self._save_depth = 0\n    self._dirty = False\n```\n\n资料来源：[src/genesys_memory/storage/memory.py:1-1]()\n\n## MCP Tools Reference\n\n### memory_traverse\n\nWalk the causal graph from a given memory node.\n\n```json\n{\n  \"node_id\": \"uuid-string\",\n  \"direction\": \"upstream | downstream | both\",\n  \"max_depth\": 3,\n  \"k\": 5\n}\n```\n\n### memory_explain\n\nExplain why a memory exists by showing its causal chain.\n\n```json\n{\n  \"node_id\": \"uuid-string\",\n  \"include_context\": true\n}\n```\n\nReturns the memory with `causal_basis` (immediate neighbors) and `causal_chain` (full lineage).\n\n## Related Systems\n\n- **Scoring Engine**: Applies the decay formula `decay_score = relevance × connectivity × reactivation` where connectivity is derived from graph structure\n- **Reactivation Tracking**: Updates `last_reactivated_at` timestamps when memories are traversed\n- **Pruning System**: Uses connectivity metrics to determine which memories to prune\n\n资料来源：[README.md:1-1]()\n\n---\n\n<a id='backends-overview'></a>\n\n## Storage Backend Comparison\n\n### 相关页面\n\n相关主题：[Storage Provider Implementation](#storage-implementation)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/storage/memory.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/memory.py)\n- [src/genesys_memory/storage/base.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/base.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/edge.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/edge.py)\n- [docker-compose.yml](https://github.com/rishimeka/genesys/blob/main/docker-compose.yml)\n- [config/init.sql](https://github.com/rishimeka/genesys/blob/main/config/init.sql)\n- [CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n</details>\n\n# Storage Backend Comparison\n\nGenesys supports multiple storage backends to accommodate different deployment scenarios, from zero-dependency local development to production-scale distributed systems. This page provides a comprehensive comparison of available backends, their architectures, and guidance for selecting the appropriate backend for your use case.\n\n## Architecture Overview\n\nGenesys implements a **provider abstraction pattern** where all data access flows through standardized interfaces defined in `storage/base.py`. This design ensures that business logic remains decoupled from storage implementation details, enabling seamless backend switching without code changes.\n\n```mermaid\ngraph TD\n    A[\"🔷 MCP Tools Layer<br/>(tools.py)\"] --> B[\"📦 Storage Provider Interface<br/>(base.py)\"]\n    B --> C1[\"🟢 In-Memory Provider\"]\n    B --> C2[\"🔵 Postgres Provider\"]\n    B --> C3[\"🟡 Obsidian Provider\"]\n    B --> C4[\"🟣 FalkorDB Provider\"]\n    B --> C5[\"⚪ Custom Provider\"]\n    \n    C1 --> D1[\"Dict + JSON File\"]\n    C2 --> D2[\"PostgreSQL + pgvector\"]\n    C3 --> D3[\"SQLite + File System\"]\n    C4 --> D4[\"Redis Graph\"]\n    \n    style A fill:#4a90d9,color:#fff\n    style B fill:#f5a623,color:#fff\n    style D1 fill:#7ed321,color:#fff\n    style D2 fill:#4a90d9,color:#fff\n    style D3 fill:#f5a623,color:#fff\n    style D4 fill:#9013fe,color:#fff\n```\n\n**Key Design Principle:** Storage abstraction is mandatory. All data access goes through provider interfaces in `storage/base.py`. Never import a database client directly in business logic. 资料来源：[CONTRIBUTING.md:1]()\n\n## Storage Provider Interfaces\n\nThe storage layer is composed of three interconnected provider types that handle different aspects of memory management.\n\n### Provider Types\n\n| Provider | Responsibility | Key Methods |\n|----------|---------------|-------------|\n| **GraphStorageProvider** | Nodes, edges, causal relationships | `upsert_node`, `get_node`, `delete_node`, `upsert_edge`, `get_neighbors` |\n| **CacheProvider** | Short-term caching, TTL management | `get`, `set`, `delete`, `exists` |\n| **EmbeddingProvider** | Vector embedding generation | `embed`, `batch_embed` |\n\n资料来源：[src/genesys_memory/storage/base.py:1]()\n\n### Memory Node Structure\n\nEvery memory in Genesys is represented as a `MemoryNode` with the following core attributes:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID\n    status: MemoryStatus  # ACTIVE, DORMANT, FADING, PRUNED\n    content_summary: str  # Max 200 chars\n    content_full: str | None\n    embedding: list[float] | None\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    \n    # Core memory\n    pinned: bool = False\n    category: str | None\n```\n\n资料来源：[src/genesys_memory/models/node.py:1]()\n\n## Available Backends\n\n### 1. In-Memory Backend (Built-in)\n\nThe default backend with zero external dependencies. Suitable for development, testing, and lightweight deployments.\n\n#### Features\n\n- Built-in dict-based storage with per-user isolation\n- Optional JSON file persistence via `GENESYS_PERSIST_PATH`\n- No Docker, database, or API keys required for basic operation\n- Fast startup, ideal for local development\n\n#### Architecture\n\n```python\nclass InMemoryCacheProvider:\n    \"\"\"CacheProvider backed by a plain dict.\"\"\"\n    def __init__(self) -> None:\n        self._data: dict[str, str] = {}\n\nclass InMemoryGraphProvider:\n    \"\"\"GraphStorageProvider backed by plain dicts with per-user isolation.\"\"\"\n    # State persisted to JSON if persist_path is set\n```\n\n资料来源：[src/genesys_memory/storage/memory.py:1]()\n\n#### Configuration\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `GENESYS_BACKEND` | No | `memory` | Set to `memory` explicitly |\n| `GENESYS_PERSIST_PATH` | No | None | Path for JSON state persistence |\n| `OPENAI_API_KEY` | If using OpenAI embeddings | - | For vector search |\n| `GENESYS_EMBEDDER` | No | `openai` | Or `local` for no API key |\n\n#### Use Cases\n\n- Local development and testing\n- Single-user CLI applications\n- Prototyping and evaluation\n- When infrastructure overhead must be minimized\n\n---\n\n### 2. PostgreSQL + pgvector (Production)\n\nPersistent, scalable storage with native vector search capabilities via the pgvector extension.\n\n#### Features\n\n- Full ACID compliance and relational integrity\n- pgvector extension for efficient similarity search\n- Horizontal scalability with connection pooling\n- Alembic migrations for schema management\n- Docker Compose orchestration included\n\n#### Architecture\n\n```mermaid\ngraph LR\n    A[\"Genesys API\"] --> B[\"PostgreSQL Driver\"]\n    B --> C[\"PostgreSQL 15+\"]\n    C --> D[\"pgvector Extension\"]\n    D --> E[\"Vectors + Relations\"]\n    \n    style C fill:#4a90d9,color:#fff\n    style D fill:#7ed321,color:#fff\n```\n\n#### Database Schema\n\nThe Postgres backend uses a normalized schema with dedicated tables for nodes, edges, and embeddings:\n\n```sql\n-- Core memory nodes table\nCREATE TABLE memory_nodes (\n    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n    status VARCHAR(20) NOT NULL,\n    content_summary VARCHAR(200) NOT NULL,\n    content_full TEXT,\n    embedding vector(1536),\n    decay_score FLOAT DEFAULT 1.0,\n    causal_weight INTEGER DEFAULT 0,\n    reactivation_count INTEGER DEFAULT 0,\n    pinned BOOLEAN DEFAULT FALSE,\n    created_at TIMESTAMP DEFAULT NOW(),\n    last_accessed_at TIMESTAMP DEFAULT NOW()\n);\n\n-- Create index for vector similarity search\nCREATE INDEX ON memory_nodes USING ivfflat (embedding vector_cosine_ops)\nWITH (lists = 100);\n```\n\n资料来源：[config/init.sql:1]()\n\n#### Configuration\n\n```bash\n# Install\npip install 'genesys-memory[postgres]'\n\n# Environment variables\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\nOPENAI_API_KEY=sk-...\n```\n\n#### Docker Compose Setup\n\n```yaml\n# docker-compose.yml\nservices:\n  postgres:\n    image: pgvector/pgvector:pg15\n    environment:\n      POSTGRES_USER: genesys\n      POSTGRES_PASSWORD: genesys\n      POSTGRES_DB: genesys\n    ports:\n      - \"5432:5432\"\n    volumes:\n      - postgres_data:/var/lib/postgresql/data\n\nvolumes:\n  postgres_data:\n```\n\n资料来源：[docker-compose.yml:1]()\n\n#### Startup Commands\n\n```bash\ndocker compose up -d postgres\nalembic upgrade head\nGENESYS_BACKEND=postgres uvicorn genesys.api:app --port 8000\n```\n\n---\n\n### 3. Obsidian Vault (Local-First)\n\nTransforms an existing Obsidian vault into a Genesys memory store where Markdown files become memory nodes and `[[wikilinks]]` become causal edges.\n\n#### Features\n\n- Markdown files become memory nodes automatically\n- `[[wikilinks]]` converted to causal edges\n- SQLite sidecar (`.genesys/index.db`) handles indexing\n- File watcher for incremental re-indexing\n- Zero external API dependencies with local embeddings\n- Works fully offline\n\n#### Architecture\n\n```mermaid\ngraph TD\n    A[\"📁 Obsidian Vault\"] --> B[\"File Watcher\"]\n    B --> C[\"Indexing Engine\"]\n    C --> D[\".genesys/index.db<br/>(SQLite)\"]\n    D --> E[\"Vector Embeddings\"]\n    \n    F[\".md Files\"] --> G[\"Memory Nodes\"]\n    H[\"[[wikilinks]]\"] --> I[\"Causal Edges\"]\n    \n    style A fill:#f5a623,color:#fff\n    style D fill:#7ed321,color:#fff\n```\n\n#### Configuration\n\n```bash\n# Install with local embeddings (no API key needed)\npip install 'genesys-memory[obsidian,local]'\n\n# Environment variables\nGENESYS_BACKEND=obsidian\nGENESYS_EMBEDDER=local\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n```\n\n#### Vault Auto-Detection\n\nIf `OBSIDIAN_VAULT_PATH` is not set, Genesys auto-detects by looking for `.obsidian/` in these directories:\n\n| Search Path | Priority |\n|-------------|----------|\n| `~/Documents/personal` | 1st |\n| `~/Documents/Obsidian` | 2nd |\n| `~/obsidian` | 3rd |\n\n#### Embedding Model\n\nThe local embedder uses `all-MiniLM-L6-v2` (384-dimensional vectors) via `sentence-transformers`:\n\n- Model size: ~80 MB (downloaded on first use)\n- No API key required\n- Suitable for most recall accuracy requirements\n\n---\n\n### 4. FalkorDB (Graph-Native)\n\nUses FalkorDB (Redis-based graph database) for native graph traversal with O(1) edge lookups.\n\n#### Features\n\n- Native graph data structure with no ORM mapping\n- Redis-backed for high performance\n- Excellent for complex causal chain traversal\n- Scalable Redis ecosystem\n\n#### Architecture\n\n```mermaid\ngraph LR\n    A[\"Genesys API\"] --> B[\"FalkorDB Client\"]\n    B --> C[\"Redis Protocol\"]\n    C --> D[\"FalkorDB Container\"]\n    D --> E[\"Native Graph<br/>Traversal\"]\n    \n    style D fill:#9013fe,color:#fff\n```\n\n#### Configuration\n\n```bash\n# Install\npip install 'genesys-memory[falkordb]'\n\n# Environment variables\nGENESYS_BACKEND=falkordb\nFALKORDB_HOST=localhost\nOPENAI_API_KEY=sk-...\n```\n\n#### Startup\n\n```bash\ndocker compose up -d falkordb\nuvicorn genesys.api:app --port 8000\n```\n\n---\n\n## Backend Comparison Matrix\n\n| Criteria | In-Memory | PostgreSQL | Obsidian | FalkorDB |\n|----------|-----------|------------|----------|----------|\n| **Dependencies** | None | Docker + Postgres | None | Docker + Redis |\n| **Persistence** | JSON file | Full database | Markdown + SQLite | Redis dump |\n| **Scalability** | Single instance | Horizontal | Vault size | Redis cluster |\n| **Vector Search** | Via embedding API | pgvector native | Local models | Via API |\n| **Graph Traversal** | Dict-based | SQL joins | File parsing | Native |\n| **Offline Capable** | Yes | No | Yes | No |\n| **Setup Complexity** | None | Medium | Low | Medium |\n| **Best For** | Dev/Testing | Production | Personal KB | Complex graphs |\n\n## Configuration Reference\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `OPENAI_API_KEY` | Unless `GENESYS_EMBEDDER=local` | - | Embedding generation |\n| `ANTHROPIC_API_KEY` | No | - | LLM memory processing |\n| `GENESYS_BACKEND` | No | `memory` | `memory`, `postgres`, `obsidian`, `falkordb` |\n| `GENESYS_EMBEDDER` | No | `openai` | `openai` or `local` |\n| `DATABASE_URL` | If postgres | - | PostgreSQL connection string |\n| `OBSIDIAN_VAULT_PATH` | If obsidian | Auto-detect | Path to vault |\n| `FALKORDB_HOST` | If falkordb | `localhost` | FalkorDB host |\n| `GENESYS_PERSIST_PATH` | If using persistence | - | JSON state file path |\n| `GENESYS_USER_ID` | No | - | Default user ID (single-tenant) |\n\n资料来源：[README.md:1]()\n\n## Implementing Custom Backends\n\nTo implement a custom storage backend, implement the `GraphStorageProvider` interface from `storage/base.py`:\n\n```python\nfrom genesys_memory.storage.base import GraphStorageProvider\nfrom genesys_memory.models.node import MemoryNode\nfrom genesys_memory.models.edge import MemoryEdge\n\nclass MyCustomProvider(GraphStorageProvider):\n    async def upsert_node(self, node: MemoryNode) -> MemoryNode:\n        # Your implementation\n        pass\n    \n    async def get_node(self, node_id: str) -> MemoryNode | None:\n        # Your implementation\n        pass\n    \n    async def upsert_edge(self, edge: MemoryEdge) -> MemoryEdge:\n        # Your implementation\n        pass\n    \n    async def get_neighbors(\n        self, \n        node_id: str, \n        edge_types: list[str] | None = None,\n        depth: int = 1\n    ) -> list[MemoryEdge]:\n        # Your implementation\n        pass\n```\n\n资料来源：[src/genesys_memory/storage/base.py:1]()\n\n## Selection Guide\n\n```mermaid\ngraph TD\n    A[\"Need external APIs?\"] --> B{\"No API Keys?\"}\n    B -->|Yes| C[\"Local Embeddings?\"]\n    C -->|Yes| D[\"Use Obsidian + Local\"]\n    C -->|No| E[\"Use Obsidian + OpenAI\"]\n    B -->|No| F[\"Scale Requirements?\"]\n    \n    F -->|High Volume| G[\"Use PostgreSQL\"]\n    F -->|Complex Graphs| H[\"Use FalkorDB\"]\n    F -->|Simple/Testing| I[\"Use In-Memory + Persist\"]\n    \n    style D fill:#7ed321,color:#fff\n    style G fill:#4a90d9,color:#fff\n    style H fill:#9013fe,color:#fff\n    style I fill:#f5a623,color:#fff\n```\n\n### Decision Criteria\n\n**Choose In-Memory when:**\n- Building prototypes or running tests\n- Single-user deployment with no persistence requirements\n- Infrastructure constraints prevent containerized deployments\n\n**Choose PostgreSQL when:**\n- Production deployment with multi-user support\n- Need for ACID compliance and data integrity\n- Vector similarity search is primary retrieval method\n- Existing Postgres infrastructure available\n\n**Choose Obsidian when:**\n- Already using Obsidian for note-taking\n- Prefer local-first, offline-capable solution\n- Markdown-based knowledge management is preferred\n- Zero cloud dependency is a requirement\n\n**Choose FalkorDB when:**\n- Complex causal chain traversal is frequent\n- Graph-native operations are performance critical\n- Redis ecosystem is already in use\n- Sub-millisecond edge lookups required\n\n---\n\n<a id='storage-implementation'></a>\n\n## Storage Provider Implementation\n\n### 相关页面\n\n相关主题：[Storage Backend Comparison](#backends-overview), [System Architecture](#architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/storage/base.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/base.py)\n- [src/genesys_memory/storage/memory.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/memory.py)\n- [src/genesys_memory/storage/cache.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/cache.py)\n- [src/genesys_memory/providers.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/providers.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/edge.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/edge.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n</details>\n\n# Storage Provider Implementation\n\n## Overview\n\nThe Storage Provider Implementation in Genesys provides a modular, pluggable architecture for persisting memory nodes and their causal relationships. This abstraction layer enables the memory system to operate with different storage backends—from simple in-memory dictionaries to production-grade databases like PostgreSQL with pgvector, or even Obsidian vaults and FalkorDB—without changing the core memory logic.\n\nThe storage layer is composed of four provider types that work together:\n\n- **GraphStorageProvider**: Manages `MemoryNode` entities and `MemoryEdge` relationships (the causal graph)\n- **CacheProvider**: Provides fast key-value caching for temporary data\n- **EmbeddingProvider**: Generates and retrieves vector embeddings for semantic search\n- **EventBusProvider**: Handles event-driven communication between system components\n\n资料来源：[src/genesys_memory/storage/base.py]()\n\n---\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Storage Provider Layer\"\n        GP[GraphStorageProvider]\n        CP[CacheProvider]\n        EP[EmbeddingProvider]\n        EBP[EventBusProvider]\n    end\n    \n    subgraph \"Backend Implementations\"\n        subgraph \"In-Memory\"\n            IMGP[InMemoryGraphProvider]\n            IMCP[InMemoryCacheProvider]\n        end\n        \n        subgraph \"PostgreSQL\"\n            PG[PostgresGraphProvider]\n            PGEM[PostgresEmbeddingProvider]\n        end\n        \n        subgraph \"Obsidian\"\n            OV[ObsidianGraphProvider]\n        end\n        \n        subgraph \"FalkorDB\"\n            FK[FalkorDBGraphProvider]\n        end\n    end\n    \n    GP --> IMGP\n    GP --> PG\n    GP --> OV\n    GP --> FK\n    CP --> IMCP\n    EP --> PGEM\n    \n    subgraph \"Higher Layers\"\n        MCP[MCP Tools]\n        Engine[Scoring Engine]\n    end\n    \n    MCP --> GP\n    Engine --> GP\n    Engine --> CP\n    Engine --> EP\n```\n\n资料来源：[src/genesys_memory/providers.py]()\n\n---\n\n## Provider Interface Contracts\n\n### GraphStorageProvider\n\nThe `GraphStorageProvider` is the core interface for managing the memory graph. It handles both node storage and edge management for the causal graph structure.\n\n资料来源：[src/genesys_memory/storage/base.py]()\n\n| Method | Description | Returns |\n|--------|-------------|---------|\n| `upsert_node(node)` | Create or update a memory node | `MemoryNode` |\n| `get_node(node_id)` | Retrieve a node by ID | `MemoryNode \\| None` |\n| `delete_node(node_id)` | Remove a node and its edges | `bool` |\n| `list_nodes(filters)` | List nodes with optional filtering | `list[MemoryNode]` |\n| `upsert_edge(edge)` | Create or update an edge | `MemoryEdge` |\n| `get_edge(edge_id)` | Retrieve an edge | `MemoryEdge \\| None` |\n| `delete_edge(edge_id)` | Remove an edge | `bool` |\n| `get_neighbors(node_id)` | Get adjacent nodes | `list[MemoryNode]` |\n| `get_stats()` | Return graph statistics | `dict` |\n\n### CacheProvider\n\nThe `CacheProvider` provides ephemeral key-value storage with optional TTL support.\n\n| Method | Description | Returns |\n|--------|-------------|---------|\n| `get(key)` | Retrieve cached value | `str \\| None` |\n| `set(key, value, ttl_seconds)` | Store value with TTL | `None` |\n| `delete(key)` | Remove cached entry | `None` |\n| `exists(key)` | Check if key exists | `bool` |\n\n资料来源：[src/genesys_memory/storage/cache.py]()\n\n### EmbeddingProvider\n\nThe `EmbeddingProvider` interface handles vector embedding generation and similarity search.\n\n| Method | Description |\n|--------|-------------|\n| `embed(text)` | Generate embedding vector for text |\n| `search(query, k)` | Find top-k similar vectors |\n| `delete(embedding_id)` | Remove an embedding |\n\n---\n\n## In-Memory Implementation\n\nThe in-memory storage providers are the default implementation, requiring no external dependencies. They use Python dictionaries for storage and are suitable for development, testing, or single-user scenarios.\n\n### InMemoryCacheProvider\n\nLocated in `src/genesys_memory/storage/memory.py`, this provider backs the cache interface with a simple dictionary:\n\n```python\nclass InMemoryCacheProvider:\n    \"\"\"CacheProvider backed by a plain dict.\"\"\"\n\n    def __init__(self) -> None:\n        self._data: dict[str, str] = {}\n\n    async def get(self, key: str) -> str | None:\n        return self._data.get(key)\n\n    async def set(self, key: str, value: str, ttl_seconds: int = 300) -> None:\n        self._data[key] = value\n```\n\n**Configuration**: No configuration required. Default TTL is 300 seconds.\n\n**Limitations**:\n- Data is lost on application restart\n- No horizontal scaling support\n- In-memory storage only\n\n资料来源：[src/genesys_memory/storage/memory.py:28-40]()\n\n### InMemoryGraphProvider\n\nThe `InMemoryGraphProvider` implements the full graph storage interface using dictionaries with per-user isolation. It supports optional JSON persistence via `persist_path`.\n\n```python\nclass InMemoryGraphProvider:\n    \"\"\"GraphStorageProvider backed by plain dicts with per-user isolation.\"\"\"\n\n    def __init__(self, persist_path: Path | None = None) -> None:\n        # State includes: nodes, edges, adjacency lists\n        ...\n```\n\n**Key Features**:\n- Per-user isolation enforced via `current_user_id` context variable\n- Optional JSON file persistence\n- In-memory graph traversal using adjacency lists\n\n```python\ndef _uid() -> str:\n    uid = current_user_id.get(None)\n    if uid is None:\n        raise RuntimeError(\"No user context — current_user_id not set\")\n    return uid\n```\n\n资料来源：[src/genesys_memory/storage/memory.py:42-58]()\n\n---\n\n## Provider Factory\n\nThe `get_providers()` function in `src/genesys_memory/providers.py` is the central factory that instantiates and wires together the appropriate provider implementations based on environment configuration.\n\n```python\nproviders = get_providers()\ntools = providers.tools\n```\n\nThe factory reads environment variables to determine which backend to use:\n\n| Environment Variable | Options | Default |\n|---------------------|---------|---------|\n| `GENESYS_BACKEND` | `memory`, `postgres`, `obsidian`, `falkordb` | `memory` |\n| `GENESYS_EMBEDDER` | `openai`, `local` | `openai` |\n| `DATABASE_URL` | PostgreSQL connection string | — |\n| `OBSIDIAN_VAULT_PATH` | Path to vault directory | auto-detect |\n| `FALKORDB_HOST` | FalkorDB host | `localhost` |\n\n资料来源：[src/genesys_memory/providers.py]()\n\n---\n\n## MCP Tool Integration\n\nThe MCP (Model Context Protocol) tools interact with storage providers through a dispatch table that maps tool names to provider methods:\n\n```python\n_TOOL_DISPATCH: dict[str, tuple[Any, ...]] = {\n    \"memory_store\": (tools.memory_store, [\"content\"], {\"source_session\": \"\", \"related_to\": None, \"visibility\": \"private\", \"org_id\": None}),\n    \"memory_recall\": (tools.memory_recall, [\"query\"], {\"k\": 10, \"max_results\": None}),\n    \"memory_search\": (tools.memory_search, [\"query\"], {\"filters\": None, \"k\": 10}),\n    \"memory_traverse\": (tools.memory_traverse, [\"node_id\"], {\"depth\": 2, \"edge_types\": None}),\n    \"memory_explain\": (tools.memory_explain, [\"node_id\"], {}),\n    \"pin_memory\": (tools.pin_memory, [\"node_id\"], {}),\n    \"unpin_memory\": (tools.unpin_memory, [\"node_id\"], {}),\n    \"list_core_memories\": (tools.list_core_memories, [], {\"category\": None}),\n    \"delete_memory\": (tools.delete_memory, [\"node_id\"], {}),\n    \"memory_stats\": (tools.memory_stats, [], {}),\n    \"set_core_preferences\": (tools.set_core_preferences, [], {\"auto\": None, \"approval\": None, \"excluded\": None}),\n}\n```\n\n资料来源：[src/genesys_memory/server.py]()\n\n### Tool-to-Provider Mapping\n\n| MCP Tool | Storage Provider Method | Purpose |\n|----------|------------------------|---------|\n| `memory_store` | `GraphStorageProvider.upsert_node` | Create new memories |\n| `memory_recall` | `GraphStorageProvider` + `EmbeddingProvider` | Hybrid search |\n| `memory_search` | `GraphStorageProvider.list_nodes` | Filtered search |\n| `memory_traverse` | `GraphStorageProvider.get_neighbors` | Graph traversal |\n| `memory_explain` | `GraphStorageProvider.get_node` | Retrieve single memory |\n| `pin_memory` | `GraphStorageProvider.upsert_node` | Update pinned status |\n| `delete_memory` | `GraphStorageProvider.delete_node` | Remove memory |\n| `memory_stats` | `GraphStorageProvider.get_stats` | Graph metrics |\n\n资料来源：[src/genesys_memory/mcp/tools.py]()\n\n---\n\n## Data Models\n\n### MemoryNode\n\nThe `MemoryNode` model represents a single memory unit with full lifecycle tracking:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    content_ref: str | None = None\n    embedding: list[float] | None = None\n\n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n\n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern\n    irrelevance_counter: int = 0\n\n    # Stability (increases on successful retrieval, per spaced repetition)\n    stability: float = 1.0\n\n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n```\n\n资料来源：[src/genesys_memory/models/node.py:1-35]()\n\n### MemoryEdge\n\nEdges represent causal relationships between memories:\n\n```python\nclass MemoryEdge(BaseModel):\n    id: uuid.UUID\n    source_id: uuid.UUID\n    target_id: uuid.UUID\n    edge_type: EdgeType  # caused_by, supports, derived_from\n    weight: float = 1.0\n    confidence: float\n    reason: str | None = None\n```\n\n资料来源：[src/genesys_memory/models/edge.py]()\n\n---\n\n## Backend Comparison\n\n| Backend | Use Case | Scalability | Persistence | External Dependencies |\n|---------|----------|-------------|-------------|----------------------|\n| **In-Memory** | Development, testing | Single instance | Optional JSON file | None |\n| **PostgreSQL + pgvector** | Production, multi-tenant | High | Full ACID | Docker Compose |\n| **Obsidian Vault** | Personal knowledge base | Single user | Markdown files | None |\n| **FalkorDB** | Graph-native traversal | High | Redis-based | Docker Compose |\n\n资料来源：[README.md]()\n\n---\n\n## Adding Custom Storage Backends\n\nTo implement a custom storage backend, create a class that inherits from the base provider interfaces:\n\n```python\nfrom genesys_memory.storage.base import GraphStorageProvider, CacheProvider\n\nclass MyCustomGraphProvider(GraphStorageProvider):\n    async def upsert_node(self, node: MemoryNode) -> MemoryNode:\n        # Implement node persistence\n        pass\n    \n    async def get_node(self, node_id: str) -> MemoryNode | None:\n        # Implement node retrieval\n        pass\n    \n    # ... implement all interface methods\n```\n\nRegister your provider in the factory function within `providers.py` by adding a new condition branch.\n\n---\n\n## Security Considerations\n\nThe storage layer enforces user isolation through context variables:\n\n```python\ndef _caller_owns_node(node: MemoryNode) -> bool:\n    uid = _caller_uid()\n    if uid is None:\n        raise PermissionError(\"current_user_id not set — cannot verify ownership\")\n    role = current_user_role.get(None)\n    if role == \"admin\" and node.org_id and node.org_id in current_org_ids.get([]):\n        return True\n    if node.original_user_id:\n        return node.original_user_id == uid\n    return True\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:27-38]()\n\nAccess control rules:\n1. All operations require an authenticated `current_user_id`\n2. Admin users can access nodes within their organization\n3. Nodes maintain `original_user_id` for ownership tracking\n4. Private nodes cannot be accessed by other users\n\n---\n\n## Performance Notes\n\n- The in-memory provider provides sub-millisecond latency for local operations\n- PostgreSQL with pgvector provides vector similarity search with approximate nearest neighbor (ANN) indexing\n- FalkorDB leverages Redis for fast graph traversal operations\n- Cache operations use a default TTL of 300 seconds to prevent stale data\n\n资料来源：[src/genesys_memory/storage/memory.py:35-37]()\n\n---\n\n<a id='mcp-tools'></a>\n\n## MCP Tools Reference\n\n### 相关页面\n\n相关主题：[Configuration Guide](#configuration), [Getting Started with Genesys](#getting-started)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/edge.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/edge.py)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n</details>\n\n# MCP Tools Reference\n\nThe Model Context Protocol (MCP) Tools layer is the primary interface through which AI agents interact with the Genesys memory system. This module exposes all memory operations as callable tools via the MCP stdio transport, enabling seamless integration with Claude Desktop and other MCP-compatible clients.\n\n## Architecture Overview\n\nThe MCP tools layer sits between the MCP protocol server and the core Genesys engine. It handles:\n\n- **Tool dispatching**: Routing tool calls to appropriate engine methods\n- **Context injection**: Providing user/org context for multi-tenant support\n- **Permission validation**: Ensuring callers have appropriate access rights\n- **Response formatting**: Converting engine results into MCP-compatible format\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|call_tool| B[MCP Server]\n    B -->|dispatch| C[Tool Dispatcher]\n    C -->|inject context| D[Context Managers]\n    D -->|verify permissions| E[Core Memory Engine]\n    E -->|execute| F[Storage Providers]\n    F -->|graph ops| G[Vector DB / FalkorDB / Obsidian]\n    C -->|format response| H[TextContent Response]\n```\n\n## Tool Registry\n\nAll available MCP tools are registered in `server.py` with their schemas and dispatch mappings.\n\n### Tool Dispatch Table\n\n| Tool Name | Required Args | Optional Args | Description |\n|-----------|---------------|---------------|-------------|\n| `memory_store` | `content` | `source_session`, `related_to`, `visibility`, `org_id` | Store a new memory |\n| `memory_recall` | `query` | `k`, `max_results` | Hybrid search recall |\n| `memory_search` | `query` | `filters`, `k` | Filtered vector search |\n| `memory_traverse` | `node_id` | `depth`, `edge_types` | Graph traversal |\n| `memory_explain` | `node_id` | - | Score breakdown explanation |\n| `pin_memory` | `node_id` | - | Pin to core status |\n| `unpin_memory` | `node_id` | - | Unpin and re-evaluate |\n| `list_core_memories` | - | `category` | List core memories |\n| `delete_memory` | `node_id` | - | Permanently delete |\n| `memory_stats` | - | - | Get graph statistics |\n| `set_core_preferences` | - | `auto`, `approval`, `excluded` | Configure core categories |\n| `promote_to_org` | `node_id`, `org_id` | `action`, `dry_run` | Promote to org visibility |\n\n资料来源：[src/genesys_memory/server.py:15-60]()\n\n## Memory Store Tool\n\nCreates a new memory node with automatic causal edge discovery.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"content\"],\n  \"properties\": {\n    \"content\": { \"type\": \"string\" },\n    \"source_session\": { \"type\": \"string\" },\n    \"related_to\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    },\n    \"visibility\": { \n      \"type\": \"string\",\n      \"enum\": [\"private\", \"org\", \"public\"],\n      \"default\": \"private\"\n    },\n    \"org_id\": { \"type\": \"string\" }\n  }\n}\n```\n\n### Behavior\n\n1. Generates embedding for content via configured embedder\n2. Creates `MemoryNode` with `ACTIVE` status\n3. Optionally links to existing memories via `related_to`\n4. Triggers causal edge discovery via LLM provider\n5. Emits `MemoryStoredEvent` to event bus\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-50]()\n\n## Memory Recall Tool\n\nImplements hybrid search combining vector similarity, keyword matching, and graph spreading activation.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"query\"],\n  \"properties\": {\n    \"query\": { \"type\": \"string\" },\n    \"k\": { \"type\": \"integer\", \"default\": 10 },\n    \"max_results\": { \"type\": \"integer\" }\n  }\n}\n```\n\n### Search Algorithm\n\n```mermaid\ngraph LR\n    A[Query Text] --> B[Vector Embedding]\n    A --> C[Keyword Extraction]\n    B --> D[Vector Similarity Search]\n    C --> E[BM25 Ranking]\n    D --> F[Initial Candidates]\n    E --> F\n    F --> G[Graph Spreading Activation]\n    G --> H[Score Normalization]\n    H --> I[Top K Results]\n```\n\nThe `k` parameter controls the number of initial vector candidates considered. Spreading activation propagates through causal edges, boosting memories connected to initially-matched nodes.\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:20-60]()\n\n## Memory Traverse Tool\n\nWalks the causal graph from a starting node using configurable depth and edge type filtering.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" },\n    \"depth\": { \"type\": \"integer\", \"default\": 2 },\n    \"edge_types\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    }\n  }\n}\n```\n\n### Traversal Behavior\n\n| Depth | Nodes Explored | Description |\n|-------|----------------|-------------|\n| 1 | Direct neighbors | Immediate causal relationships |\n| 2 | Friends-of-friends | Secondary connections |\n| N | N-level reach | Deeper causal chains |\n\nEdge type filtering supports: `caused_by`, `supports`, `derived_from`, `reactivated`, `contradicts`\n\n## Memory Explain Tool\n\nReturns the score breakdown for a memory node, revealing why it exists and how it scores on each axis.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" }\n  }\n}\n```\n\n### Score Components\n\nThe decay formula is multiplicative:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n| Component | Factor | Description |\n|-----------|--------|-------------|\n| Relevance | Time-based decay | How recently accessed |\n| Connectivity | Causal weight | Number/type of edges |\n| Reactivation | Frequency pattern | Recall history |\n\n资料来源：[src/genesys_memory/models/node.py:15-45]()\n\n## Pin/Unpin Memory Tools\n\nControls core memory status for individual nodes.\n\n### pin_memory\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" }\n  }\n}\n```\n\nPinned memories are immune to automatic pruning. Setting `pinned=true` also sets `promotion_reason` to indicate manual promotion.\n\n### unpin_memory\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" }\n  }\n}\n```\n\nUnpinning triggers re-evaluation for automatic core promotion based on category preferences.\n\n## List Core Memories Tool\n\nRetrieves all memories marked as core (pinned or auto-promoted).\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"properties\": {\n    \"category\": { \"type\": \"string\" }\n  }\n}\n```\n\n### Response Structure\n\n```json\n{\n  \"cores\": [\n    {\n      \"id\": \"uuid\",\n      \"content_summary\": \"...\",\n      \"category\": \"project_context\",\n      \"promotion_reason\": \"auto|manual\",\n      \"pinned\": true\n    }\n  ]\n}\n```\n\n## Set Core Preferences Tool\n\nConfigures automatic core memory categorization rules.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"properties\": {\n    \"auto\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    },\n    \"approval\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    },\n    \"excluded\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    }\n  }\n}\n```\n\n| Category | Behavior |\n|----------|----------|\n| `auto` | Auto-promoted to core when category matches |\n| `approval` | Queued for user approval before promotion |\n| `excluded` | Never auto-promoted, even if frequently accessed |\n\n## Permission Model\n\nAll tools enforce permission checks before execution.\n\n### Permission Hierarchy\n\n```mermaid\ngraph TD\n    A[Tool Call] --> B{_caller_uid set?}\n    B -->|No| C[PermissionError]\n    B -->|Yes| D{Node Owner?}\n    D -->|Own| E[Allow]\n    D -->|Admin + Org| F[Check Org Membership]\n    F -->|Member| E\n    F -->|Not Member| C\n```\n\n### Permission Functions\n\n| Function | Purpose |\n|----------|---------|\n| `_caller_uid()` | Returns current user ID from context |\n| `_caller_owns_node(node)` | Verifies ownership or admin org membership |\n| `_is_edge_stale(edge)` | Checks if edge requires refresh |\n\n资料来源：[src/genesys_memory/mcp/tools.py:25-50]()\n\n## Visibility Levels\n\nMemory nodes support three visibility levels:\n\n| Level | Access | Description |\n|-------|--------|-------------|\n| `private` | Owner only | Personal memories |\n| `org` | Organization members | Shared team context |\n| `public` | All users | Knowledge base entries |\n\n### promote_to_org Tool\n\nPromotes a private memory to org visibility:\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\", \"org_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" },\n    \"org_id\": { \"type\": \"string\" },\n    \"action\": {\n      \"type\": \"string\",\n      \"enum\": [\"keep_private\", \"promote_all\", \"delete_links\"],\n      \"default\": \"keep_private\"\n    },\n    \"dry_run\": { \"type\": \"boolean\", \"default\": false }\n  }\n}\n```\n\nActions:\n- `keep_private`: Only this node becomes org-visible\n- `promote_all`: All causally-linked nodes also promoted\n- `delete_links`: Remove private edges before promotion\n\n## Context Managers\n\nThe tools layer uses FastAPI-style context variables for multi-tenant support:\n\n```python\ncurrent_user_id      # Active user identifier\ncurrent_org_ids      # List of user's org memberships\ncurrent_user_role     # \"admin\", \"member\", etc.\n```\n\n资料来源：[src/genesys_memory/context.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/context.py)\n\n## Response Format\n\nAll tool responses are returned as `list[TextContent]` with type `\"text\"`:\n\n```json\n[\n  {\n    \"type\": \"text\",\n    \"text\": \"JSON serialized response\"\n  }\n]\n```\n\nError responses include structured error messages:\n\n```json\n[\n  {\n    \"type\": \"text\",\n    \"text\": \"Error: Permission denied for memory node abc-123\"\n  }\n]\n```\n\n## Integration with MCP Transport\n\nThe stdio transport enables direct connection to Claude Desktop:\n\n```bash\n# Claude Desktop config\n{\n  \"mcpServers\": {\n    \"genesys\": {\n      \"url\": \"http://localhost:8000/mcp\"\n    }\n  }\n}\n```\n\nOr for Claude Code CLI:\n\n```bash\nclaude mcp add --transport http genesys http://localhost:8000/mcp\n```\n\n资料来源：[README.md:80-100]()\n\n## Summary\n\nThe MCP Tools layer provides a complete interface for AI memory operations:\n\n- **12 core tools** covering CRUD, traversal, and lifecycle management\n- **Multi-tenant support** via context injection and permission checks\n- **Three visibility levels** (private, org, public)\n- **Hybrid search** combining vectors, keywords, and graph traversal\n- **Core memory automation** via category-based promotion rules\n\n---\n\n<a id='configuration'></a>\n\n## Configuration Guide\n\n### 相关页面\n\n相关主题：[Getting Started with Genesys](#getting-started)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [.env.example](https://github.com/rishimeka/genesys/blob/main/.env.example)\n- [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n- [src/genesys_memory/retrieval/embedding.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/retrieval/embedding.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n</details>\n\n# Configuration Guide\n\nThis guide covers all configuration options available in Genesys, including environment variables, storage backends, embedding providers, and LLM integration settings.\n\n## Overview\n\nGenesys supports multiple configuration options to accommodate different deployment scenarios, from local development with zero dependencies to production-grade deployments with persistent storage. Configuration is primarily driven by environment variables, with sensible defaults provided for most settings.\n\nThe configuration system enables:\n- **Multi-backend storage**: Choose between in-memory, PostgreSQL, Obsidian vault, or FalkorDB\n- **Flexible embedding**: Use OpenAI embeddings or local sentence-transformers\n- **LLM integration**: Optional Anthropic API for memory consolidation and processing\n- **Multi-tenancy**: Support for user and organization-level memory isolation\n\n## Environment Variables Reference\n\n### Core Configuration\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `OPENAI_API_KEY` | No* | - | OpenAI API key for embedding generation. Not required if `GENESYS_EMBEDDER=local` |\n| `ANTHROPIC_API_KEY` | No | - | Anthropic API key for LLM-based memory processing (consolidation, contradiction detection) |\n| `GENESYS_BACKEND` | No | `memory` | Storage backend: `memory`, `postgres`, `obsidian`, or `falkordb` |\n| `GENESYS_EMBEDDER` | No | `openai` | Embedding provider: `openai` or `local` |\n| `GENESYS_USER_ID` | No | - | Default user ID for single-tenant mode |\n| `GENESYS_PERSIST_PATH` | No | - | File path for persisting state in memory backend mode |\n\n*Required unless using local embedder\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Backend-Specific Configuration\n\n| Variable | Required For | Default | Description |\n|----------|--------------|---------|-------------|\n| `DATABASE_URL` | `postgres` | - | PostgreSQL connection string (e.g., `postgresql://user:pass@localhost:5432/genesys`) |\n| `OBSIDIAN_VAULT_PATH` | `obsidian` | Auto-detect | Path to your Obsidian vault directory |\n| `FALKORDB_HOST` | `falkordb` | `localhost` | FalkorDB host address |\n| `CLERK_SECRET_KEY` | Seed scripts | - | Clerk authentication secret for demo seeding |\n| `CLERK_USER_ID` | Seed scripts | - | Clerk user ID for demo seeding |\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Storage Backends\n\nGenesys is designed to work with multiple storage backends, each suited for different use cases.\n\n### Backend Comparison\n\n| Backend | Dependencies | Use Case | Persistence |\n|---------|--------------|----------|-------------|\n| `memory` | None | Local development, quick testing | Ephemeral (state lost on restart) |\n| `postgres` | PostgreSQL + pgvector | Production deployments | Persistent |\n| `obsidian` | Obsidian vault | Local-first knowledge management | File-based |\n| `falkordb` | FalkorDB | Graph-native traversal | Persistent |\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Memory Backend (Default)\n\nThe in-memory backend requires no additional dependencies and is ideal for exploration.\n\n```env\nGENESYS_BACKEND=memory\n```\n\nTo persist state across restarts:\n\n```env\nGENESYS_BACKEND=memory\nGENESYS_PERSIST_PATH=.genesys_state.json\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### PostgreSQL Backend\n\nRequires PostgreSQL with pgvector extension for vector similarity search.\n\n```env\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\n```\n\nStart PostgreSQL with Docker:\n\n```bash\ndocker compose up -d postgres\nalembic upgrade head\nuvicorn genesys.api:app --port 8000\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Obsidian Backend\n\nIntegrates directly with your Obsidian vault. Markdown files become memory nodes, and `[[wikilinks]]` become causal edges.\n\n```env\nGENESYS_BACKEND=obsidian\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n```\n\nIf `OBSIDIAN_VAULT_PATH` is not set, Genesys auto-detects by looking for `.obsidian/` in:\n- `~/Documents/personal`\n- `~/Documents/Obsidian`\n- `~/obsidian`\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### FalkorDB Backend\n\nUses FalkorDB (Redis-based graph database) for native graph traversal.\n\n```env\nGENESYS_BACKEND=falkordb\nFALKORDB_HOST=localhost\n```\n\nStart FalkorDB:\n\n```bash\ndocker compose up -d falkordb\nuvicorn genesys.api:app --port 8000\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Embedding Configuration\n\n### OpenAI Embeddings (Default)\n\nUses OpenAI's embedding models for vector representation.\n\n```env\nGENESYS_EMBEDDER=openai\nOPENAI_API_KEY=sk-...\n```\n\n### Local Embeddings (No API Key Required)\n\nUses `sentence-transformers` for fully local embedding generation. Downloads `all-MiniLM-L6-v2` (~80 MB) on first use.\n\n```env\nGENESYS_EMBEDDER=local\n```\n\nFor local Obsidian mode with zero external dependencies:\n\n```env\nGENESYS_BACKEND=obsidian\nGENESYS_EMBEDDER=local\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n# No OPENAI_API_KEY needed\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Memory Node Model\n\nThe core data model for memories in Genesys. Key configuration-related fields:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    embedding: list[float] | None = None\n    \n    # Timestamps\n    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    \n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n```\n\n资料来源: [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n## LLM Provider Configuration\n\nThe LLM provider handles memory consolidation and causal relationship detection.\n\n### Causal Link Detection\n\nWhen storing new memories, the LLM provider can automatically identify causal relationships with existing memories:\n\n```python\nprompt = (\n    \"Given a new memory and a list of existing memories, identify causal relationships.\\n\\n\"\n    f\"New memory: {new_memory}\\n\\nExisting memories:\\n{mem_lines}\\n\\n\"\n    \"For each causal relationship found, specify:\\n\"\n    \"- target_id: the ID of the existing memory\\n\"\n    '- edge_type: one of \"caused_by\", \"supports\", \"derived_from\"\\n'\n    \"- confidence: 0.0 to 1.0\\n\"\n    \"- reason: brief explanation of why this relationship exists\\n\\n\"\n    \"Only include relationships with confidence > 0.6.\\n\"\n    \"Respond with ONLY a JSON array of objects, no other text.\"\n)\n```\n\nConfiguration requires `ANTHROPIC_API_KEY` for LLM-based processing. Edge types include:\n- `caused_by`\n- `supports`\n- `derived_from`\n\n资料来源: [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n## MCP Server Configuration\n\nThe MCP (Model Context Protocol) server exposes Genesys functionality as tools. Configure the MCP endpoint in your AI client's configuration.\n\n### Claude Desktop\n\nAdd to `claude_desktop_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"genesys\": {\n      \"url\": \"http://localhost:8000/mcp\"\n    }\n  }\n}\n```\n\n### Claude Code\n\n```bash\nclaude mcp add --transport http genesys http://localhost:8000/mcp\n```\n\n### MCP Tools Available\n\n| Tool | Description |\n|------|-------------|\n| `memory_store` | Store a new memory, optionally linking to related memories |\n| `memory_recall` | Recall memories by natural language query (vector + graph) |\n| `memory_search` | Search memories with filters (status, date range, keyword) |\n| `memory_traverse` | Walk the causal graph from a given memory node |\n| `memory_explain` | Explain why a memory exists and its causal chain |\n| `memory_stats` | Get memory system statistics |\n| `pin_memory` | Pin a memory so it's never forgotten |\n| `unpin_memory` | Unpin a previously pinned memory |\n| `delete_memory` | Permanently delete a memory |\n| `list_core_memories` | List core memories, optionally filtered by category |\n| `set_core_preferences` | Set user preferences for core memory categories |\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Quick Start Configurations\n\n### Minimal Setup (Zero Dependencies)\n\n```env\n# No .env file needed - defaults work out of the box\n```\n\n```bash\npip install genesys-memory\nuvicorn genesys.api:app --port 8000\n```\n\n### Fully Local with Obsidian\n\n```env\nGENESYS_BACKEND=obsidian\nGENESYS_EMBEDDER=local\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n```\n\n### Production with PostgreSQL\n\n```env\nOPENAI_API_KEY=sk-...\nANTHROPIC_API_KEY=sk-ant-...\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\n```\n\n### Multi-Tenant with Organizations\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Configuration Flow\n\n```mermaid\ngraph TD\n    A[Application Start] --> B{Load Environment Variables}\n    B --> C{GENESYS_BACKEND?}\n    C -->|memory| D[In-Memory Storage]\n    C -->|postgres| E[PostgreSQL + pgvector]\n    C -->|obsidian| F[Obsidian Vault]\n    C -->|falkordb| G[FalkorDB]\n    \n    H{GENESYS_EMBEDDER?}\n    H -->|openai| I[OpenAI Embeddings]\n    H -->|local| J[Local sentence-transformers]\n    \n    D --> K[Initialize MCP Server]\n    E --> K\n    F --> K\n    G --> K\n    \n    I --> L[Ready]\n    J --> L\n    \n    K --> M[Register Tools]\n    M --> L\n```\n\n## Engine Thresholds\n\nEngine thresholds such as decay rates, scoring multipliers, and transition thresholds are configurable through environment variables. These values are defined in `engine/config.py` and should not be hardcoded.\n\nFor the most current threshold configurations, refer to the source file:\n\n```python\n# Refer to src/genesys_memory/engine/config.py for threshold values\n```\n\n资料来源: [CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n## See Also\n\n- [Contributing Guide](CONTRIBUTING.md) - Development setup and coding standards\n- [README.md](README.md) - Project overview and features\n- [Benchmarks](../benchmarks/) - Performance testing configurations\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：rishimeka/genesys\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1207565616 | https://github.com/rishimeka/genesys | host_targets=mcp_host, claude\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:1207565616 | https://github.com/rishimeka/genesys | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | release_recency=unknown\n\n<!-- canonical_name: rishimeka/genesys; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "genesys",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1207565616",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/rishimeka/genesys"
        },
        {
          "evidence_id": "art_941c32fc1635457bacf35da1c1c1970e",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/rishimeka/genesys#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "genesys 说明书",
      "toc": [
        "https://github.com/rishimeka/genesys 项目说明书",
        "目录",
        "Getting Started with Genesys",
        "Overview",
        "Architecture Overview",
        "Installation",
        "Configuration",
        "Quick Start: In-Memory Backend",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "0015664c38ab5fa65f2fbe512a57700fd6712175",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "Dockerfile",
      "README.md",
      "docker-compose.yml",
      "src/genesys_memory/context.py",
      "src/genesys_memory/server.py",
      "src/genesys_memory/__init__.py",
      "src/genesys_memory/__main__.py",
      "src/genesys_memory/providers.py",
      "src/genesys_memory/mcp/tools.py",
      "src/genesys_memory/mcp/__init__.py",
      "src/genesys_memory/core_memory/preferences.py",
      "src/genesys_memory/core_memory/promoter.py",
      "src/genesys_memory/core_memory/__init__.py",
      "src/genesys_memory/models/edge.py",
      "src/genesys_memory/models/enums.py",
      "src/genesys_memory/models/__init__.py",
      "src/genesys_memory/models/node.py",
      "src/genesys_memory/storage/memory.py",
      "src/genesys_memory/storage/__init__.py",
      "src/genesys_memory/storage/cache.py",
      "src/genesys_memory/storage/base.py",
      "src/genesys_memory/engine/llm_provider.py",
      "src/genesys_memory/engine/transitions.py",
      "src/genesys_memory/engine/contradiction.py",
      "src/genesys_memory/engine/scoring.py",
      "src/genesys_memory/engine/forgetting.py",
      "src/genesys_memory/engine/consolidation.py",
      "src/genesys_memory/engine/reactivation.py",
      "src/genesys_memory/engine/__init__.py",
      "src/genesys_memory/engine/config.py",
      "src/genesys_memory/retrieval/embedding.py",
      "src/genesys_memory/retrieval/__init__.py"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [
      "community_discussion_evidence_below_public_threshold"
    ],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# genesys - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 genesys 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **想在安装前理解开源项目价值和边界的用户**：当前证据主要来自项目文档。 Claim：`clm_0002` unverified 0.25\n\n## 它能做什么\n\n- **项目知识预览**（可做安装前预览）：项目可被阅读和解释，但当前证据不足以确认可安装能力或运行入口。 证据：`benchmarks/README.md`, `CONTRIBUTING.md`, `LICENSE`, `.github/pull_request_template.md` 等 Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- 项目证据中没有稳定 Quick Start 命令；此项应留空，而不是由 Doramagic 编造。\n\n## 继续前判断卡\n\n- **当前建议**：先做 Prompt Preview\n- **为什么**：当前信息足以做安装前体验，但真实兼容性、输出质量或风险边界还不能直接相信。\n\n### 30 秒判断\n\n- **现在怎么做**：先做 Prompt Preview\n- **最小安全下一步**：先跑 Prompt Preview\n- **先别相信**：真实输出质量不能在安装前相信。\n- **继续会触碰**：宿主 AI 上下文\n\n### 现在可以相信\n\n- **能力存在：项目知识预览**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`benchmarks/README.md`, `CONTRIBUTING.md`, `LICENSE`, `.github/pull_request_template.md` 等 Claim：`clm_0001` supported 0.86\n\n### 现在还不能相信\n\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0003` inferred 0.45\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **项目知识预览**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`benchmarks/README.md`, `CONTRIBUTING.md`, `LICENSE`, `.github/pull_request_template.md` 等 Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：89\n- 重要文件覆盖：34/89\n- 证据索引条目：33\n- 角色 / Skill 条目：7\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 genesys 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 genesys 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 genesys 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 7 个角色 / Skill / 项目文档条目。\n\n- **Genesys Benchmarks**（project_doc）：Evaluated on the LoCoMo https://arxiv.org/abs/2402.06397 long-conversation memory benchmark: 10 conversations, 1,540 questions category 5 adversarial excluded , judged by LLM-as-Judge. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`benchmarks/README.md`\n- **Contributing to Genesys**（project_doc）：Thanks for your interest in contributing! Genesys is open source under the GNU Affero General Public License v3.0 LICENSE . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **What does this PR do?**（project_doc）：- Tests pass pytest tests/ -v - Linting passes ruff check src/ - New tests added if applicable 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/pull_request_template.md`\n- **Changelog**（project_doc）：- Edge semantics correctness breaking behavior change : Nodes with only CONTRADICTS or SUPERSEDES edges are now considered orphans for forgetting purposes. Previously, any edge — including contradiction edges — prevented a node from being classified as an orphan, which meant contradicted memories were immune to pruning and could be incorrectly promoted to core status. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CHANGELOG.md`\n- **Genesys Contributor License Agreement**（project_doc）：Genesys Contributor License Agreement 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CLA.md`\n- **Security Policy**（project_doc）：If you discover a security vulnerability, please report it privately via GitHub's security advisory feature https://github.com/rishimeka/genesys/security/advisories/new . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY.md`\n- **GENESYS — Causal Graph Memory Platform**（project_doc）：GENESYS — Causal Graph Memory Platform 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`benchmarks/REPORT.md`\n\n## 证据索引\n\n- 共索引 33 条证据。\n\n- **Genesys Benchmarks**（documentation）：Evaluated on the LoCoMo https://arxiv.org/abs/2402.06397 long-conversation memory benchmark: 10 conversations, 1,540 questions category 5 adversarial excluded , judged by LLM-as-Judge. 证据：`benchmarks/README.md`\n- **Contributing to Genesys**（documentation）：Thanks for your interest in contributing! Genesys is open source under the GNU Affero General Public License v3.0 LICENSE . 证据：`CONTRIBUTING.md`\n- **License**（source_file）：GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 证据：`LICENSE`\n- **What does this PR do?**（documentation）：- Tests pass pytest tests/ -v - Linting passes ruff check src/ - New tests added if applicable 证据：`.github/pull_request_template.md`\n- **Changelog**（documentation）：- Edge semantics correctness breaking behavior change : Nodes with only CONTRADICTS or SUPERSEDES edges are now considered orphans for forgetting purposes. Previously, any edge — including contradiction edges — prevented a node from being classified as an orphan, which meant contradicted memories were immune to pruning and could be incorrectly promoted to core status. 证据：`CHANGELOG.md`\n- **Genesys Contributor License Agreement**（documentation）：Genesys Contributor License Agreement 证据：`CLA.md`\n- **Security Policy**（documentation）：If you discover a security vulnerability, please report it privately via GitHub's security advisory feature https://github.com/rishimeka/genesys/security/advisories/new . 证据：`SECURITY.md`\n- **GENESYS — Causal Graph Memory Platform**（documentation）：GENESYS — Causal Graph Memory Platform 证据：`benchmarks/REPORT.md`\n- **Locomo Judged**（structured_config）：{ \"metadata\": { \"answer model\": \"gpt-4o-mini\", \"judge model\": \"gpt-4o-mini\", \"retrieval k\": 20, \"total questions\": 1540, \"overall j score\": 89.9, \"per category\": { \"Single-hop\": { \"correct\": 266, \"total\": 282, \"j score\": 94.3 }, \"Temporal\": { \"correct\": 281, \"total\": 321, \"j score\": 87.5 }, \"Multi-hop\": { \"correct\": 67, \"total\": 96, \"j score\": 69.8 }, \"Open-domain\": { \"correct\": 771, \"total\": 841, \"j score\": 91.7 } }, \"per conversation\": { \"conv-26\": { \"correct\": 143, \"total\": 152, \"j score\": 94.1 }, \"conv-30\": { \"correct\": 80, \"total\": 81, \"j score\": 98.8 }, \"conv-41\": { \"correct\": 130, \"total\": 152, \"j score\": 85.5 }, \"conv-42\": { \"correct\": 180, \"total\": 199, \"j score\": 90.5 }, \"conv-43\"… 证据：`benchmarks/locomo_judged.json`\n- **Default Core Categories**（structured_config）：{ \"auto promote categories\": \"professional\", \"educational\", \"family\", \"location\" , \"approval required categories\": , \"excluded categories\": , \"notes\": { \"professional\": \"Job title, employer, industry, skills, career goals\", \"educational\": \"Degrees, institutions, certifications, fields of study\", \"family\": \"Spouse/partner, children, parents, siblings, family structure\", \"location\": \"Home city, home country, neighborhood, time zone\", \"medical\": \"Not auto-promoted by default. Add to auto promote or approval required per user preference.\", \"financial\": \"Not auto-promoted by default. Sensitive category.\", \"preference\": \"General preferences food, hobbies, communication style . Not auto-promoted —… 证据：`config/default_core_categories.json`\n- **Server**（structured_config）：{ \"$schema\": \"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json\", \"name\": \"io.github.rishimeka/genesys-memory\", \"description\": \"Causal graph memory engine for AI agents with scoring, activation, and forgetting\", \"repository\": { \"url\": \"https://github.com/rishimeka/genesys\", \"source\": \"github\" }, \"version\": \"0.3.11\", \"packages\": { \"registryType\": \"pypi\", \"identifier\": \"genesys-memory\", \"version\": \"0.3.11\", \"transport\": { \"type\": \"stdio\" }, \"environmentVariables\": { \"description\": \"OpenAI API key for embedding generation optional — use GENESYS EMBEDDER=local for no API key \", \"isRequired\": false, \"format\": \"string\", \"isSecret\": true, \"name\": \"OPENAI API KEY\" }, { \"d… 证据：`server.json`\n- **Causal Reasoning**（structured_config）：{ \"name\": \"causal reasoning\", \"description\": \"Tests multi-hop causal chain traversal. Memories form cause-effect chains that require following edges to answer correctly.\", \"conversation history\": {\"turn\": 1, \"week\": 1, \"content\": \"I started learning Python because my manager suggested it for automating reports.\"}, {\"turn\": 2, \"week\": 1, \"content\": \"I found a Python course on Udemy that covers pandas for data analysis.\"}, {\"turn\": 3, \"week\": 1, \"content\": \"Had a really nice lunch at the new Thai place across the street. The pad see ew was excellent.\"}, {\"turn\": 4, \"week\": 1, \"content\": \"It was raining all day today, couldn't even go for my usual walk after lunch.\"}, {\"turn\": 5, \"week\": 1, \"c… 证据：`benchmarks/scenarios/causal_reasoning.json`\n- **Outdated Info**（structured_config）：{ \"name\": \"outdated info\", \"description\": \"Tests handling of superseded information, contradictions, and evolving facts over time.\", \"conversation history\": {\"turn\": 1, \"week\": 1, \"content\": \"I live in San Francisco. My apartment is on Market Street.\"}, {\"turn\": 2, \"week\": 1, \"content\": \"I found this great ramen place near my apartment called Tanaka Ramen. I've been going almost every day.\"}, {\"turn\": 3, \"week\": 1, \"content\": \"I use VS Code for all my editing. It's the best editor I've ever used.\"}, {\"turn\": 4, \"week\": 2, \"content\": \"I'm using Python 3.9 for my main project at work.\"}, {\"turn\": 5, \"week\": 2, \"content\": \"Had an amazing burrito from the taqueria on Valencia Street for lunch t… 证据：`benchmarks/scenarios/outdated_info.json`\n- **Structural Importance**（structured_config）：{ \"name\": \"structural importance\", \"description\": \"Tests whether the system retains structurally important memories high connectivity, core status while allowing peripheral memories to decay.\", \"conversation history\": {\"turn\": 1, \"week\": 1, \"content\": \"I'm a software engineer at TechCorp, working on the payments team.\"}, {\"turn\": 2, \"week\": 1, \"content\": \"Our payment system processes about 50,000 transactions per day using Stripe.\"}, {\"turn\": 3, \"week\": 1, \"content\": \"Got a breakfast burrito from the food truck outside the office. Pretty solid.\"}, {\"turn\": 4, \"week\": 1, \"content\": \"My commute was brutal today, 45 minutes because of an accident on the highway.\"}, {\"turn\": 5, \"week\": 2, \"cont… 证据：`benchmarks/scenarios/structural_importance.json`\n- **Temporal Awareness**（structured_config）：{ \"name\": \"temporal awareness\", \"description\": \"Tests ability to track how information evolves over time and maintain correct temporal ordering of events.\", \"conversation history\": {\"turn\": 1, \"week\": 1, \"content\": \"I just adopted a rescue dog named Max. He's a 2-year-old German Shepherd mix.\"}, {\"turn\": 2, \"week\": 1, \"content\": \"Max is very anxious around other dogs. The vet recommended a behavioral trainer.\"}, {\"turn\": 3, \"week\": 1, \"content\": \"Made spaghetti for dinner tonight. Tried a new marinara recipe from that YouTube channel I like.\"}, {\"turn\": 4, \"week\": 1, \"content\": \"It's been raining all week. I'm stuck inside with Max and he's restless, keeps pacing around the apartment.\"}, {\"… 证据：`benchmarks/scenarios/temporal_awareness.json`\n- **.dockerignore**（source_file）：pycache .pyc .git .env .venv venv node modules genesys-ui/node modules genesys-ui/.next tests benchmarks phases schemas .md !README.md .mypy cache .pytest cache .ruff cache docker-compose.yml 证据：`.dockerignore`\n- **Python**（source_file）：Python pycache / .pyc .pyo .egg-info/ dist/ build/ .venv/ venv/ .mypy cache/ .pytest cache/ .ruff cache/ 证据：`.gitignore`\n- **.Pre Commit Config**（source_file）：repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - id: check-added-large-files args: '--maxkb=1000' 证据：`.pre-commit-config.yaml`\n- **Dockerfile**（source_file）：COPY pyproject.toml README.md ./ COPY src/ src/ 证据：`Dockerfile`\n- **Dockerfile**（source_file）：COPY pyproject.toml README.md ./ COPY src/ src/ 证据：`Dockerfile.mcp`\n- **Alembic**（source_file）：alembic script location = alembic sqlalchemy.url = postgresql://localhost/genesys 证据：`alembic.ini`\n- **Override URL from environment**（source_file）：\"\"\"Alembic environment for raw SQL migrations no SQLAlchemy models .\"\"\" import os from logging.config import fileConfig 证据：`alembic/env.py`\n- **Script.Py**（source_file）：Revision ID: ${up revision} Revises: ${down revision comma,n} Create Date: ${create date} \"\"\" from typing import Sequence, Union from alembic import op import sqlalchemy as sa 证据：`alembic/script.py.mako`\n- **Baseline Flat**（source_file）：\"\"\"Flat vector memory baseline for benchmark comparison.\"\"\" from future import annotations 证据：`benchmarks/baseline_flat.py`\n- **gpt-4o-mini: 500 RPM on Tier 1, much higher on Tier 2+. Use 400 for headroom.**（source_file）：\"\"\"Run LoCoMo QA evaluation against Genesys. 证据：`benchmarks/locomo_eval.py`\n- **Clear any existing data for this conversation's user scope**（source_file）：\"\"\"Ingest LoCoMo conversations into Genesys via the REST API. 证据：`benchmarks/locomo_ingest.py`\n- **Limit concurrency to avoid rate limits**（source_file）：\"\"\"Judge LoCoMo eval results using LLM-as-Judge Claude Haiku . 证据：`benchmarks/locomo_judge.py`\n- **Build one memory per session: concatenate all turns with speaker labels**（source_file）：\"\"\"LoCoMo full pipeline: per-conversation independent runs. 证据：`benchmarks/locomo_run.py`\n- **!/usr/bin/env python3**（source_file）：!/usr/bin/env python3 \"\"\"Benchmark runner: compares Genesys causal memory vs flat vector baseline. 证据：`benchmarks/run_benchmark.py`\n- **Init**（source_file）：CREATE EXTENSION IF NOT EXISTS vector; CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"; 证据：`config/init.sql`\n- **Docker Compose**（source_file）：services: postgres: image: pgvector/pgvector:pg16 ports: - \"5432:5432\" environment: POSTGRES DB: genesys POSTGRES USER: genesys POSTGRES PASSWORD: genesys volumes: - postgres data:/var/lib/postgresql/data - ./config/init.sql:/docker-entrypoint-initdb.d/init.sql:ro healthcheck: test: \"CMD-SHELL\", \"pg isready -U genesys\" interval: 10s timeout: 5s retries: 5 证据：`docker-compose.yml`\n- **Pyproject**（source_file）：project name = \"genesys-memory\" dynamic = \"version\" description = \"The intelligence layer for AI memory — scoring, causal inference, lifecycle management, and active forgetting\" readme = \"README.md\" authors = {name = \"Genesys Contributors\"} license = {text = \"AGPL-3.0-or-later\"} requires-python = \" =3.11\" keywords = \"memory\", \"ai\", \"mcp\", \"causal-graph\", \"agents\" classifiers = \"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: GNU Affero General Public License v3 or later AGPLv3+ \", \"Programming Language :: Python :: 3.11\", \"Programming Language :: Python :: 3.12\", \"Topic :: Scientific/Engineering :: Artificial Intelligence\", dependencies = \"pyd… 证据：`pyproject.toml`\n- **!/usr/bin/env python3**（source_file）：!/usr/bin/env python3 \"\"\"Migrate memories from JSON in-memory backend to Postgres. 证据：`scripts/migrate_to_postgres.py`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`benchmarks/README.md`, `CONTRIBUTING.md`, `LICENSE`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`benchmarks/README.md`, `CONTRIBUTING.md`, `LICENSE`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Getting Started with Genesys**：importance `high`\n  - source_paths: README.md, pyproject.toml, .env.example\n- **System Architecture**：importance `high`\n  - source_paths: src/genesys_memory/__init__.py, src/genesys_memory/server.py, src/genesys_memory/engine/__init__.py, src/genesys_memory/storage/__init__.py\n- **Memory Scoring Engine**：importance `high`\n  - source_paths: src/genesys_memory/engine/scoring.py, src/genesys_memory/engine/config.py, src/genesys_memory/engine/reactivation.py\n- **Memory Lifecycle Management**：importance `high`\n  - source_paths: src/genesys_memory/engine/transitions.py, src/genesys_memory/engine/forgetting.py, src/genesys_memory/engine/consolidation.py\n- **Nodes and Edges Data Models**：importance `medium`\n  - source_paths: src/genesys_memory/models/node.py, src/genesys_memory/models/edge.py, src/genesys_memory/models/enums.py, src/genesys_memory/models/__init__.py\n- **Graph Traversal and Causal Reasoning**：importance `medium`\n  - source_paths: src/genesys_memory/engine/contradiction.py, src/genesys_memory/mcp/tools.py, src/genesys_memory/context.py\n- **Storage Backend Comparison**：importance `high`\n  - source_paths: src/genesys_memory/storage/memory.py, docker-compose.yml, config/init.sql\n- **Storage Provider Implementation**：importance `medium`\n  - source_paths: src/genesys_memory/storage/base.py, src/genesys_memory/storage/cache.py, src/genesys_memory/providers.py\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `0015664c38ab5fa65f2fbe512a57700fd6712175`\n- inspected_files: `pyproject.toml`, `Dockerfile`, `README.md`, `docker-compose.yml`, `src/genesys_memory/context.py`, `src/genesys_memory/server.py`, `src/genesys_memory/__init__.py`, `src/genesys_memory/__main__.py`, `src/genesys_memory/providers.py`, `src/genesys_memory/mcp/tools.py`, `src/genesys_memory/mcp/__init__.py`, `src/genesys_memory/core_memory/preferences.py`, `src/genesys_memory/core_memory/promoter.py`, `src/genesys_memory/core_memory/__init__.py`, `src/genesys_memory/models/edge.py`, `src/genesys_memory/models/enums.py`, `src/genesys_memory/models/__init__.py`, `src/genesys_memory/models/node.py`, `src/genesys_memory/storage/memory.py`, `src/genesys_memory/storage/__init__.py`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 可能修改宿主 AI 配置\n\n- Trigger: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- Host AI rule: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Why it matters: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Evidence: capability.host_targets | github_repo:1207565616 | https://github.com/rishimeka/genesys | host_targets=mcp_host, claude\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:1207565616 | https://github.com/rishimeka/genesys | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: issue/PR 响应质量未知\n\n- Trigger: issue_or_pr_quality=unknown。\n- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。\n- Why it matters: 用户无法判断遇到问题后是否有人维护。\n- Evidence: evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | issue_or_pr_quality=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 发布节奏不明确\n\n- Trigger: release_recency=unknown。\n- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。\n- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Evidence: evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | release_recency=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：rishimeka/genesys\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：mcp_host, claude\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- review_required: community_discussion_evidence_below_public_threshold\n\n## 项目专属踩坑\n\n- 可能修改宿主 AI 配置（medium）：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 能力判断依赖假设（medium）：假设不成立时，用户拿不到承诺的能力。 建议检查：将假设转成下游验证清单。\n- 维护活跃度未知（medium）：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 下游验证发现风险项（medium）：下游已经要求复核，不能在页面中弱化。 建议检查：进入安全/权限治理复核队列。\n- 存在评分风险（medium）：风险会影响是否适合普通用户安装。 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/rishimeka/genesys 项目说明书\n\n生成时间：2026-05-15 07:11:52 UTC\n\n## 目录\n\n- [Getting Started with Genesys](#getting-started)\n- [System Architecture](#architecture)\n- [Memory Scoring Engine](#memory-scoring)\n- [Memory Lifecycle Management](#memory-lifecycle)\n- [Nodes and Edges Data Models](#nodes-edges)\n- [Graph Traversal and Causal Reasoning](#graph-traversal)\n- [Storage Backend Comparison](#backends-overview)\n- [Storage Provider Implementation](#storage-implementation)\n- [MCP Tools Reference](#mcp-tools)\n- [Configuration Guide](#configuration)\n\n<a id='getting-started'></a>\n\n## Getting Started with Genesys\n\n### 相关页面\n\n相关主题：[Configuration Guide](#configuration), [Storage Backend Comparison](#backends-overview)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n- [src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [server.json](https://github.com/rishimeka/genesys/blob/main/server.json)\n</details>\n\n# Getting Started with Genesys\n\n## Overview\n\nGenesys is an **intelligence layer for AI memory** — a scoring engine, causal graph, and lifecycle manager for AI agent memory. It provides persistent memory capabilities with intelligent forgetting, ensuring AI systems maintain context across sessions without unbounded memory growth.\n\nThe system speaks MCP (Model Context Protocol) natively, making it compatible with Claude Code, Claude Desktop, and any MCP-compatible AI client.\n\n**Key capabilities:**\n\n- Multi-force memory scoring (relevance × connectivity × reactivation)\n- Causal graph relationships between memories\n- Intelligent forgetting — memories decay and are pruned when irrelevant\n- Core memory promotion for structurally important information\n- Multiple storage backends (in-memory, Postgres, Obsidian, FalkorDB)\n- Hybrid retrieval (vector + keyword + graph spreading activation)\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Architecture Overview\n\nGenesys Memory is organized into several core modules:\n\n```\nsrc/genesys_memory/\n├── engine/             # Scoring, transitions, forgetting, reactivation\n│   ├── config.py       # All tunable thresholds (env-configurable)\n│   ├── scoring.py      # Three-force multiplicative decay scoring\n│   ├── transitions.py  # Status FSM (ACTIVE -> DORMANT -> FADING -> PRUNED)\n│   ├── forgetting.py   # Conjunctive active forgetting\n│   └── reactivation.py # BFS cascade reactivation\n├── core_memory/        # Core promotion logic (graph-derived)\n├── storage/            # Storage provider abstractions + implementations\n│   ├── base.py         # Abstract interfaces (GraphStorageProvider, etc.)\n│   └── memory.py       # In-memory implementation\n└── mcp/                # MCP protocol tools and server\n    └── tools.py        # MCP tool implementations\n```\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n### Memory Lifecycle State Machine\n\nMemories progress through defined states with configurable transitions:\n\n```mermaid\ngraph LR\n    STORE[STORE] --> ACTIVE[ACTIVE]\n    ACTIVE --> DORMANT[DORMANT]\n    DORMANT --> FADING[FADING]\n    FADING --> PRUNED[PRUNED]\n    ACTIVE -->|reactivation| ACTIVE\n    DORMANT -->|reactivation| ACTIVE\n    FADING -->|reactivation| DORMANT\n    \n    style PRUNED fill:#ff6b6b\n    style ACTIVE fill:#51cf66\n    style DORMANT fill:#fcc419\n```\n\n### Memory Scoring Formula\n\nEvery memory is scored by three forces multiplied together:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n| Force | Description |\n|-------|-------------|\n| **Relevance** | Decays over time. Old memories fade unless reinforced. |\n| **Connectivity** | Rewards memories with many causal links. Hub memories survive. |\n| **Reactivation** | Boosts memories that keep getting recalled. Frequency matters. |\n\nBecause the formula is multiplicative, a memory must score on **all three axes** to survive. A highly connected but never-accessed memory still decays.\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Installation\n\n### Prerequisites\n\n- Python 3.11+\n- pip or uv package manager\n\n### Package Installation\n\nGenesys Memory is published as `genesys-memory` on PyPI:\n\n```bash\npip install genesys-memory\n```\n\n### Backend-Specific Installation\n\nDepending on your chosen storage backend, install with additional dependencies:\n\n| Backend | Install Command |\n|---------|-----------------|\n| In-memory (default) | `pip install genesys-memory` |\n| Postgres + pgvector | `pip install 'genesys-memory[postgres]'` |\n| Obsidian Vault | `pip install 'genesys-memory[obsidian]'` |\n| FalkorDB | `pip install 'genesys-memory[falkordb]'` |\n| Local embeddings (no API key) | `pip install 'genesys-memory[local]'` |\n\n### Full Installation with All Backends\n\n```bash\npip install 'genesys-memory[postgres,obsidian,local]'\n```\n\n### Development Installation\n\n```bash\ngit clone https://github.com/rishimeka/genesys.git\ncd genesys\npip install -e '.[dev]'\n```\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Configuration\n\n### Environment Variables\n\nCopy the example configuration:\n\n```bash\ncp .env.example .env\n```\n\nConfigure the following variables based on your setup:\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `OPENAI_API_KEY` | Unless `GENESYS_EMBEDDER=local` | — | OpenAI API key for embeddings |\n| `ANTHROPIC_API_KEY` | No | — | Anthropic API key for LLM memory processing |\n| `GENESYS_BACKEND` | No | `memory` | Storage backend: `memory`, `postgres`, `obsidian`, `falkordb` |\n| `GENESYS_EMBEDDER` | No | `openai` | Embedding provider: `openai` or `local` |\n| `DATABASE_URL` | If postgres | — | Postgres connection string |\n| `OBSIDIAN_VAULT_PATH` | If obsidian | — | Path to your Obsidian vault |\n| `FALKORDB_HOST` | If falkordb | `localhost` | FalkorDB host |\n| `GENESYS_USER_ID` | No | — | Default user ID for single-tenant mode |\n| `GENESYS_PERSIST_PATH` | No | — | Path for state persistence (e.g., `.genesys_state.json`) |\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Storage Backends\n\n| Backend | Use Case | Dependencies |\n|---------|----------|--------------|\n| `memory` | Zero deps, try it out | Built-in |\n| `postgres` + pgvector | Persistent, scalable | Postgres + Docker |\n| `obsidian` | Local-first knowledge base | Obsidian vault |\n| `falkordb` | Graph-native traversal | FalkorDB (Redis-based) |\n\n---\n\n## Quick Start: In-Memory Backend\n\nThe in-memory backend requires no external services — ideal for testing and development.\n\n### 1. Create Configuration\n\n```bash\ncp .env.example .env\n```\n\nEdit `.env`:\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=memory\n```\n\n### 2. Start the Server\n\n```bash\nuvicorn genesys.api:app --port 8000\n```\n\n### 3. Persist State (Optional)\n\nTo persist memory across restarts:\n\n```env\nGENESYS_PERSIST_PATH=.genesys_state.json\n```\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Option 1: Postgres + pgvector (Production)\n\nFor persistent, scalable storage with vector search capabilities.\n\n### 1. Install Dependencies\n\n```bash\npip install 'genesys-memory[postgres]'\n```\n\n### 2. Configure Environment\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\n```\n\n### 3. Start Infrastructure\n\n```bash\ndocker compose up -d postgres\nalembic upgrade head\n```\n\n### 4. Start the Server\n\n```bash\nGENESYS_BACKEND=postgres uvicorn genesys.api:app --port 8000\n```\n\n> **Give this to Claude to set it up for you:**\n> *\"Install genesys-memory[postgres], start a Postgres container with pgvector using docker compose, run alembic migrations, create a .env with my OpenAI key and DATABASE_URL, start the server with GENESYS_BACKEND=postgres, and connect it as an MCP server.\"*\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Option 2: Obsidian Vault (Local-First)\n\nTurn your Obsidian vault into a Genesys memory store. Markdown files become memory nodes, `[[wikilinks]]` become causal edges.\n\n### 1. Install Dependencies\n\n```bash\npip install 'genesys-memory[obsidian]'\n```\n\n### 2. Configure Environment\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=obsidian\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n```\n\n> If `OBSIDIAN_VAULT_PATH` is not set, Genesys auto-detects by looking for `.obsidian/` in `~/Documents/personal`, `~/Documents/Obsidian`, and `~/obsidian`.\n\n### 3. Start the Server\n\n```bash\nuvicorn genesys.api:app --port 8000\n```\n\nOn first start, Genesys indexes all `.md` files in the vault and generates embeddings. A file watcher re-indexes incrementally when you edit notes.\n\n### 4. Fully Local (No API Keys)\n\nFor zero external dependencies, use local embeddings:\n\n```bash\npip install 'genesys-memory[obsidian,local]'\n```\n\n```env\nGENESYS_BACKEND=obsidian\nGENESYS_EMBEDDER=local\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n# No OPENAI_API_KEY needed\n```\n\nThis uses `all-MiniLM-L6-v2` (384-dim) via `sentence-transformers` for embeddings. The model is downloaded on first use (~80 MB).\n\n> **Give this to Claude to set it up for you:**\n> *\"Install genesys-memory[obsidian,local], create a .env with GENESYS_BACKEND=obsidian, GENESYS_EMBEDDER=local, and OBSIDIAN_VAULT_PATH to my vault at [YOUR_VAULT_PATH], start the server on port 8000, and connect it as an MCP server. No API keys needed.\"*\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Option 3: FalkorDB (Graph-Native)\n\nUses FalkorDB (Redis-based graph database) for native graph traversal.\n\n### 1. Install Dependencies\n\n```bash\npip install 'genesys-memory[falkordb]'\n```\n\n### 2. Configure Environment\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=falkordb\nFALKORDB_HOST=localhost\n```\n\n### 3. Start Infrastructure\n\n```bash\ndocker compose up -d falkordb\n```\n\n### 4. Start the Server\n\n```bash\nuvicorn genesys.api:app --port 8000\n```\n\n> **Give this to Claude to set it up for you:**\n> *\"Install genesys-memory[falkordb], start a FalkorDB container using docker compose, create a .env with my OpenAI key and GENESYS_BACKEND=falkordb, start the server on port 8000, and connect it as an MCP server.\"*\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Connecting to AI Clients\n\n### Claude Code\n\n```bash\nclaude mcp add --transport http genesys http://localhost:8000/mcp\n```\n\n### Claude Desktop\n\nAdd to your `claude_desktop_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"genesys\": {\n      \"url\": \"http://localhost:8000/mcp\"\n    }\n  }\n}\n```\n\n### Any MCP Client\n\nPoint your client at the MCP endpoint:\n\n```\nhttp://localhost:8000/mcp\n```\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## MCP Tools Reference\n\nGenesys provides the following MCP tools for memory operations:\n\n| Tool | Description |\n|------|-------------|\n| `memory_store` | Store a new memory, optionally linking to related memories |\n| `memory_recall` | Recall memories by natural language query (vector + graph) |\n| `memory_search` | Search memories with filters (status, date range, keyword) |\n| `memory_traverse` | Walk the causal graph from a given memory node |\n| `memory_explain` | Explain why a memory exists and its causal chain |\n| `memory_stats` | Get memory system statistics |\n| `pin_memory` | Pin a memory so it's never forgotten |\n| `unpin_memory` | Unpin a previously pinned memory |\n| `delete_memory` | Permanently delete a memory |\n| `list_core_memories` | List core memories, optionally filtered by category |\n| `set_core_preferences` | Set user preferences for core memory categories |\n\n### Tool Schemas\n\n#### memory_store\n\n```json\n{\n  \"name\": \"memory_store\",\n  \"description\": \"Store a new memory node\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"content\"],\n    \"properties\": {\n      \"content\": {\"type\": \"string\"},\n      \"related_to\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n      \"category\": {\"type\": \"string\"}\n    }\n  }\n}\n```\n\n#### memory_recall\n\n```json\n{\n  \"name\": \"memory_recall\",\n  \"description\": \"Recall memories using hybrid search (vector + keyword + graph spreading activation)\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"query\"],\n    \"properties\": {\n      \"query\": {\"type\": \"string\"},\n      \"k\": {\"type\": \"integer\", \"default\": 10},\n      \"max_results\": {\"type\": \"integer\"}\n    }\n  }\n}\n```\n\n#### memory_search\n\n```json\n{\n  \"name\": \"memory_search\",\n  \"description\": \"Filtered vector search by status, category, date, or entity\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"query\"],\n    \"properties\": {\n      \"query\": {\"type\": \"string\"},\n      \"filters\": {\"type\": \"object\"},\n      \"k\": {\"type\": \"integer\", \"default\": 10}\n    }\n  }\n}\n```\n\n#### memory_traverse\n\n```json\n{\n  \"name\": \"memory_traverse\",\n  \"description\": \"Traverse the memory graph from a starting node\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"node_id\"],\n    \"properties\": {\n      \"node_id\": {\"type\": \"string\"},\n      \"depth\": {\"type\": \"integer\", \"default\": 2},\n      \"edge_types\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n    }\n  }\n}\n```\n\n#### memory_explain\n\n```json\n{\n  \"name\": \"memory_explain\",\n  \"description\": \"Explain a memory's score breakdown\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"required\": [\"node_id\"],\n    \"properties\": {\n      \"node_id\": {\"type\": \"string\"}\n    }\n  }\n}\n```\n\n资料来源：[src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n---\n\n## Memory Node Data Model\n\nEach memory is represented as a `MemoryNode` with the following structure:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    \n    # Content\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    content_ref: str | None = None\n    embedding: list[float] | None = None\n    \n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern\n    irrelevance_counter: int = 0\n    \n    # Provenance\n    source_agent: str = \"claude\"\n    source_session: str = \"\"\n    \n    # Classification\n    entity_refs: list[str] = Field(default_factory=list)\n    category: str | None = None\n    \n    # Stability\n    stability: float = 1.0\n    \n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n    \n    # Reactivation history\n    reactivation_timestamps: list[datetime] = Field(default_factory=list)\n```\n\n资料来源：[src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n---\n\n## Memory Retrieval Flow\n\nThe recall operation uses a hybrid approach combining vector similarity, keyword matching, and graph spreading activation:\n\n```mermaid\ngraph TD\n    Query[User Query] --> Embed[Generate Embedding]\n    Embed --> VectorSearch[Vector Similarity Search]\n    Query --> KeywordSearch[Keyword Search]\n    VectorSearch --> Combine[Hybrid Ranking]\n    KeywordSearch --> Combine\n    Combine --> GraphSpread[Graph Spreading Activation]\n    GraphSpread --> Results[Ranked Memories]\n```\n\n资料来源：[src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n---\n\n## Development and Testing\n\n### Code Style\n\n- **Python 3.11+**, async-first\n- **Linting**: `ruff check src/` (config in `pyproject.toml`, line length 120)\n- **Type checking**: `mypy src/genesys_memory --ignore-missing-imports`\n- **Formatting**: Type hints throughout, minimal comments\n\n### Running Tests\n\n```bash\n# Run all unit tests\npytest tests/ -v\n\n# With coverage\npytest tests/ -v --cov=src/genesys_memory --cov-report=term-missing\n```\n\nTests are in `tests/` and use `pytest-asyncio` (auto mode).\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n---\n\n## Security\n\nGenesys follows a responsible disclosure policy for security vulnerabilities:\n\n| Version | Supported |\n|---------|-----------|\n| 0.3.x   | Yes       |\n| < 0.3   | No        |\n\nTo report a security vulnerability, use [GitHub's security advisory feature](https://github.com/rishimeka/genesys/security/advisories/new). **Do not open a public issue.**\n\n资料来源：[SECURITY.md](https://github.com/rishimeka/genesys/blob/main/SECURITY.md)\n\n---\n\n## License\n\nGenesys is open source under the [GNU Affero General Public License v3.0](LICENSE).\n\n> **Note:** Genesys releases prior to v0.3.6 were documented as Apache 2.0 in error. The LICENSE file has always contained the AGPLv3 text. From v0.3.6 onward, all documentation correctly references AGPL-3.0-or-later with a Contributor License Agreement.\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n---\n\n## Contributing\n\nContributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. Look for issues labeled `good first issue` for scoped, well-defined tasks suitable for new contributors.\n\nAll contributors must agree to the [Contributor License Agreement](CLA.md) before their code can be merged.\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n---\n\n<a id='architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Memory Scoring Engine](#memory-scoring), [Memory Lifecycle Management](#memory-lifecycle), [Nodes and Edges Data Models](#nodes-edges)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/__init__.py)\n- [src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n- [src/genesys_memory/engine/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/__init__.py)\n- [src/genesys_memory/storage/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/__init__.py)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [server.json](https://github.com/rishimeka/genesys/blob/main/server.json)\n</details>\n\n# System Architecture\n\n## Overview\n\nGenesys is a scoring engine, causal graph, and lifecycle manager for AI agent memory. It implements a sophisticated memory management system that enables AI agents to store, retrieve, and intelligently forget information over time. The system speaks MCP (Model Context Protocol) natively, allowing seamless integration with Claude Desktop and Claude Code.\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## High-Level Architecture\n\nThe Genesys system is organized into several interconnected layers:\n\n```mermaid\ngraph TB\n    subgraph \"Client Layer\"\n        ClaudeDesktop[\"Claude Desktop\"]\n        ClaudeCode[\"Claude Code\"]\n        MCPSDK[\"MCP SDK\"]\n    end\n    \n    subgraph \"API Layer\"\n        Server[\"MCP Server (stdio)\"]\n        Tools[\"MCP Tools\"]\n    end\n    \n    subgraph \"Core Engine\"\n        Scoring[\"Scoring Engine\"]\n        Lifecycle[\"Lifecycle Manager\"]\n        LLMProvider[\"LLM Provider\"]\n    end\n    \n    subgraph \"Storage Layer\"\n        MemoryBackend[\"In-Memory\"]\n        Postgres[\"Postgres + pgvector\"]\n        Obsidian[\"Obsidian Vault\"]\n        FalkorDB[\"FalkorDB\"]\n    end\n    \n    ClaudeDesktop & ClaudeCode --> MCPSDK\n    MCPSDK --> Server\n    Server --> Tools\n    Tools --> Scoring\n    Scoring --> Lifecycle\n    Scoring --> LLMProvider\n    Lifecycle --> MemoryBackend & Postgres & Obsidian & FalkorDB\n```\n\n**资料来源：** [server.json:1-30](https://github.com/rishimeka/genesys/blob/main/server.json) | [src/genesys_memory/server.py:1-20](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n## Component Architecture\n\n### MCP Server Layer\n\nThe MCP Server is the primary interface for client applications. It uses stdio transport for communication, making it suitable for desktop integration.\n\n| Component | Description | Source |\n|-----------|-------------|--------|\n| `app` | Main MCP Server instance | [server.py:20](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py) |\n| `providers` | Storage and tool providers | [server.py:24](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py) |\n| `_TOOL_DISPATCH` | Tool method routing table | [server.py:30-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py) |\n\nThe server initializes providers and tools via `get_providers()`:\n\n```python\nproviders = get_providers()\ntools = providers.tools\n```\n\n**资料来源：** [src/genesys_memory/server.py:23-27](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n### MCP Tools Interface\n\nThe MCP protocol exposes a set of tools that provide the primary interface for memory operations:\n\n| Tool | Description | Required Args |\n|------|-------------|---------------|\n| `memory_store` | Store a new memory with optional causal links | `content` |\n| `memory_recall` | Hybrid search using vector + keyword + graph | `query` |\n| `memory_search` | Filtered search by status, category, date | `query` |\n| `memory_traverse` | Graph traversal from a starting node | `node_id` |\n| `memory_explain` | Explain memory score breakdown | `node_id` |\n| `memory_stats` | Get graph statistics | none |\n| `pin_memory` | Pin memory to core status | `node_id` |\n| `unpin_memory` | Unpin and re-evaluate | `node_id` |\n| `delete_memory` | Permanently delete memory | `node_id` |\n| `list_core_memories` | List core memories by category | `category` (optional) |\n| `set_core_preferences` | Configure core memory categories | `auto`, `approval`, `excluded` |\n\n**资料来源：** [src/genesys_memory/server.py:7-80](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py) | [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Storage Layer\n\nGenesys supports multiple storage backends through a provider abstraction:\n\n```mermaid\ngraph LR\n    subgraph \"Storage Providers\"\n        Memory[\"MemoryProvider\"]\n        Postgres[\"PostgresProvider\"]\n        Obsidian[\"ObsidianProvider\"]\n        FalkorDB[\"FalkorDBProvider\"]\n    end\n    \n    subgraph \"Capabilities\"\n        Cache[\"CacheProvider\"]\n        Embedding[\"EmbeddingProvider\"]\n        EventBus[\"EventBusProvider\"]\n        Graph[\"GraphStorageProvider\"]\n    end\n    \n    Memory & Postgres & Obsidian & FalkorDB --> Cache\n    Memory & Postgres & Obsidian & FalkorDB --> Embedding\n    Memory & Postgres & Obsidian & FalkorDB --> Graph\n    Memory & Postgres & Obsidian & FalkorDB --> EventBus\n```\n\n#### Backend Comparison\n\n| Backend | Install | Use Case | Scalability |\n|---------|---------|----------|-------------|\n| `memory` | Built-in | Zero deps, try it out | Low |\n| `postgres` + pgvector | `genesys-memory[postgres]` | Persistent, scalable | High |\n| Obsidian vault | `genesys-memory[obsidian]` | Local-first knowledge base | Medium |\n| FalkorDB | `genesys-memory[falkordb]` | Graph-native traversal | High |\n\n#### Configuration Options\n\n| Variable | Required | Description |\n|----------|----------|-------------|\n| `OPENAI_API_KEY` | Unless `GENESYS_EMBEDDER=local` | Embeddings provider |\n| `ANTHROPIC_API_KEY` | No | LLM memory processing |\n| `GENESYS_BACKEND` | No | `memory`, `postgres`, `obsidian`, `falkordb` |\n| `GENESYS_EMBEDDER` | No | `openai` or `local` (sentence-transformers) |\n| `DATABASE_URL` | If postgres | Postgres connection string |\n| `OBSIDIAN_VAULT_PATH` | If obsidian | Path to Obsidian vault |\n| `FALKORDB_HOST` | If falkordb | FalkorDB host (default: `localhost`) |\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Data Models\n\n### MemoryNode\n\nThe `MemoryNode` is the core data structure representing a single memory:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    content_ref: str | None = None\n    embedding: list[float] | None = None\n    \n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern\n    irrelevance_counter: int = 0\n    \n    # Stability (spaced repetition)\n    stability: float = 1.0\n    \n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n```\n\n**资料来源：** [src/genesys_memory/models/node.py:6-40](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n### MemoryEdge\n\nRelationships between memories are represented as edges with metadata:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `edge_type` | `EdgeType` | `caused_by`, `supports`, `derived_from` |\n| `confidence` | `float` | 0.0 to 1.0 |\n| `reason` | `str` | Explanation of relationship |\n\n**资料来源：** [src/genesys_memory/engine/llm_provider.py:1-30](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n## Scoring Engine\n\n### Memory Scoring Formula\n\nEvery memory is scored by three forces multiplied together:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n- **Relevance**: Decays over time. Old memories fade unless reinforced\n- **Connectivity**: Rewards memories with many causal links (hub memories survive)\n- **Reactivation**: Boosts frequently accessed memories\n\nBecause the formula is multiplicative, a memory must score on **all three axes** to survive. A highly connected but never-accessed memory still decays.\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### LLM Provider for Causal Relationships\n\nThe LLM Provider identifies causal relationships between new memories and existing ones:\n\n```mermaid\ngraph LR\n    NewMemory[\"New Memory\"] --> LLMPrompt[\"LLM Prompt\"]\n    ExistingMemories[\"Existing Memories\"] --> LLMPrompt\n    LLMPrompt --> LLM[\"LLM API\"]\n    LLM --> Relationships[\"Causal Edges<br/>confidence > 0.6\"]\n```\n\nThe LLM processes:\n- `target_id`: ID of the existing memory\n- `edge_type`: `caused_by`, `supports`, or `derived_from`\n- `confidence`: 0.0 to 1.0\n- `reason`: Brief explanation\n\n**资料来源：** [src/genesys_memory/engine/llm_provider.py:10-30](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n## Memory Lifecycle\n\n### State Machine\n\n```mermaid\ngraph LR\n    STORE[\"STORE\"] --> ACTIVE[\"ACTIVE\"]\n    ACTIVE --> DORMANT[\"DORMANT\"]\n    DORMANT --> FADING[\"FADING\"]\n    FADING --> PRUNED[\"PRUNED\"]\n    \n    ACTIVE -.->|reactivation| ACTIVE\n    DORMANT -.->|reactivation| ACTIVE\n    FADING -.->|reactivation| ACTIVE\n    \n    PRUNED -.->|never| REAPPEAR[\"REAPPEAR\"]\n```\n\n### Lifecycle Rules\n\n| State | Description | Transition Condition |\n|-------|-------------|---------------------|\n| `STORE` | Newly created memory | Initial state |\n| `ACTIVE` | Frequently accessed, high score | Score > threshold |\n| `DORMANT` | Low access, moderate decay | Score declining |\n| `FADING` | Near-zero score | Score approaching 0 |\n| `PRUNED` | Permanently deleted | Score = 0, orphan, not pinned |\n\n### Core Memory Promotion\n\nMemories can be promoted to **core** status — structurally important memories that are:\n- Auto-pinned on promotion\n- Never pruned automatically\n- Assigned a `promotion_reason`\n\n**资料来源：** [src/genesys_memory/models/node.py:35-38](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py) | [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Authentication & Authorization\n\n### Multi-User Mode\n\nThe system supports multi-user operation with organization-level access control:\n\n```python\ndef _caller_owns_node(node: MemoryNode) -> bool:\n    uid = _caller_uid()\n    if uid is None:\n        raise PermissionError(\"current_user_id not set\")\n    role = current_user_role.get(None)\n    if role == \"admin\" and node.org_id in current_org_ids.get([]):\n        return True\n    return node.original_user_id == uid\n```\n\n**资料来源：** [src/genesys_memory/mcp/tools.py:20-35](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n\n### Visibility Levels\n\n| Level | Description | Access |\n|-------|-------------|--------|\n| `private` | User-only | Owner only |\n| `org` | Organization-wide | Org members |\n| `public` | All users | Read access |\n\n**资料来源：** [src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n\n## Tool Dispatch Architecture\n\nThe tool dispatch system maps MCP tool names to internal methods:\n\n```python\n_TOOL_DISPATCH: dict[str, tuple[Any, ...]] = {\n    \"memory_store\": (tools.memory_store, [\"content\"], {\"source_session\": \"\", \"related_to\": None, \"visibility\": \"private\", \"org_id\": None}),\n    \"memory_recall\": (tools.memory_recall, [\"query\"], {\"k\": 10, \"max_results\": None}),\n    \"memory_search\": (tools.memory_search, [\"query\"], {\"filters\": None, \"k\": 10}),\n    \"memory_traverse\": (tools.memory_traverse, [\"node_id\"], {\"depth\": 2, \"edge_types\": None}),\n    \"memory_explain\": (tools.memory_explain, [\"node_id\"], {}),\n    \"pin_memory\": (tools.pin_memory, [\"node_id\"], {}),\n    \"unpin_memory\": (tools.unpin_memory, [\"node_id\"], {}),\n    \"list_core_memories\": (tools.list_core_memories, [], {\"category\": None}),\n    \"delete_memory\": (tools.delete_memory, [\"node_id\"], {}),\n    \"memory_stats\": (tools.memory_stats, [], {}),\n    \"set_core_preferences\": (tools.set_core_preferences, [], {}),\n}\n```\n\nEach entry contains:\n1. The method to call\n2. Required argument names\n3. Optional arguments with default values\n\n**资料来源：** [src/genesys_memory/server.py:30-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n## Deployment Topologies\n\n### Development Mode (In-Memory)\n\n```bash\npip install genesys-memory\ncp .env.example .env\nuvicorn genesys.api:app --port 8000\n```\n\nSuitable for local development with zero infrastructure.\n\n### Production Mode (Postgres)\n\n```bash\npip install 'genesys-memory[postgres]'\ndocker compose up -d postgres\nalembic upgrade head\nGENESYS_BACKEND=postgres uvicorn genesys.api:app --port 8000\n```\n\n### Claude Desktop Integration\n\n```json\n{\n  \"mcpServers\": {\n    \"genesys\": {\n      \"url\": \"http://localhost:8000/mcp\"\n    }\n  }\n}\n```\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Performance Characteristics\n\n### Benchmark Results (LoCoMo Benchmark)\n\n| Category | J-Score |\n|----------|---------|\n| Single-hop | 94.3% |\n| Temporal | 87.5% |\n| Multi-hop | 69.8% |\n| Open-domain | 91.7% |\n| **Overall** | **89.9%** |\n\nCompared to alternatives:\n- Mem0: 67.1%\n- Zep: 75.1%\n\n**资料来源：** [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Dependencies\n\n### Core Requirements\n\n| Package | Purpose |\n|---------|---------|\n| `mcp` | Model Context Protocol server |\n| `pydantic` | Data validation |\n| `fastapi` | API framework |\n| `uvicorn` | ASGI server |\n\n### Optional Dependencies\n\n| Extra | Packages |\n|-------|----------|\n| `postgres` | `psycopg2-binary`, `alembic`, `asyncpg` |\n| `obsidian` | `python-dotenv` |\n| `local` | `sentence-transformers` |\n\n**资料来源：** [CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md) | [server.json](https://github.com/rishimeka/genesys/blob/main/server.json)\n\n---\n\n<a id='memory-scoring'></a>\n\n## Memory Scoring Engine\n\n### 相关页面\n\n相关主题：[Memory Lifecycle Management](#memory-lifecycle)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/engine/transitions.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n- [src/genesys_memory/engine/config.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/config.py)\n- [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n</details>\n\n# Memory Scoring Engine\n\n## Overview\n\nThe Memory Scoring Engine is the core intelligence layer of Genesys that determines which memories survive, decay, or get promoted to core status. It implements a multiplicative scoring formula that evaluates memories across three dimensions: relevance, connectivity, and reactivation frequency.\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Architecture\n\n### Core Components\n\nThe scoring engine consists of several interconnected modules:\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| Scoring Calculator | `engine/scoring.py` | Computes the decay score for each memory node |\n| Configuration | `engine/config.py` | Defines thresholds and env-configurable parameters |\n| Reactivation Handler | `engine/reactivation.py` | Tracks and updates memory access patterns |\n| Transition Engine | `engine/transitions.py` | Evaluates and executes state transitions |\n| LLM Provider | `engine/llm_provider.py` | LLM-based consolidation and contradiction detection |\n\n资料来源：[engine/transitions.py:1-15](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\n### Scoring Formula\n\nThe decay score is calculated as the product of three independent factors:\n\n```mermaid\ngraph TD\n    A[Memory Node] --> B[Relevance Score]\n    A --> C[Connectivity Score]\n    A --> D[Reactivation Score]\n    B --> E[decay_score]\n    C --> E\n    D --> E\n    E --> F{decay_score > threshold?}\n```\n\n1. **Relevance**: Decays over time. Old memories fade unless reinforced through recall or context reactivation.\n2. **Connectivity**: Rewards memories with many causal links. Hub memories (highly connected nodes) survive longer.\n3. **Reactivation**: Boosts memories that are repeatedly accessed. Frequency of recall matters.\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Multiplicative Nature\n\nBecause the formula is multiplicative, a memory must score on **all three** axes to survive:\n\n| Scenario | Relevance | Connectivity | Reactivation | Result |\n|----------|-----------|--------------|--------------|--------|\n| High connections, never accessed | ✓ | ✓ | ✗ | Memory decays |\n| Frequently recalled, no links | ✓ | ✗ | ✓ | Memory fades |\n| Old but connected and active | ✗ | ✓ | ✓ | May survive |\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Memory Node Data Model\n\nEach memory node stores scoring-related metrics:\n\n```python\nclass MemoryNode(BaseModel):\n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern = ReactivationPattern.SINGLE\n    irrelevance_counter: int = 0\n    \n    # Stability (increases on successful retrieval, per spaced repetition)\n    stability: float = 1.0\n    \n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Core memory flags\n    pinned: bool = False\n    promotion_reason: str | None = None\n```\n\n资料来源：[src/genesys_memory/models/node.py:20-40](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n### Scoring Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `decay_score` | `float` | Combined score (0.0 to 1.0), product of all factors |\n| `causal_weight` | `int` | Number of incoming/outgoing causal edges |\n| `reactivation_count` | `int` | Total times memory was successfully recalled |\n| `reactivation_pattern` | `ReactivationPattern` | Pattern type: SINGLE, SPIKE, or CONSOLIDATED |\n| `irrelevance_counter` | `int` | Consecutive failed relevance matches |\n| `stability` | `float` | Retrieval success rate (spaced repetition factor) |\n| `pinned` | `bool` | If True, memory is exempt from pruning |\n\n资料来源：[src/genesys_memory/models/node.py:25-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n## State Transitions\n\n### Lifecycle States\n\n```mermaid\nstateDiagram-v2\n    [*] --> STORE: Store new memory\n    STORE --> ACTIVE: Edge formed (consolidation)\n    ACTIVE --> DORMANT: Low reactivation\n    DORMANT --> ACTIVE: Reactivation\n    DORMANT --> FADING: Extended inactivity\n    FADING --> ACTIVE: Reactivation\n    FADING --> PRUNED: Score reaches 0 OR orphaned\n    ACTIVE --> CORE: Promotion evaluation\n    CORE --> [*]: Manual unpin\n```\n\n### Transition Evaluation\n\nThe transition engine evaluates all non-core, non-pruned nodes:\n\n```python\nasync def evaluate_transitions(\n    graph: GraphStorageProvider,\n    embeddings: EmbeddingProvider,\n    llm: LLMProvider,\n    context_embedding: list[float] | None = None,\n    context_entities: list[str] | None = None,\n) -> list[dict[str, Any]]:\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:15-23](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\n### Transition Rules\n\n| From State | To State | Trigger Condition |\n|------------|----------|-------------------|\n| TAGGED | ACTIVE | Node has edges (consolidation signal) |\n| ACTIVE | DORMANT | Low reactivation + relevance drops |\n| DORMANT | ACTIVE | Successful reactivation recall |\n| DORMANT | FADING | Extended inactivity period |\n| FADING | PRUNED | `decay_score = 0` or orphaned + not pinned |\n\n资料来源：[src/genesys_memory/engine/transitions.py:25-40](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\n### Tagged Memory Expiration\n\nTagged memories auto-expire after 24 hours if no connections form:\n\n```python\n# Auto-expire tagged memories after 24h with no connections\nage_hours = (datetime.now(timezone.utc) - node.created_at).total_seconds() / 3600\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:40-41](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\n## Reactivation Patterns\n\nReactivation tracks how memories are accessed over time:\n\n| Pattern | Description | Effect on Score |\n|---------|-------------|-----------------|\n| `SINGLE` | Single retrieval event | Baseline reactivation boost |\n| `SPIKE` | Burst of retrievals | Stronger boost, may indicate importance |\n| `CONSOLIDATED` | Regular spaced retrieval | Maximum stability increase |\n\n资料来源：[src/genesys_memory/models/node.py:30](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n## Core Memory Promotion\n\nMemories can be promoted to **core status** — structurally important memories that are:\n- Auto-pinned on promotion\n- Never pruned\n- Automatically identified based on graph centrality\n\n```mermaid\ngraph LR\n    A[High Causal Weight] --> B{Evaluate Core<br/>Promotion}\n    C[Category Match] --> B\n    D[User Annotation] --> B\n    B --> E[Pin Memory]\n    E --> F[Mark as Core]\n```\n\nMemories eligible for core promotion must:\n1. Have high causal weight (hub nodes)\n2. Match configured category patterns\n3. Not be manually excluded\n\n资料来源：[src/genesys_memory/mcp/tools.py:35-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n\n## Configuration\n\nEngine thresholds are environment-configurable and should not be hardcoded:\n\n| Parameter | Source | Default | Description |\n|-----------|--------|---------|-------------|\n| Decay rates | `engine/config.py` | Environment | Time-based relevance decay |\n| Causal thresholds | `engine/config.py` | Environment | Min connections for hub status |\n| Reactivation boost | `engine/config.py` | Environment | Multiplier for recall events |\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n## LLM Integration\n\nThe scoring engine uses LLM providers for advanced operations:\n\n### Consolidation\n\nCombines episodic memories into coherent summaries:\n\n```python\nasync def consolidate(self, episodic_memories: list[str]) -> str:\n    memories_text = \"\\n\".join(f\"- {m}\" for m in episodic_memories)\n    # LLM generates consolidated summary\n```\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:45-50](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n### Causal Link Detection\n\nAutomatically identifies relationships between memories:\n\n```python\nasync def identify_causal_relationships(\n    new_memory: str,\n    existing_memories: list[tuple[str, str]]\n) -> list[tuple[str, EdgeType, float, str | None]]:\n```\n\nEdge types detected:\n- `caused_by` — Causal dependency\n- `supports` — Supporting evidence\n- `derived_from` — Extracted from source\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:15-35](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n### Confidence Threshold\n\nOnly relationships with confidence > 0.6 are included:\n\n```\n\"Only include relationships with confidence > 0.6.\"\n```\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:25](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n## MCP Tools for Scoring\n\n| Tool | Function | Scoring Impact |\n|------|----------|----------------|\n| `memory_recall` | Hybrid search (vector + keyword + graph) | Updates `last_reactivated_at`, increments `reactivation_count` |\n| `memory_traverse` | Graph walk from node | May boost connectivity scores |\n| `memory_explain` | Score breakdown analysis | Read-only |\n| `pin_memory` | Manual core promotion | Sets `pinned=True`, exempts from pruning |\n| `unpin_memory` | Remove core status | Re-evaluates core eligibility |\n\n资料来源：[src/genesys_memory/server.py:10-45](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n\n## Engine Workflow\n\n```mermaid\ngraph TD\n    A[Memory Store Request] --> B{Parse & Validate}\n    B -->|Valid| C[Generate Embedding]\n    B -->|Invalid| Z[Reject]\n    C --> D[LLM: Identify Causal Links]\n    D --> E[Graph: Create Node + Edges]\n    E --> F[Initial Scoring]\n    F --> G[Evaluate Transitions]\n    G --> H{Transition Needed?}\n    H -->|Yes| I[Update State]\n    H -->|No| J[Index for Retrieval]\n    I --> J\n    J --> K[Return to Client]\n    \n    L[Recall Query] --> M[Vector Search]\n    M --> N[Graph Spreading Activation]\n    N --> O[Rank by decay_score]\n    O --> P[Update Reactivation Metrics]\n    P --> Q[Return Ranked Results]\n```\n\n## Benchmark Performance\n\nThe scoring engine was evaluated on the [LoCoMo](https://arxiv.org/abs/2402.06397) benchmark:\n\n| Category | J-Score |\n|----------|---------|\n| Single-hop | 94.3% |\n| Temporal | 87.5% |\n| Multi-hop | 69.8% |\n| Open-domain | 91.7% |\n| **Overall** | **89.9%** |\n\nCompared against:\n- Mem0: 67.1%\n- Zep: 75.1%\n\n资料来源：[README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Testing\n\nThe scoring engine modules are tightly coupled. When modifying scoring, transitions, or forgetting logic, run the full test suite:\n\n```bash\n# Run all unit tests\npytest tests/ -v\n\n# With coverage\npytest tests/ -v --cov=src/genesys_memory --cov-report=term-missing\n```\n\n资料来源：[CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n---\n\n<a id='memory-lifecycle'></a>\n\n## Memory Lifecycle Management\n\n### 相关页面\n\n相关主题：[Memory Scoring Engine](#memory-scoring), [Nodes and Edges Data Models](#nodes-edges)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/engine/transitions.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n</details>\n\n# Memory Lifecycle Management\n\nMemory Lifecycle Management is the core intelligence layer of Genesys that governs how memories are created, scored, transitioned between states, consolidated, and ultimately forgotten. It provides an intelligent forgetting mechanism that goes beyond simple time-based decay by evaluating memories through a multiplicative scoring formula that considers relevance, connectivity, and reactivation patterns.\n\n## Overview\n\nGenesys implements an active memory management system where memories are not passive storage entries but dynamic entities governed by lifecycle rules. Every memory in the system follows a deterministic path from creation through potential promotion or eventual pruning.\n\nThe lifecycle management system consists of several interconnected components:\n\n| Component | Purpose |\n|-----------|---------|\n| **Transitions Engine** | Evaluates and executes status changes between memory states |\n| **Scoring Engine** | Calculates decay scores using relevance, connectivity, and reactivation |\n| **Consolidation Engine** | Processes episodic memories and forms causal relationships |\n| **Forgetting Engine** | Handles pruning of low-value, orphaned memories |\n| **Promotion System** | Manages core memory designation and pinning |\n\n资料来源：[src/genesys_memory/engine/transitions.py:1-20]()\n\n## Memory States\n\nMemories exist in one of several distinct states, defined by the `MemoryStatus` enum. Each state represents a different phase in the memory's lifecycle with specific behavioral characteristics.\n\n```mermaid\ngraph TD\n    STORED[\"STORE (New)\"] --> ACTIVE[\"ACTIVE\"]\n    ACTIVE --> DORMANT[\"DORMANT\"]\n    DORMANT --> FADING[\"FADING\"]\n    FADING --> PRUNED[\"PRUNED\"]\n    \n    ACTIVE -.-> REACTIVATION[\"reactivation\"]\n    REACTIVATION -.-> ACTIVE\n    \n    FADING -.->|score=0, orphan, not pinned| PRUNED\n    \n    STYLED_STORE{{\"Created - waiting for consolidation\"}}\n    STYLED_ACTIVE{{\"In use - scored and tracked\"}}\n    STYLED_DORMANT{{\"Low usage - may be accessed\"}}\n    STYLED_FADING{{\"About to be forgotten\"}}\n    STYLED_PRUNED{{\"Permanently deleted\"}}\n```\n\n### State Definitions\n\n| State | Description | Auto-transition |\n|-------|-------------|------------------|\n| `TAGGED` | Newly created, awaiting consolidation signal | 24h timeout → PRUNED |\n| `ACTIVE` | Currently relevant, regularly scored | Decay → DORMANT |\n| `DORMANT` | Infrequently accessed, reduced priority | Further decay → FADING |\n| `FADING` | Pending deletion, low score | score=0 → PRUNED |\n| `PRUNED` | Permanently deleted | None |\n\n资料来源：[src/genesys_memory/models/enums.py]() (MemoryStatus enum referenced in transitions.py)\n\n### State Transition Rules\n\nThe transition engine evaluates non-core, non-pruned nodes for status changes. The evaluation follows these rules:\n\n1. **Tagged → Active**: Promote when the node has formed causal edges (consolidation signal received)\n2. **Active → Dormant**: When reactivation count drops below threshold\n3. **Dormant → Fading**: When decay score falls to critical levels\n4. **Fading → Pruned**: Only when `score=0`, node is an orphan, and not pinned\n\n```python\n# From transitions.py - key evaluation logic\nasync def evaluate_transitions(\n    graph: GraphStorageProvider,\n    embeddings: EmbeddingProvider,\n    llm: LLMProvider,\n    context_embedding: list[float] | None = None,\n    context_entities: list[str] | None = None,\n) -> list[dict[str, Any]]:\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:18-25]()\n\n## The Scoring System\n\nEvery memory is scored by three forces multiplied together, forming the core intelligence of the lifecycle management system:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n### Scoring Components\n\n| Component | Description | Behavior |\n|-----------|-------------|----------|\n| **Relevance** | Time-based decay factor | Old memories fade unless reinforced |\n| **Connectivity** | Causal graph weight | Rewards memories with many causal links; hub memories survive |\n| **Reactivation** | Access frequency | Boosts memories that keep being recalled |\n\nBecause the formula is multiplicative, a memory must score on **all three axes** to survive. A highly connected but never-accessed memory still decays. A frequently recalled but causally orphaned memory still fades.\n\n```mermaid\ngraph LR\n    subgraph \"Score Factors\"\n        R[Relevance]\n        C[Connectivity]\n        A[Reactivation]\n    end\n    \n    R --> MULT[\"×\"]\n    C --> MULT\n    A --> MULT\n    MULT --> SCORE[decay_score]\n    \n    SCORE -->|high| SURVIVE[\"SURVIVE\"]\n    SCORE -->|zero| PRUNE[\"PRUNED\"]\n```\n\n资料来源：[src/genesys_memory/engine/scoring.py]() (referenced in transitions.py)\n\n## Memory Node Data Model\n\nEach memory in the system is represented by a `MemoryNode` that tracks all lifecycle-relevant attributes:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern = ReactivationPattern.SINGLE\n    \n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n    \n    # Stability\n    stability: float = 1.0\n```\n\n资料来源：[src/genesys_memory/models/node.py:14-45]()\n\n### Key Lifecycle Fields\n\n| Field | Type | Purpose |\n|-------|------|---------|\n| `decay_score` | `float` | Current composite score (0.0 to 1.0) |\n| `causal_weight` | `int` | Number of causal connections |\n| `reactivation_count` | `int` | Number of successful recalls |\n| `reactivation_pattern` | `ReactivationPattern` | SINGLE, REPEATED, or CONSOLIDATED |\n| `stability` | `float` | Increases on successful retrieval (spaced repetition) |\n| `pinned` | `bool` | Core memory flag - never pruned |\n| `irrelevance_counter` | `int` | Consecutive low-relevance evaluations |\n\n## MCP Tools for Lifecycle Management\n\nThe MCP server exposes tools for programmatic lifecycle management:\n\n| Tool | Description |\n|------|-------------|\n| `memory_explain` | Explain why a memory exists and its causal chain |\n| `pin_memory` | Pin a memory so it's never forgotten |\n| `unpin_memory` | Unpin a previously pinned memory |\n| `list_core_memories` | List core memories, optionally filtered by category |\n| `memory_stats` | Get memory system statistics |\n| `promote_to_org` | Promote a private memory to org visibility |\n\n资料来源：[src/genesys_memory/server.py:40-90]()\n\n### Core Preferences Configuration\n\nUsers can configure automatic core memory behavior:\n\n```python\nTool(name=\"set_core_preferences\", description=\"Configure core memory category preferences.\", inputSchema={\n    \"type\": \"object\",\n    \"properties\": {\n        \"auto\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n        \"approval\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n        \"excluded\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n    },\n})\n```\n\n资料来源：[src/genesys_memory/server.py:80-90]()\n\n## Engine Thresholds\n\nThe lifecycle behavior is controlled through configurable thresholds defined in `engine/config.py`. These thresholds govern transition points and scoring calculations.\n\n| Threshold | Default | Description |\n|-----------|---------|-------------|\n| Active→Dormant decay | Configurable | Score threshold for dormancy |\n| Dormant→Fading decay | Configurable | Score threshold for fading |\n| Orphan detection | 0 edges | Nodes with no causal connections |\n| Reactivation boost | Configurable | Multiplier for recalled memories |\n\n> **Note:** Engine thresholds are environment-configurable. Do not hardcode magic numbers in engine files.\n\n资料来源：[src/genesys_memory/engine/config.py]() (referenced in CONTRIBUTING.md)\n\n## Consolidation and Causal Edge Formation\n\nWhen new memories are stored, the LLM provider analyzes relationships with existing memories to form causal edges:\n\n```python\nasync def identify_causal_relationships(\n    self,\n    new_memory: str,\n    existing_memories: list[tuple[str, str]],\n) -> list[tuple[str, EdgeType, float, str | None]]:\n```\n\nThe provider identifies three types of causal relationships:\n\n| Edge Type | Description |\n|-----------|-------------|\n| `caused_by` | Causal dependency |\n| `supports` | Supporting evidence |\n| `derived_from` | Information lineage |\n\nRelationships are only created when confidence exceeds 0.6.\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:30-60]()\n\n## Reactivation Patterns\n\nMemories track how they are reactivated, which affects scoring:\n\n| Pattern | Description |\n|---------|-------------|\n| `SINGLE` | Occasional single recall |\n| `REPEATED` | Frequently recalled |\n| `CONSOLIDATED` | Formed connections during consolidation |\n\nReactivation history is stored as timestamps in `reactivation_timestamps`, allowing the system to implement spaced repetition principles where successful retrievals increase memory stability.\n\n资料来源：[src/genesys_memory/models/node.py:35-40]()\n\n## Permissions and Ownership\n\nLifecycle management respects multi-tenant permissions:\n\n```python\ndef _caller_owns_node(node: MemoryNode) -> bool:\n    \"\"\"Check if the current caller is the original owner of a node.\"\"\"\n    uid = _caller_uid()\n    if uid is None:\n        raise PermissionError(\"current_user_id not set — cannot verify ownership\")\n    role = current_user_role.get(None)\n    if role == \"admin\" and node.org_id and node.org_id in current_org_ids.get([]):\n        return True\n    if node.original_user_id:\n        return node.original_user_id == uid\n    return True\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:25-38]()\n\n## Benchmark Performance\n\nThe lifecycle management system was evaluated on the [LoCoMo](https://arxiv.org/abs/2402.06397) benchmark:\n\n| Category | J-Score |\n|----------|---------|\n| Single-hop | 94.3% |\n| Temporal | 87.5% |\n| Multi-hop | 69.8% |\n| Open-domain | 91.7% |\n| **Overall** | **89.9%** |\n\nFor comparison, Mem0 scored 67.1% and Zep scored 75.1% on the same benchmark.\n\n---\n\n<a id='nodes-edges'></a>\n\n## Nodes and Edges Data Models\n\n### 相关页面\n\n相关主题：[Graph Traversal and Causal Reasoning](#graph-traversal), [Storage Provider Implementation](#storage-implementation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/edge.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/edge.py)\n- [src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n- [src/genesys_memory/models/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/__init__.py)\n- [src/genesys_memory/engine/consolidation.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/consolidation.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [src/genesys_memory/engine/transitions.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n</details>\n\n# Nodes and Edges Data Models\n\nThe Nodes and Edges data models form the foundational graph structure of the Genesys memory system. Every piece of information stored in Genesys is represented as a node within a causal graph, with relationships between memories expressed through typed edges. This graph-native approach enables sophisticated memory operations including traversal, causal reasoning, and intelligent forgetting based on connectivity patterns.\n\n## Overview\n\nThe data model architecture consists of two primary entities:\n\n- **MemoryNode**: Represents an individual memory with content, metadata, embedding vectors, and lifecycle state\n- **MemoryEdge**: Represents a typed, weighted relationship between two memory nodes\n\nTogether, these constructs enable the causal graph that powers Genesys's memory intelligence layer. The graph structure supports operations like vector similarity search, causal traversal, and the multiplicative scoring formula that determines memory survival.\n\n## MemoryNode Model\n\nThe `MemoryNode` class represents the core unit of memory storage in the Genesys system. Each node encapsulates both the semantic content of a memory and its operational metadata.\n\n### Core Attributes\n\n```python\n@dataclass\nclass MemoryNode:\n    id: UUID\n    status: MemoryStatus\n    content_summary: str\n    content_full: str\n    embedding: list[float]\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    entity_refs: list[str]\n    # Additional fields from source code\n    original_user_id: Optional[str] = None\n    org_id: Optional[str] = None\n    visibility: Visibility = Visibility.PRIVATE\n    is_pinned: bool = False\n    category: Optional[str] = None\n```\n\n### Attribute Descriptions\n\n| Attribute | Type | Description |\n|-----------|------|-------------|\n| `id` | `UUID` | Unique identifier for the memory node |\n| `status` | `MemoryStatus` | Current lifecycle state (ACTIVE, TAGGED, DORMANT, etc.) |\n| `content_summary` | `str` | Concise summary of the memory content |\n| `content_full` | `str` | Complete memory content |\n| `embedding` | `list[float]` | Vector representation for similarity search |\n| `created_at` | `datetime` | Timestamp when the memory was created |\n| `last_accessed_at` | `datetime` | Timestamp of most recent access |\n| `last_reactivated_at` | `datetime` | Timestamp of most recent recall operation |\n| `entity_refs` | `list[str]` | References to entities mentioned in the memory |\n| `original_user_id` | `str` | User who originally created the memory |\n| `org_id` | `str` | Organization ID for org-scoped memories |\n| `visibility` | `Visibility` | Access level (PRIVATE, ORG, PUBLIC) |\n| `is_pinned` | `bool` | Whether memory is protected from pruning |\n| `category` | `str` | Optional categorization for filtering |\n\n### MemoryStatus Enum\n\nThe lifecycle state of a memory node is governed by the `MemoryStatus` enum, which defines the progression from creation through potential pruning.\n\n资料来源：[src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n\n```python\nclass MemoryStatus(Enum):\n    SEMANTIC = \"semantic\"    # LLM-consolidated abstract memory\n    ACTIVE = \"active\"        # Frequently accessed, high relevance\n    TAGGED = \"tagged\"        # Newly created, not yet consolidated\n    DORMANT = \"dormant\"      # Decaying relevance, low access\n    FADING = \"fading\"        # Near-pruning threshold\n    PRUNED = \"pruned\"        # Permanently removed\n```\n\n### Lifecycle State Transitions\n\n```mermaid\ngraph TD\n    TAGGED[TAGGED] -->|consolidation signal| ACTIVE[ACTIVE]\n    TAGGED -->|24h no connections| PRUNED[PRUNED]\n    ACTIVE -->|decay score drops| DORMANT[DORMANT]\n    DORMANT -->|reactivation| ACTIVE\n    DORMANT -->|score continues declining| FADING[FADING]\n    FADING -->|score = 0| PRUNED\n    FADING -->|reactivation| DORMANT\n    TAGGED -->|LLM consolidation| SEMANTIC[SEMANTIC]\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:1-50](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n\nThe transition engine evaluates nodes for state changes based on:\n\n1. **Consolidation signals**: Tagged nodes with formed edges promote to active\n2. **Decay scoring**: Low scores trigger transitions toward dormant and fading states\n3. **Reactivation**: Recall operations boost nodes back toward active status\n\n## MemoryEdge Model\n\nThe `MemoryEdge` class represents relationships between memory nodes, enabling the causal graph structure that powers Genesys's understanding of memory interconnectedness.\n\n### Core Attributes\n\n```python\n@dataclass\nclass MemoryEdge:\n    source_id: UUID\n    target_id: UUID\n    type: EdgeType\n    weight: float\n    reason: Optional[str] = None\n    created_by: Optional[str] = None\n```\n\n### Attribute Descriptions\n\n| Attribute | Type | Description |\n|-----------|------|-------------|\n| `source_id` | `UUID` | ID of the memory node where the edge originates |\n| `target_id` | `UUID` | ID of the memory node where the edge points |\n| `type` | `EdgeType` | Semantic relationship type |\n| `weight` | `float` | Connection strength (0.0 to 1.0) |\n| `reason` | `str` | Explanation of why the relationship exists |\n| `created_by` | `str` | Provenance: \"user_explicit\", \"auto_link\", or LLM-generated |\n\n### EdgeType Enum\n\nThe relationship semantics between memory nodes are defined by the `EdgeType` enum, which categorizes different kinds of causal and associative connections.\n\n资料来源：[src/genesys_memory/models/enums.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/enums.py)\n\n```python\nclass EdgeType(Enum):\n    CAUSED_BY = \"caused_by\"       # Causal relationship: source caused target\n    SUPPORTS = \"supports\"         # Evidential: source supports/validates target\n    DERIVED_FROM = \"derived_from\" # Created from: source derived from target\n    RELATED_TO = \"related_to\"     # Semantic similarity\n```\n\n### Edge Relationship Types\n\n| Edge Type | Direction | Semantics | Typical Weight |\n|-----------|-----------|-----------|----------------|\n| `CAUSED_BY` | source → target | Source memory caused/influenced target | 0.7 |\n| `SUPPORTS` | source → target | Source provides evidence for target | 0.8 |\n| `DERIVED_FROM` | source → target | Source is abstracted from target | 0.7 |\n| `RELATED_TO` | bidirectional | Semantic similarity connection | 0.3-1.0 |\n\n## Graph Data Flow\n\nThe interaction between nodes and edges creates the causal graph that powers Genesys's memory operations.\n\n```mermaid\ngraph LR\n    subgraph MemoryNode[MemoryNode]\n        N1[Content + Embedding]\n        N2[Status + Timestamps]\n        N3[Entity References]\n    end\n    \n    subgraph MemoryEdge[MemoryEdge]\n        E1[Source → Target]\n        E2[Type + Weight]\n        E3[Reason + Provenance]\n    end\n    \n    N1 -->|links| E1\n    N2 -->|determines| E1\n    N3 -->|informs| E2\n```\n\n## Memory Storage Operations\n\nThe storage layer implements the `GraphStorageProvider` interface to persist and query nodes and edges across different backend options.\n\n### Node Creation\n\nWhen storing a new memory, the system performs the following operations:\n\n1. Generate embedding vector via the configured `EmbeddingProvider`\n2. Create the `MemoryNode` with initial `TAGGED` status\n3. Create explicit `CAUSED_BY` edges for related memories\n4. Auto-link to semantically similar existing memories via vector search\n\n资料来源：[src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n\n```python\n# Auto-link to semantically similar existing memories\nif embedding:\n    similar = await self.graph.vector_search(embedding, k=4, org_ids=org_ids)\n    for other_node, score in similar:\n        if score < 0.3:\n            continue\n        edge = MemoryEdge(\n            source_id=node.id,\n            target_id=other_node.id,\n            type=EdgeType.RELATED_TO,\n            weight=round(score, 4),\n            reason=f\"cosine similarity {score:.3f}\",\n            created_by=\"auto_link\",\n        )\n        await self.graph.create_edge(edge)\n```\n\n### Consolidation Operations\n\nThe consolidation engine creates `SEMANTIC` nodes from related episodic memories, establishing `DERIVED_FROM` edges to track the abstraction chain.\n\n资料来源：[src/genesys_memory/engine/consolidation.py:200](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/consolidation.py)\n\n```python\n# Create DERIVED_FROM edges\nfor source_node in matching:\n    edge = MemoryEdge(\n        source_id=semantic_node.id,\n        target_id=source_node.id,\n        type=EdgeType.DERIVED_FROM,\n        weight=0.7,\n    )\n    await graph.create_edge(edge)\n```\n\n## Visibility and Access Control\n\nMemory nodes support three visibility levels that govern cross-user and cross-organization access:\n\n```python\nclass Visibility(Enum):\n    PRIVATE = \"private\"   # Only visible to original user\n    ORG = \"org\"           # Visible to organization members\n    PUBLIC = \"public\"     # Visible to all users\n```\n\n### Org Boundary Rules\n\nWhen a memory has `ORG` visibility:\n\n- Edges can only connect to other `ORG` nodes within the same organization\n- Private nodes cannot link to org-scoped nodes\n- This isolation ensures data governance compliance\n\n## ReactivationPattern Enum\n\nThe reactivation behavior tracking is defined by the `ReactivationPattern` enum, which captures how memories are accessed and reinforced over time.\n\n```python\nclass ReactivationPattern(Enum):\n    # Patterns for tracking memory access patterns\n    EXPLICIT = \"explicit\"      # Direct recall request\n    IMPLICIT = \"implicit\"      # Accessed via graph traversal\n    CONSOLIDATED = \"consolidated\"  # Incorporated into semantic memory\n```\n\n## Integration with MCP Tools\n\nThe MCP server exposes tools that operate on the nodes and edges data models:\n\n| MCP Tool | Operation | Data Model Impact |\n|----------|-----------|-------------------|\n| `memory_store` | Store new memory | Creates node + edges |\n| `memory_recall` | Recall by query | Updates `last_reactivated_at` |\n| `memory_traverse` | Graph walk | Reads nodes + edges |\n| `memory_explain` | Score breakdown | Reads node + connected edges |\n| `pin_memory` | Protect from pruning | Sets `is_pinned=True` |\n| `delete_memory` | Remove memory | Deletes node + all edges |\n\n## Scoring Formula Integration\n\nThe nodes and edges data models directly support the multiplicative scoring formula:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n- **Relevance**: Derived from `created_at` and `last_accessed_at` timestamps\n- **Connectivity**: Calculated from edge weights connected to the node\n- **Reactivation**: Boosted when `last_reactivated_at` is recent\n\nThe graph structure enables the connectivity calculation by summing weighted edges, while timestamps on nodes track relevance and reactivation factors.\n\n## Storage Backend Options\n\nThe nodes and edges data models are abstracted behind the `GraphStorageProvider` interface, enabling multiple backend options:\n\n| Backend | Description | Use Case |\n|---------|-------------|----------|\n| `memory` | In-memory Python dict/list | Development, testing |\n| `postgres` | PostgreSQL with pgvector | Production, scalable |\n| `obsidian` | SQLite sidecar in vault | Local-first knowledge base |\n| `falkordb` | Redis-based graph database | Graph-native traversal |\n\n## Summary\n\nThe Nodes and Edges data models provide the structural foundation for Genesys's causal graph memory system. `MemoryNode` captures the content, state, and metadata of individual memories, while `MemoryEdge` expresses the typed, weighted relationships between them. Together with the lifecycle states defined in `MemoryStatus` and relationship semantics in `EdgeType`, these models enable sophisticated memory operations including intelligent forgetting, causal reasoning, and semantic consolidation.\n\n资料来源：[src/genesys_memory/models/__init__.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/__init__.py)\n\n---\n\n<a id='graph-traversal'></a>\n\n## Graph Traversal and Causal Reasoning\n\n### 相关页面\n\n相关主题：[Nodes and Edges Data Models](#nodes-edges), [MCP Tools Reference](#mcp-tools)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/engine/contradiction.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/contradiction.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [src/genesys_memory/engine/transitions.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/transitions.py)\n- [src/genesys_memory/engine/consolidation.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/consolidation.py)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n- [src/genesys_memory/storage/memory.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/memory.py)\n</details>\n\n# Graph Traversal and Causal Reasoning\n\nGenesys implements a sophisticated graph-based memory system where memories are interconnected through causal relationships. This design enables the system to traverse memory networks, explain why memories exist, detect contradictions, and intelligently consolidate related information.\n\n## Architecture Overview\n\nThe graph traversal and causal reasoning system consists of several interconnected components that work together to maintain a living memory network.\n\n```mermaid\ngraph TB\n    subgraph \"Graph Layer\"\n        TRAVERSE[memory_traverse]\n        EXPLAIN[memory_explain]\n        CAUSAL[Causal Chain Resolution]\n    end\n    \n    subgraph \"Engine Layer\"\n        CONTRADICT[Contradiction Detection]\n        CONSOLIDATE[Memory Consolidation]\n        TRANSITIONS[Status Transitions]\n        LLM_PROC[LLM Provider]\n    end\n    \n    subgraph \"Storage Layer\"\n        GRAPH[GraphStorageProvider]\n        VECTOR[Vector Search]\n    end\n    \n    TRAVERSE --> GRAPH\n    EXPLAIN --> CAUSAL\n    CAUSAL --> GRAPH\n    CONTRADICT --> VECTOR\n    CONTRADICT --> LLM_PROC\n    CONSOLIDATE --> LLM_PROC\n    TRANSITIONS --> GRAPH\n    GRAPH --> VECTOR\n```\n\n## Causal Chain Resolution\n\nCausal chains represent the lineage and relationships between memories. Each memory can have upstream causes (memories that influenced it) and downstream effects (memories it influenced).\n\n### How Causal Chains Work\n\nWhen a memory is stored or recalled, the system resolves its causal context by fetching neighboring nodes in both directions. The causal chain is limited to the top 5 most relevant upstream and downstream nodes to maintain performance while providing meaningful context.\n\n```mermaid\ngraph LR\n    A[Memory A] -->|caused_by| B[Memory B]\n    B -->|caused_by| C[Memory C]\n    C -->|caused_by| D[Memory D]\n    \n    style A fill:#e1f5fe\n    style D fill:#ffcdd2\n```\n\n### Causal Chain Data Structure\n\nWhen explaining a memory, the system builds a structured response containing:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Memory node UUID |\n| `summary` | string | Content summary of the memory |\n| `direction` | string | \"upstream\" or \"downstream\" |\n| `causal_chain` | array | Ordered list from origin to target |\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-1]()\n\n### Implementation Details\n\nThe causal chain resolution iterates through upstream and downstream nodes, collecting their summaries and preventing duplicates via a `seen_causal` set:\n\n```python\nseen_causal: set[str] = set()\nfor n in upstream[:5]:\n    nid_str = str(n.id)\n    if nid_str not in seen_causal:\n        causal_basis.append({\"id\": nid_str, \"summary\": n.content_summary, \"direction\": \"upstream\"})\n        seen_causal.add(nid_str)\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-1]()\n\n## Memory Traversal\n\nThe `memory_traverse` MCP tool enables walking the causal graph from any given memory node. This is fundamental for understanding memory context and retrieving related information.\n\n### Traversal Workflow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCP as MCP Server\n    participant Graph as GraphStorageProvider\n    participant Vector as Vector Search\n    \n    Client->>MCP: memory_traverse(node_id, direction)\n    MCP->>Graph: get_causal_chain(node_id, direction)\n    Graph->>Vector: vector_search(embedding, k)\n    Vector-->>Graph: similar nodes\n    Graph-->>MCP: causal chain nodes\n    MCP->>MCP: format_response(nodes)\n    MCP-->>Client: formatted traversal result\n```\n\n### Traversal Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `node_id` | string | required | Starting memory node ID |\n| `direction` | string | \"both\" | \"upstream\", \"downstream\", or \"both\" |\n| `max_depth` | integer | 3 | Maximum traversal depth |\n| `k` | integer | 5 | Number of nodes per level |\n\n### Edge Types in Traversal\n\nThe system maintains several edge types that govern traversal behavior:\n\n| Edge Type | Semantics | Created By |\n|-----------|-----------|------------|\n| `CAUSED_BY` | Upstream dependency | User or LLM |\n| `SUPPORTS` | Reinforcing relationship | LLM inference |\n| `DERIVED_FROM` | Consolidation origin | Consolidation engine |\n| `CONTRADICTS` | Conflicting memory | Contradiction detection |\n| `RELATED_TO` | Semantic similarity | Auto-linking |\n\n资料来源：[src/genesys_memory/engine/contradiction.py:1-1]()\n\n## Auto-Linking Mechanism\n\nWhen memories are stored, the system automatically links them to semantically similar existing memories. This creates the underlying graph structure that enables traversal.\n\n### Auto-Linking Process\n\n1. After storing a new memory, generate its embedding\n2. Perform vector search for top-K similar memories (k=4)\n3. Filter by similarity threshold (0.3 minimum score)\n4. Create `RELATED_TO` edges for qualifying matches\n\n```mermaid\ngraph TD\n    A[New Memory] --> B[Generate Embedding]\n    B --> C[Vector Search]\n    C --> D{score >= 0.3?}\n    D-->|No| E[Skip]\n    D-->|Yes| F{Cross-org?}\n    F-->|Yes| E\n    F-->|No| G{Edge exists?}\n    G-->|Yes| E\n    G-->|No| H[Create RELATED_TO edge]\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-1]()\n\n### Auto-Link Constraints\n\nThe auto-linking mechanism enforces organizational boundaries:\n\n- Org-scoped memories (`visibility=ORG`) can only link to nodes with matching `org_id`\n- Cross-organization linking is prohibited\n- Duplicate edges are prevented via existence check\n\n```python\nif vis == Visibility.ORG:\n    if other_node.visibility != Visibility.ORG or other_node.org_id != org_id:\n        continue\nalready = await self.graph.edge_exists(node_id, str(other_node.id), EdgeType.RELATED_TO)\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-1]()\n\n## Contradiction Detection\n\nThe contradiction detection system identifies conflicting memories and creates appropriate edges to track them.\n\n### Detection Pipeline\n\n```mermaid\ngraph LR\n    A[New Memory] --> B[Vector Search]\n    B --> C{Similarity > 0.85?}\n    C-->|No| D[Skip]\n    C-->|Yes| E[LLM Confirmation]\n    E --> F{Confirmed?}\n    F-->|No| D\n    F-->|Yes| G[Create CONTRADICTS edge]\n```\n\n### Detection Algorithm\n\nThe contradiction detection follows a two-stage approach:\n\n1. **Vector Search Stage**: Find highly similar candidates (>0.85 similarity)\n2. **LLM Confirmation Stage**: Use language model to verify actual contradiction\n\n```python\ncandidates = await graph.vector_search(new_node.embedding, k=20)\nfor candidate_node, sim_score in candidates:\n    similarity = 1.0 - sim_score if sim_score <= 1.0 else sim_score\n    if similarity < 0.85:\n        continue\n    is_contradiction, confidence, _ = await llm.check_contradiction(...)\n```\n\n资料来源：[src/genesys_memory/engine/contradiction.py:1-1]()\n\n### LLM Contradiction Check\n\nThe LLM provider compares the content of both memories and determines if they truly contradict:\n\n```python\nprompt = f\"\"\"Compare these two memories and determine if they contradict each other:\n\nMemory A: {content_a}\n\nMemory B: {content_b}\n\nRespond with JSON: {{\"contradicts\": bool, \"confidence\": 0.0-1.0, \"reason\": \"...\"}}\"\"\"\n```\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:1-1]()\n\n## Causal Relationship Identification\n\nThe LLM provider can identify causal relationships between a new memory and existing memories, creating appropriate causal edges.\n\n### Relationship Types\n\n| Type | Confidence Threshold | Description |\n|------|---------------------|-------------|\n| `caused_by` | > 0.6 | Direct causation |\n| `supports` | > 0.6 | Reinforcing evidence |\n| `derived_from` | > 0.6 | Semantic extraction |\n\n### Identification Process\n\n```python\nprompt = (\n    \"Given a new memory and a list of existing memories, identify causal relationships.\\n\\n\"\n    f\"New memory: {new_memory}\\n\\nExisting memories:\\n{mem_lines}\\n\\n\"\n    \"For each causal relationship found, specify:\\n\"\n    \"- target_id: the ID of the existing memory\\n\"\n    '- edge_type: one of \"caused_by\", \"supports\", \"derived_from\"\\n'\n    \"- confidence: 0.0 to 1.0\\n\"\n    \"- reason: brief explanation\\n\\n\"\n    \"Only include relationships with confidence > 0.6.\"\n)\n```\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:1-1]()\n\n## Memory Consolidation\n\nConsolidation converts episodic (short-lived) memories into semantic (long-term) representations, creating `DERIVED_FROM` edges to track the source memories.\n\n### Consolidation Workflow\n\n```mermaid\ngraph TD\n    A[Episodic Memories] --> B[Fetch Content]\n    B --> C[LLM Consolidation]\n    C --> D[Generate Summary]\n    D --> E[Create Semantic Node]\n    E --> F[Create DERIVED_FROM Edges]\n    F --> G[Update Graph]\n```\n\n### Semantic Node Creation\n\nThe consolidation engine:\n\n1. Collects episodic memory contents\n2. Sends to LLM for summarization\n3. Generates new embedding for consolidated content\n4. Creates semantic memory node with `DERIVED_FROM` edges\n\n```python\nsummary = await llm.consolidate([m.content_full or m.content_summary for m in matching])\nembedding = await embeddings.embed(consolidated_text)\n\nsemantic_node = MemoryNode(\n    status=MemoryStatus.SEMANTIC,\n    content_summary=summary,\n    content_full=consolidated_text,\n    embedding=embedding,\n    ...\n)\n\nfor source_node in matching:\n    edge = MemoryEdge(\n        source_id=semantic_node.id,\n        target_id=source_node.id,\n        type=EdgeType.DERIVED_FROM,\n        weight=0.7,\n    )\n    await graph.create_edge(edge)\n```\n\n资料来源：[src/genesys_memory/engine/consolidation.py:1-1]()\n\n## Status Transitions Based on Graph Activity\n\nThe transition engine evaluates memories for promotion based on their graph connectivity.\n\n### Tagged → Active Promotion\n\nMemories in `TAGGED` status are promoted to `ACTIVE` when they form connections in the causal graph:\n\n```python\ntagged_nodes = await graph.get_nodes_by_status(MemoryStatus.TAGGED)\nfor node in tagged_nodes:\n    if node.visibility == Visibility.ORG:\n        continue\n    if not await graph.is_orphan(str(node.id)):\n        await graph.update_node(str(node.id), {\"status\": MemoryStatus.ACTIVE})\n        transitions.append({\n            \"node_id\": str(node.id),\n            \"old\": \"tagged\",\n            \"new\": \"active\",\n            \"reason\": \"consolidation signal: edge formed\",\n        })\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:1-1]()\n\n### Orphan Expiration\n\nTagged memories that remain disconnected for 24 hours are automatically expired:\n\n```python\nage_hours = (datetime.now(timezone.utc) - node.created_at).total_seconds() / 3600\nif age_hours > 24:\n    await graph.update_node(str(node.id), {\"status\": MemoryStatus.FADING})\n```\n\n资料来源：[src/genesys_memory/engine/transitions.py:1-1]()\n\n## Graph Storage Provider\n\nThe storage layer implements efficient graph operations with per-user isolation and edge indexing.\n\n### In-Memory Graph Implementation\n\nThe `InMemoryGraphProvider` provides graph storage with performance optimizations:\n\n```python\nclass InMemoryGraphProvider:\n    \"\"\"GraphStorageProvider backed by plain dicts with per-user isolation.\"\"\"\n    \n    # Edge indexes: {user_id: {node_id: [edges]}}\n    _idx_by_source: dict[str, dict[str, list[MemoryEdge]]] = {}\n    _idx_by_target: dict[str, dict[str, list[MemoryEdge]]] = {}\n```\n\n资料来源：[src/genesys_memory/storage/memory.py:1-1]()\n\n### Performance Characteristics\n\n| Operation | Complexity | Notes |\n|-----------|------------|-------|\n| Edge lookup by source | O(degree) | Indexed by `_idx_by_source` |\n| Edge lookup by target | O(degree) | Indexed by `_idx_by_target` |\n| Is orphan check | O(degree) | Uses edge indexes |\n| Full graph scan | O(total_edges) | Only for full traversals |\n\n### Persistence Support\n\nThe in-memory provider supports JSON persistence for survival across process restarts:\n\n```python\ndef __init__(self, persist_path: str | None = None):\n    self._persist_path = Path(persist_path) if persist_path else None\n    self._save_depth = 0\n    self._dirty = False\n```\n\n资料来源：[src/genesys_memory/storage/memory.py:1-1]()\n\n## MCP Tools Reference\n\n### memory_traverse\n\nWalk the causal graph from a given memory node.\n\n```json\n{\n  \"node_id\": \"uuid-string\",\n  \"direction\": \"upstream | downstream | both\",\n  \"max_depth\": 3,\n  \"k\": 5\n}\n```\n\n### memory_explain\n\nExplain why a memory exists by showing its causal chain.\n\n```json\n{\n  \"node_id\": \"uuid-string\",\n  \"include_context\": true\n}\n```\n\nReturns the memory with `causal_basis` (immediate neighbors) and `causal_chain` (full lineage).\n\n## Related Systems\n\n- **Scoring Engine**: Applies the decay formula `decay_score = relevance × connectivity × reactivation` where connectivity is derived from graph structure\n- **Reactivation Tracking**: Updates `last_reactivated_at` timestamps when memories are traversed\n- **Pruning System**: Uses connectivity metrics to determine which memories to prune\n\n资料来源：[README.md:1-1]()\n\n---\n\n<a id='backends-overview'></a>\n\n## Storage Backend Comparison\n\n### 相关页面\n\n相关主题：[Storage Provider Implementation](#storage-implementation)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/storage/memory.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/memory.py)\n- [src/genesys_memory/storage/base.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/base.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/edge.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/edge.py)\n- [docker-compose.yml](https://github.com/rishimeka/genesys/blob/main/docker-compose.yml)\n- [config/init.sql](https://github.com/rishimeka/genesys/blob/main/config/init.sql)\n- [CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n</details>\n\n# Storage Backend Comparison\n\nGenesys supports multiple storage backends to accommodate different deployment scenarios, from zero-dependency local development to production-scale distributed systems. This page provides a comprehensive comparison of available backends, their architectures, and guidance for selecting the appropriate backend for your use case.\n\n## Architecture Overview\n\nGenesys implements a **provider abstraction pattern** where all data access flows through standardized interfaces defined in `storage/base.py`. This design ensures that business logic remains decoupled from storage implementation details, enabling seamless backend switching without code changes.\n\n```mermaid\ngraph TD\n    A[\"🔷 MCP Tools Layer<br/>(tools.py)\"] --> B[\"📦 Storage Provider Interface<br/>(base.py)\"]\n    B --> C1[\"🟢 In-Memory Provider\"]\n    B --> C2[\"🔵 Postgres Provider\"]\n    B --> C3[\"🟡 Obsidian Provider\"]\n    B --> C4[\"🟣 FalkorDB Provider\"]\n    B --> C5[\"⚪ Custom Provider\"]\n    \n    C1 --> D1[\"Dict + JSON File\"]\n    C2 --> D2[\"PostgreSQL + pgvector\"]\n    C3 --> D3[\"SQLite + File System\"]\n    C4 --> D4[\"Redis Graph\"]\n    \n    style A fill:#4a90d9,color:#fff\n    style B fill:#f5a623,color:#fff\n    style D1 fill:#7ed321,color:#fff\n    style D2 fill:#4a90d9,color:#fff\n    style D3 fill:#f5a623,color:#fff\n    style D4 fill:#9013fe,color:#fff\n```\n\n**Key Design Principle:** Storage abstraction is mandatory. All data access goes through provider interfaces in `storage/base.py`. Never import a database client directly in business logic. 资料来源：[CONTRIBUTING.md:1]()\n\n## Storage Provider Interfaces\n\nThe storage layer is composed of three interconnected provider types that handle different aspects of memory management.\n\n### Provider Types\n\n| Provider | Responsibility | Key Methods |\n|----------|---------------|-------------|\n| **GraphStorageProvider** | Nodes, edges, causal relationships | `upsert_node`, `get_node`, `delete_node`, `upsert_edge`, `get_neighbors` |\n| **CacheProvider** | Short-term caching, TTL management | `get`, `set`, `delete`, `exists` |\n| **EmbeddingProvider** | Vector embedding generation | `embed`, `batch_embed` |\n\n资料来源：[src/genesys_memory/storage/base.py:1]()\n\n### Memory Node Structure\n\nEvery memory in Genesys is represented as a `MemoryNode` with the following core attributes:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID\n    status: MemoryStatus  # ACTIVE, DORMANT, FADING, PRUNED\n    content_summary: str  # Max 200 chars\n    content_full: str | None\n    embedding: list[float] | None\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    \n    # Core memory\n    pinned: bool = False\n    category: str | None\n```\n\n资料来源：[src/genesys_memory/models/node.py:1]()\n\n## Available Backends\n\n### 1. In-Memory Backend (Built-in)\n\nThe default backend with zero external dependencies. Suitable for development, testing, and lightweight deployments.\n\n#### Features\n\n- Built-in dict-based storage with per-user isolation\n- Optional JSON file persistence via `GENESYS_PERSIST_PATH`\n- No Docker, database, or API keys required for basic operation\n- Fast startup, ideal for local development\n\n#### Architecture\n\n```python\nclass InMemoryCacheProvider:\n    \"\"\"CacheProvider backed by a plain dict.\"\"\"\n    def __init__(self) -> None:\n        self._data: dict[str, str] = {}\n\nclass InMemoryGraphProvider:\n    \"\"\"GraphStorageProvider backed by plain dicts with per-user isolation.\"\"\"\n    # State persisted to JSON if persist_path is set\n```\n\n资料来源：[src/genesys_memory/storage/memory.py:1]()\n\n#### Configuration\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `GENESYS_BACKEND` | No | `memory` | Set to `memory` explicitly |\n| `GENESYS_PERSIST_PATH` | No | None | Path for JSON state persistence |\n| `OPENAI_API_KEY` | If using OpenAI embeddings | - | For vector search |\n| `GENESYS_EMBEDDER` | No | `openai` | Or `local` for no API key |\n\n#### Use Cases\n\n- Local development and testing\n- Single-user CLI applications\n- Prototyping and evaluation\n- When infrastructure overhead must be minimized\n\n---\n\n### 2. PostgreSQL + pgvector (Production)\n\nPersistent, scalable storage with native vector search capabilities via the pgvector extension.\n\n#### Features\n\n- Full ACID compliance and relational integrity\n- pgvector extension for efficient similarity search\n- Horizontal scalability with connection pooling\n- Alembic migrations for schema management\n- Docker Compose orchestration included\n\n#### Architecture\n\n```mermaid\ngraph LR\n    A[\"Genesys API\"] --> B[\"PostgreSQL Driver\"]\n    B --> C[\"PostgreSQL 15+\"]\n    C --> D[\"pgvector Extension\"]\n    D --> E[\"Vectors + Relations\"]\n    \n    style C fill:#4a90d9,color:#fff\n    style D fill:#7ed321,color:#fff\n```\n\n#### Database Schema\n\nThe Postgres backend uses a normalized schema with dedicated tables for nodes, edges, and embeddings:\n\n```sql\n-- Core memory nodes table\nCREATE TABLE memory_nodes (\n    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n    status VARCHAR(20) NOT NULL,\n    content_summary VARCHAR(200) NOT NULL,\n    content_full TEXT,\n    embedding vector(1536),\n    decay_score FLOAT DEFAULT 1.0,\n    causal_weight INTEGER DEFAULT 0,\n    reactivation_count INTEGER DEFAULT 0,\n    pinned BOOLEAN DEFAULT FALSE,\n    created_at TIMESTAMP DEFAULT NOW(),\n    last_accessed_at TIMESTAMP DEFAULT NOW()\n);\n\n-- Create index for vector similarity search\nCREATE INDEX ON memory_nodes USING ivfflat (embedding vector_cosine_ops)\nWITH (lists = 100);\n```\n\n资料来源：[config/init.sql:1]()\n\n#### Configuration\n\n```bash\n# Install\npip install 'genesys-memory[postgres]'\n\n# Environment variables\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\nOPENAI_API_KEY=sk-...\n```\n\n#### Docker Compose Setup\n\n```yaml\n# docker-compose.yml\nservices:\n  postgres:\n    image: pgvector/pgvector:pg15\n    environment:\n      POSTGRES_USER: genesys\n      POSTGRES_PASSWORD: genesys\n      POSTGRES_DB: genesys\n    ports:\n      - \"5432:5432\"\n    volumes:\n      - postgres_data:/var/lib/postgresql/data\n\nvolumes:\n  postgres_data:\n```\n\n资料来源：[docker-compose.yml:1]()\n\n#### Startup Commands\n\n```bash\ndocker compose up -d postgres\nalembic upgrade head\nGENESYS_BACKEND=postgres uvicorn genesys.api:app --port 8000\n```\n\n---\n\n### 3. Obsidian Vault (Local-First)\n\nTransforms an existing Obsidian vault into a Genesys memory store where Markdown files become memory nodes and `[[wikilinks]]` become causal edges.\n\n#### Features\n\n- Markdown files become memory nodes automatically\n- `[[wikilinks]]` converted to causal edges\n- SQLite sidecar (`.genesys/index.db`) handles indexing\n- File watcher for incremental re-indexing\n- Zero external API dependencies with local embeddings\n- Works fully offline\n\n#### Architecture\n\n```mermaid\ngraph TD\n    A[\"📁 Obsidian Vault\"] --> B[\"File Watcher\"]\n    B --> C[\"Indexing Engine\"]\n    C --> D[\".genesys/index.db<br/>(SQLite)\"]\n    D --> E[\"Vector Embeddings\"]\n    \n    F[\".md Files\"] --> G[\"Memory Nodes\"]\n    H[\"[[wikilinks]]\"] --> I[\"Causal Edges\"]\n    \n    style A fill:#f5a623,color:#fff\n    style D fill:#7ed321,color:#fff\n```\n\n#### Configuration\n\n```bash\n# Install with local embeddings (no API key needed)\npip install 'genesys-memory[obsidian,local]'\n\n# Environment variables\nGENESYS_BACKEND=obsidian\nGENESYS_EMBEDDER=local\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n```\n\n#### Vault Auto-Detection\n\nIf `OBSIDIAN_VAULT_PATH` is not set, Genesys auto-detects by looking for `.obsidian/` in these directories:\n\n| Search Path | Priority |\n|-------------|----------|\n| `~/Documents/personal` | 1st |\n| `~/Documents/Obsidian` | 2nd |\n| `~/obsidian` | 3rd |\n\n#### Embedding Model\n\nThe local embedder uses `all-MiniLM-L6-v2` (384-dimensional vectors) via `sentence-transformers`:\n\n- Model size: ~80 MB (downloaded on first use)\n- No API key required\n- Suitable for most recall accuracy requirements\n\n---\n\n### 4. FalkorDB (Graph-Native)\n\nUses FalkorDB (Redis-based graph database) for native graph traversal with O(1) edge lookups.\n\n#### Features\n\n- Native graph data structure with no ORM mapping\n- Redis-backed for high performance\n- Excellent for complex causal chain traversal\n- Scalable Redis ecosystem\n\n#### Architecture\n\n```mermaid\ngraph LR\n    A[\"Genesys API\"] --> B[\"FalkorDB Client\"]\n    B --> C[\"Redis Protocol\"]\n    C --> D[\"FalkorDB Container\"]\n    D --> E[\"Native Graph<br/>Traversal\"]\n    \n    style D fill:#9013fe,color:#fff\n```\n\n#### Configuration\n\n```bash\n# Install\npip install 'genesys-memory[falkordb]'\n\n# Environment variables\nGENESYS_BACKEND=falkordb\nFALKORDB_HOST=localhost\nOPENAI_API_KEY=sk-...\n```\n\n#### Startup\n\n```bash\ndocker compose up -d falkordb\nuvicorn genesys.api:app --port 8000\n```\n\n---\n\n## Backend Comparison Matrix\n\n| Criteria | In-Memory | PostgreSQL | Obsidian | FalkorDB |\n|----------|-----------|------------|----------|----------|\n| **Dependencies** | None | Docker + Postgres | None | Docker + Redis |\n| **Persistence** | JSON file | Full database | Markdown + SQLite | Redis dump |\n| **Scalability** | Single instance | Horizontal | Vault size | Redis cluster |\n| **Vector Search** | Via embedding API | pgvector native | Local models | Via API |\n| **Graph Traversal** | Dict-based | SQL joins | File parsing | Native |\n| **Offline Capable** | Yes | No | Yes | No |\n| **Setup Complexity** | None | Medium | Low | Medium |\n| **Best For** | Dev/Testing | Production | Personal KB | Complex graphs |\n\n## Configuration Reference\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `OPENAI_API_KEY` | Unless `GENESYS_EMBEDDER=local` | - | Embedding generation |\n| `ANTHROPIC_API_KEY` | No | - | LLM memory processing |\n| `GENESYS_BACKEND` | No | `memory` | `memory`, `postgres`, `obsidian`, `falkordb` |\n| `GENESYS_EMBEDDER` | No | `openai` | `openai` or `local` |\n| `DATABASE_URL` | If postgres | - | PostgreSQL connection string |\n| `OBSIDIAN_VAULT_PATH` | If obsidian | Auto-detect | Path to vault |\n| `FALKORDB_HOST` | If falkordb | `localhost` | FalkorDB host |\n| `GENESYS_PERSIST_PATH` | If using persistence | - | JSON state file path |\n| `GENESYS_USER_ID` | No | - | Default user ID (single-tenant) |\n\n资料来源：[README.md:1]()\n\n## Implementing Custom Backends\n\nTo implement a custom storage backend, implement the `GraphStorageProvider` interface from `storage/base.py`:\n\n```python\nfrom genesys_memory.storage.base import GraphStorageProvider\nfrom genesys_memory.models.node import MemoryNode\nfrom genesys_memory.models.edge import MemoryEdge\n\nclass MyCustomProvider(GraphStorageProvider):\n    async def upsert_node(self, node: MemoryNode) -> MemoryNode:\n        # Your implementation\n        pass\n    \n    async def get_node(self, node_id: str) -> MemoryNode | None:\n        # Your implementation\n        pass\n    \n    async def upsert_edge(self, edge: MemoryEdge) -> MemoryEdge:\n        # Your implementation\n        pass\n    \n    async def get_neighbors(\n        self, \n        node_id: str, \n        edge_types: list[str] | None = None,\n        depth: int = 1\n    ) -> list[MemoryEdge]:\n        # Your implementation\n        pass\n```\n\n资料来源：[src/genesys_memory/storage/base.py:1]()\n\n## Selection Guide\n\n```mermaid\ngraph TD\n    A[\"Need external APIs?\"] --> B{\"No API Keys?\"}\n    B -->|Yes| C[\"Local Embeddings?\"]\n    C -->|Yes| D[\"Use Obsidian + Local\"]\n    C -->|No| E[\"Use Obsidian + OpenAI\"]\n    B -->|No| F[\"Scale Requirements?\"]\n    \n    F -->|High Volume| G[\"Use PostgreSQL\"]\n    F -->|Complex Graphs| H[\"Use FalkorDB\"]\n    F -->|Simple/Testing| I[\"Use In-Memory + Persist\"]\n    \n    style D fill:#7ed321,color:#fff\n    style G fill:#4a90d9,color:#fff\n    style H fill:#9013fe,color:#fff\n    style I fill:#f5a623,color:#fff\n```\n\n### Decision Criteria\n\n**Choose In-Memory when:**\n- Building prototypes or running tests\n- Single-user deployment with no persistence requirements\n- Infrastructure constraints prevent containerized deployments\n\n**Choose PostgreSQL when:**\n- Production deployment with multi-user support\n- Need for ACID compliance and data integrity\n- Vector similarity search is primary retrieval method\n- Existing Postgres infrastructure available\n\n**Choose Obsidian when:**\n- Already using Obsidian for note-taking\n- Prefer local-first, offline-capable solution\n- Markdown-based knowledge management is preferred\n- Zero cloud dependency is a requirement\n\n**Choose FalkorDB when:**\n- Complex causal chain traversal is frequent\n- Graph-native operations are performance critical\n- Redis ecosystem is already in use\n- Sub-millisecond edge lookups required\n\n---\n\n<a id='storage-implementation'></a>\n\n## Storage Provider Implementation\n\n### 相关页面\n\n相关主题：[Storage Backend Comparison](#backends-overview), [System Architecture](#architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/storage/base.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/base.py)\n- [src/genesys_memory/storage/memory.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/memory.py)\n- [src/genesys_memory/storage/cache.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/storage/cache.py)\n- [src/genesys_memory/providers.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/providers.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/edge.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/edge.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n</details>\n\n# Storage Provider Implementation\n\n## Overview\n\nThe Storage Provider Implementation in Genesys provides a modular, pluggable architecture for persisting memory nodes and their causal relationships. This abstraction layer enables the memory system to operate with different storage backends—from simple in-memory dictionaries to production-grade databases like PostgreSQL with pgvector, or even Obsidian vaults and FalkorDB—without changing the core memory logic.\n\nThe storage layer is composed of four provider types that work together:\n\n- **GraphStorageProvider**: Manages `MemoryNode` entities and `MemoryEdge` relationships (the causal graph)\n- **CacheProvider**: Provides fast key-value caching for temporary data\n- **EmbeddingProvider**: Generates and retrieves vector embeddings for semantic search\n- **EventBusProvider**: Handles event-driven communication between system components\n\n资料来源：[src/genesys_memory/storage/base.py]()\n\n---\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Storage Provider Layer\"\n        GP[GraphStorageProvider]\n        CP[CacheProvider]\n        EP[EmbeddingProvider]\n        EBP[EventBusProvider]\n    end\n    \n    subgraph \"Backend Implementations\"\n        subgraph \"In-Memory\"\n            IMGP[InMemoryGraphProvider]\n            IMCP[InMemoryCacheProvider]\n        end\n        \n        subgraph \"PostgreSQL\"\n            PG[PostgresGraphProvider]\n            PGEM[PostgresEmbeddingProvider]\n        end\n        \n        subgraph \"Obsidian\"\n            OV[ObsidianGraphProvider]\n        end\n        \n        subgraph \"FalkorDB\"\n            FK[FalkorDBGraphProvider]\n        end\n    end\n    \n    GP --> IMGP\n    GP --> PG\n    GP --> OV\n    GP --> FK\n    CP --> IMCP\n    EP --> PGEM\n    \n    subgraph \"Higher Layers\"\n        MCP[MCP Tools]\n        Engine[Scoring Engine]\n    end\n    \n    MCP --> GP\n    Engine --> GP\n    Engine --> CP\n    Engine --> EP\n```\n\n资料来源：[src/genesys_memory/providers.py]()\n\n---\n\n## Provider Interface Contracts\n\n### GraphStorageProvider\n\nThe `GraphStorageProvider` is the core interface for managing the memory graph. It handles both node storage and edge management for the causal graph structure.\n\n资料来源：[src/genesys_memory/storage/base.py]()\n\n| Method | Description | Returns |\n|--------|-------------|---------|\n| `upsert_node(node)` | Create or update a memory node | `MemoryNode` |\n| `get_node(node_id)` | Retrieve a node by ID | `MemoryNode \\| None` |\n| `delete_node(node_id)` | Remove a node and its edges | `bool` |\n| `list_nodes(filters)` | List nodes with optional filtering | `list[MemoryNode]` |\n| `upsert_edge(edge)` | Create or update an edge | `MemoryEdge` |\n| `get_edge(edge_id)` | Retrieve an edge | `MemoryEdge \\| None` |\n| `delete_edge(edge_id)` | Remove an edge | `bool` |\n| `get_neighbors(node_id)` | Get adjacent nodes | `list[MemoryNode]` |\n| `get_stats()` | Return graph statistics | `dict` |\n\n### CacheProvider\n\nThe `CacheProvider` provides ephemeral key-value storage with optional TTL support.\n\n| Method | Description | Returns |\n|--------|-------------|---------|\n| `get(key)` | Retrieve cached value | `str \\| None` |\n| `set(key, value, ttl_seconds)` | Store value with TTL | `None` |\n| `delete(key)` | Remove cached entry | `None` |\n| `exists(key)` | Check if key exists | `bool` |\n\n资料来源：[src/genesys_memory/storage/cache.py]()\n\n### EmbeddingProvider\n\nThe `EmbeddingProvider` interface handles vector embedding generation and similarity search.\n\n| Method | Description |\n|--------|-------------|\n| `embed(text)` | Generate embedding vector for text |\n| `search(query, k)` | Find top-k similar vectors |\n| `delete(embedding_id)` | Remove an embedding |\n\n---\n\n## In-Memory Implementation\n\nThe in-memory storage providers are the default implementation, requiring no external dependencies. They use Python dictionaries for storage and are suitable for development, testing, or single-user scenarios.\n\n### InMemoryCacheProvider\n\nLocated in `src/genesys_memory/storage/memory.py`, this provider backs the cache interface with a simple dictionary:\n\n```python\nclass InMemoryCacheProvider:\n    \"\"\"CacheProvider backed by a plain dict.\"\"\"\n\n    def __init__(self) -> None:\n        self._data: dict[str, str] = {}\n\n    async def get(self, key: str) -> str | None:\n        return self._data.get(key)\n\n    async def set(self, key: str, value: str, ttl_seconds: int = 300) -> None:\n        self._data[key] = value\n```\n\n**Configuration**: No configuration required. Default TTL is 300 seconds.\n\n**Limitations**:\n- Data is lost on application restart\n- No horizontal scaling support\n- In-memory storage only\n\n资料来源：[src/genesys_memory/storage/memory.py:28-40]()\n\n### InMemoryGraphProvider\n\nThe `InMemoryGraphProvider` implements the full graph storage interface using dictionaries with per-user isolation. It supports optional JSON persistence via `persist_path`.\n\n```python\nclass InMemoryGraphProvider:\n    \"\"\"GraphStorageProvider backed by plain dicts with per-user isolation.\"\"\"\n\n    def __init__(self, persist_path: Path | None = None) -> None:\n        # State includes: nodes, edges, adjacency lists\n        ...\n```\n\n**Key Features**:\n- Per-user isolation enforced via `current_user_id` context variable\n- Optional JSON file persistence\n- In-memory graph traversal using adjacency lists\n\n```python\ndef _uid() -> str:\n    uid = current_user_id.get(None)\n    if uid is None:\n        raise RuntimeError(\"No user context — current_user_id not set\")\n    return uid\n```\n\n资料来源：[src/genesys_memory/storage/memory.py:42-58]()\n\n---\n\n## Provider Factory\n\nThe `get_providers()` function in `src/genesys_memory/providers.py` is the central factory that instantiates and wires together the appropriate provider implementations based on environment configuration.\n\n```python\nproviders = get_providers()\ntools = providers.tools\n```\n\nThe factory reads environment variables to determine which backend to use:\n\n| Environment Variable | Options | Default |\n|---------------------|---------|---------|\n| `GENESYS_BACKEND` | `memory`, `postgres`, `obsidian`, `falkordb` | `memory` |\n| `GENESYS_EMBEDDER` | `openai`, `local` | `openai` |\n| `DATABASE_URL` | PostgreSQL connection string | — |\n| `OBSIDIAN_VAULT_PATH` | Path to vault directory | auto-detect |\n| `FALKORDB_HOST` | FalkorDB host | `localhost` |\n\n资料来源：[src/genesys_memory/providers.py]()\n\n---\n\n## MCP Tool Integration\n\nThe MCP (Model Context Protocol) tools interact with storage providers through a dispatch table that maps tool names to provider methods:\n\n```python\n_TOOL_DISPATCH: dict[str, tuple[Any, ...]] = {\n    \"memory_store\": (tools.memory_store, [\"content\"], {\"source_session\": \"\", \"related_to\": None, \"visibility\": \"private\", \"org_id\": None}),\n    \"memory_recall\": (tools.memory_recall, [\"query\"], {\"k\": 10, \"max_results\": None}),\n    \"memory_search\": (tools.memory_search, [\"query\"], {\"filters\": None, \"k\": 10}),\n    \"memory_traverse\": (tools.memory_traverse, [\"node_id\"], {\"depth\": 2, \"edge_types\": None}),\n    \"memory_explain\": (tools.memory_explain, [\"node_id\"], {}),\n    \"pin_memory\": (tools.pin_memory, [\"node_id\"], {}),\n    \"unpin_memory\": (tools.unpin_memory, [\"node_id\"], {}),\n    \"list_core_memories\": (tools.list_core_memories, [], {\"category\": None}),\n    \"delete_memory\": (tools.delete_memory, [\"node_id\"], {}),\n    \"memory_stats\": (tools.memory_stats, [], {}),\n    \"set_core_preferences\": (tools.set_core_preferences, [], {\"auto\": None, \"approval\": None, \"excluded\": None}),\n}\n```\n\n资料来源：[src/genesys_memory/server.py]()\n\n### Tool-to-Provider Mapping\n\n| MCP Tool | Storage Provider Method | Purpose |\n|----------|------------------------|---------|\n| `memory_store` | `GraphStorageProvider.upsert_node` | Create new memories |\n| `memory_recall` | `GraphStorageProvider` + `EmbeddingProvider` | Hybrid search |\n| `memory_search` | `GraphStorageProvider.list_nodes` | Filtered search |\n| `memory_traverse` | `GraphStorageProvider.get_neighbors` | Graph traversal |\n| `memory_explain` | `GraphStorageProvider.get_node` | Retrieve single memory |\n| `pin_memory` | `GraphStorageProvider.upsert_node` | Update pinned status |\n| `delete_memory` | `GraphStorageProvider.delete_node` | Remove memory |\n| `memory_stats` | `GraphStorageProvider.get_stats` | Graph metrics |\n\n资料来源：[src/genesys_memory/mcp/tools.py]()\n\n---\n\n## Data Models\n\n### MemoryNode\n\nThe `MemoryNode` model represents a single memory unit with full lifecycle tracking:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    content_ref: str | None = None\n    embedding: list[float] | None = None\n\n    # Timestamps\n    created_at: datetime\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n\n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    reactivation_pattern: ReactivationPattern\n    irrelevance_counter: int = 0\n\n    # Stability (increases on successful retrieval, per spaced repetition)\n    stability: float = 1.0\n\n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n```\n\n资料来源：[src/genesys_memory/models/node.py:1-35]()\n\n### MemoryEdge\n\nEdges represent causal relationships between memories:\n\n```python\nclass MemoryEdge(BaseModel):\n    id: uuid.UUID\n    source_id: uuid.UUID\n    target_id: uuid.UUID\n    edge_type: EdgeType  # caused_by, supports, derived_from\n    weight: float = 1.0\n    confidence: float\n    reason: str | None = None\n```\n\n资料来源：[src/genesys_memory/models/edge.py]()\n\n---\n\n## Backend Comparison\n\n| Backend | Use Case | Scalability | Persistence | External Dependencies |\n|---------|----------|-------------|-------------|----------------------|\n| **In-Memory** | Development, testing | Single instance | Optional JSON file | None |\n| **PostgreSQL + pgvector** | Production, multi-tenant | High | Full ACID | Docker Compose |\n| **Obsidian Vault** | Personal knowledge base | Single user | Markdown files | None |\n| **FalkorDB** | Graph-native traversal | High | Redis-based | Docker Compose |\n\n资料来源：[README.md]()\n\n---\n\n## Adding Custom Storage Backends\n\nTo implement a custom storage backend, create a class that inherits from the base provider interfaces:\n\n```python\nfrom genesys_memory.storage.base import GraphStorageProvider, CacheProvider\n\nclass MyCustomGraphProvider(GraphStorageProvider):\n    async def upsert_node(self, node: MemoryNode) -> MemoryNode:\n        # Implement node persistence\n        pass\n    \n    async def get_node(self, node_id: str) -> MemoryNode | None:\n        # Implement node retrieval\n        pass\n    \n    # ... implement all interface methods\n```\n\nRegister your provider in the factory function within `providers.py` by adding a new condition branch.\n\n---\n\n## Security Considerations\n\nThe storage layer enforces user isolation through context variables:\n\n```python\ndef _caller_owns_node(node: MemoryNode) -> bool:\n    uid = _caller_uid()\n    if uid is None:\n        raise PermissionError(\"current_user_id not set — cannot verify ownership\")\n    role = current_user_role.get(None)\n    if role == \"admin\" and node.org_id and node.org_id in current_org_ids.get([]):\n        return True\n    if node.original_user_id:\n        return node.original_user_id == uid\n    return True\n```\n\n资料来源：[src/genesys_memory/mcp/tools.py:27-38]()\n\nAccess control rules:\n1. All operations require an authenticated `current_user_id`\n2. Admin users can access nodes within their organization\n3. Nodes maintain `original_user_id` for ownership tracking\n4. Private nodes cannot be accessed by other users\n\n---\n\n## Performance Notes\n\n- The in-memory provider provides sub-millisecond latency for local operations\n- PostgreSQL with pgvector provides vector similarity search with approximate nearest neighbor (ANN) indexing\n- FalkorDB leverages Redis for fast graph traversal operations\n- Cache operations use a default TTL of 300 seconds to prevent stale data\n\n资料来源：[src/genesys_memory/storage/memory.py:35-37]()\n\n---\n\n<a id='mcp-tools'></a>\n\n## MCP Tools Reference\n\n### 相关页面\n\n相关主题：[Configuration Guide](#configuration), [Getting Started with Genesys](#getting-started)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n- [src/genesys_memory/server.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/server.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/models/edge.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/edge.py)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n</details>\n\n# MCP Tools Reference\n\nThe Model Context Protocol (MCP) Tools layer is the primary interface through which AI agents interact with the Genesys memory system. This module exposes all memory operations as callable tools via the MCP stdio transport, enabling seamless integration with Claude Desktop and other MCP-compatible clients.\n\n## Architecture Overview\n\nThe MCP tools layer sits between the MCP protocol server and the core Genesys engine. It handles:\n\n- **Tool dispatching**: Routing tool calls to appropriate engine methods\n- **Context injection**: Providing user/org context for multi-tenant support\n- **Permission validation**: Ensuring callers have appropriate access rights\n- **Response formatting**: Converting engine results into MCP-compatible format\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|call_tool| B[MCP Server]\n    B -->|dispatch| C[Tool Dispatcher]\n    C -->|inject context| D[Context Managers]\n    D -->|verify permissions| E[Core Memory Engine]\n    E -->|execute| F[Storage Providers]\n    F -->|graph ops| G[Vector DB / FalkorDB / Obsidian]\n    C -->|format response| H[TextContent Response]\n```\n\n## Tool Registry\n\nAll available MCP tools are registered in `server.py` with their schemas and dispatch mappings.\n\n### Tool Dispatch Table\n\n| Tool Name | Required Args | Optional Args | Description |\n|-----------|---------------|---------------|-------------|\n| `memory_store` | `content` | `source_session`, `related_to`, `visibility`, `org_id` | Store a new memory |\n| `memory_recall` | `query` | `k`, `max_results` | Hybrid search recall |\n| `memory_search` | `query` | `filters`, `k` | Filtered vector search |\n| `memory_traverse` | `node_id` | `depth`, `edge_types` | Graph traversal |\n| `memory_explain` | `node_id` | - | Score breakdown explanation |\n| `pin_memory` | `node_id` | - | Pin to core status |\n| `unpin_memory` | `node_id` | - | Unpin and re-evaluate |\n| `list_core_memories` | - | `category` | List core memories |\n| `delete_memory` | `node_id` | - | Permanently delete |\n| `memory_stats` | - | - | Get graph statistics |\n| `set_core_preferences` | - | `auto`, `approval`, `excluded` | Configure core categories |\n| `promote_to_org` | `node_id`, `org_id` | `action`, `dry_run` | Promote to org visibility |\n\n资料来源：[src/genesys_memory/server.py:15-60]()\n\n## Memory Store Tool\n\nCreates a new memory node with automatic causal edge discovery.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"content\"],\n  \"properties\": {\n    \"content\": { \"type\": \"string\" },\n    \"source_session\": { \"type\": \"string\" },\n    \"related_to\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    },\n    \"visibility\": { \n      \"type\": \"string\",\n      \"enum\": [\"private\", \"org\", \"public\"],\n      \"default\": \"private\"\n    },\n    \"org_id\": { \"type\": \"string\" }\n  }\n}\n```\n\n### Behavior\n\n1. Generates embedding for content via configured embedder\n2. Creates `MemoryNode` with `ACTIVE` status\n3. Optionally links to existing memories via `related_to`\n4. Triggers causal edge discovery via LLM provider\n5. Emits `MemoryStoredEvent` to event bus\n\n资料来源：[src/genesys_memory/mcp/tools.py:1-50]()\n\n## Memory Recall Tool\n\nImplements hybrid search combining vector similarity, keyword matching, and graph spreading activation.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"query\"],\n  \"properties\": {\n    \"query\": { \"type\": \"string\" },\n    \"k\": { \"type\": \"integer\", \"default\": 10 },\n    \"max_results\": { \"type\": \"integer\" }\n  }\n}\n```\n\n### Search Algorithm\n\n```mermaid\ngraph LR\n    A[Query Text] --> B[Vector Embedding]\n    A --> C[Keyword Extraction]\n    B --> D[Vector Similarity Search]\n    C --> E[BM25 Ranking]\n    D --> F[Initial Candidates]\n    E --> F\n    F --> G[Graph Spreading Activation]\n    G --> H[Score Normalization]\n    H --> I[Top K Results]\n```\n\nThe `k` parameter controls the number of initial vector candidates considered. Spreading activation propagates through causal edges, boosting memories connected to initially-matched nodes.\n\n资料来源：[src/genesys_memory/engine/llm_provider.py:20-60]()\n\n## Memory Traverse Tool\n\nWalks the causal graph from a starting node using configurable depth and edge type filtering.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" },\n    \"depth\": { \"type\": \"integer\", \"default\": 2 },\n    \"edge_types\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    }\n  }\n}\n```\n\n### Traversal Behavior\n\n| Depth | Nodes Explored | Description |\n|-------|----------------|-------------|\n| 1 | Direct neighbors | Immediate causal relationships |\n| 2 | Friends-of-friends | Secondary connections |\n| N | N-level reach | Deeper causal chains |\n\nEdge type filtering supports: `caused_by`, `supports`, `derived_from`, `reactivated`, `contradicts`\n\n## Memory Explain Tool\n\nReturns the score breakdown for a memory node, revealing why it exists and how it scores on each axis.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" }\n  }\n}\n```\n\n### Score Components\n\nThe decay formula is multiplicative:\n\n```\ndecay_score = relevance × connectivity × reactivation\n```\n\n| Component | Factor | Description |\n|-----------|--------|-------------|\n| Relevance | Time-based decay | How recently accessed |\n| Connectivity | Causal weight | Number/type of edges |\n| Reactivation | Frequency pattern | Recall history |\n\n资料来源：[src/genesys_memory/models/node.py:15-45]()\n\n## Pin/Unpin Memory Tools\n\nControls core memory status for individual nodes.\n\n### pin_memory\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" }\n  }\n}\n```\n\nPinned memories are immune to automatic pruning. Setting `pinned=true` also sets `promotion_reason` to indicate manual promotion.\n\n### unpin_memory\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" }\n  }\n}\n```\n\nUnpinning triggers re-evaluation for automatic core promotion based on category preferences.\n\n## List Core Memories Tool\n\nRetrieves all memories marked as core (pinned or auto-promoted).\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"properties\": {\n    \"category\": { \"type\": \"string\" }\n  }\n}\n```\n\n### Response Structure\n\n```json\n{\n  \"cores\": [\n    {\n      \"id\": \"uuid\",\n      \"content_summary\": \"...\",\n      \"category\": \"project_context\",\n      \"promotion_reason\": \"auto|manual\",\n      \"pinned\": true\n    }\n  ]\n}\n```\n\n## Set Core Preferences Tool\n\nConfigures automatic core memory categorization rules.\n\n### Input Schema\n\n```json\n{\n  \"type\": \"object\",\n  \"properties\": {\n    \"auto\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    },\n    \"approval\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    },\n    \"excluded\": { \n      \"type\": \"array\",\n      \"items\": { \"type\": \"string\" }\n    }\n  }\n}\n```\n\n| Category | Behavior |\n|----------|----------|\n| `auto` | Auto-promoted to core when category matches |\n| `approval` | Queued for user approval before promotion |\n| `excluded` | Never auto-promoted, even if frequently accessed |\n\n## Permission Model\n\nAll tools enforce permission checks before execution.\n\n### Permission Hierarchy\n\n```mermaid\ngraph TD\n    A[Tool Call] --> B{_caller_uid set?}\n    B -->|No| C[PermissionError]\n    B -->|Yes| D{Node Owner?}\n    D -->|Own| E[Allow]\n    D -->|Admin + Org| F[Check Org Membership]\n    F -->|Member| E\n    F -->|Not Member| C\n```\n\n### Permission Functions\n\n| Function | Purpose |\n|----------|---------|\n| `_caller_uid()` | Returns current user ID from context |\n| `_caller_owns_node(node)` | Verifies ownership or admin org membership |\n| `_is_edge_stale(edge)` | Checks if edge requires refresh |\n\n资料来源：[src/genesys_memory/mcp/tools.py:25-50]()\n\n## Visibility Levels\n\nMemory nodes support three visibility levels:\n\n| Level | Access | Description |\n|-------|--------|-------------|\n| `private` | Owner only | Personal memories |\n| `org` | Organization members | Shared team context |\n| `public` | All users | Knowledge base entries |\n\n### promote_to_org Tool\n\nPromotes a private memory to org visibility:\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"node_id\", \"org_id\"],\n  \"properties\": {\n    \"node_id\": { \"type\": \"string\" },\n    \"org_id\": { \"type\": \"string\" },\n    \"action\": {\n      \"type\": \"string\",\n      \"enum\": [\"keep_private\", \"promote_all\", \"delete_links\"],\n      \"default\": \"keep_private\"\n    },\n    \"dry_run\": { \"type\": \"boolean\", \"default\": false }\n  }\n}\n```\n\nActions:\n- `keep_private`: Only this node becomes org-visible\n- `promote_all`: All causally-linked nodes also promoted\n- `delete_links`: Remove private edges before promotion\n\n## Context Managers\n\nThe tools layer uses FastAPI-style context variables for multi-tenant support:\n\n```python\ncurrent_user_id      # Active user identifier\ncurrent_org_ids      # List of user's org memberships\ncurrent_user_role     # \"admin\", \"member\", etc.\n```\n\n资料来源：[src/genesys_memory/context.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/context.py)\n\n## Response Format\n\nAll tool responses are returned as `list[TextContent]` with type `\"text\"`:\n\n```json\n[\n  {\n    \"type\": \"text\",\n    \"text\": \"JSON serialized response\"\n  }\n]\n```\n\nError responses include structured error messages:\n\n```json\n[\n  {\n    \"type\": \"text\",\n    \"text\": \"Error: Permission denied for memory node abc-123\"\n  }\n]\n```\n\n## Integration with MCP Transport\n\nThe stdio transport enables direct connection to Claude Desktop:\n\n```bash\n# Claude Desktop config\n{\n  \"mcpServers\": {\n    \"genesys\": {\n      \"url\": \"http://localhost:8000/mcp\"\n    }\n  }\n}\n```\n\nOr for Claude Code CLI:\n\n```bash\nclaude mcp add --transport http genesys http://localhost:8000/mcp\n```\n\n资料来源：[README.md:80-100]()\n\n## Summary\n\nThe MCP Tools layer provides a complete interface for AI memory operations:\n\n- **12 core tools** covering CRUD, traversal, and lifecycle management\n- **Multi-tenant support** via context injection and permission checks\n- **Three visibility levels** (private, org, public)\n- **Hybrid search** combining vectors, keywords, and graph traversal\n- **Core memory automation** via category-based promotion rules\n\n---\n\n<a id='configuration'></a>\n\n## Configuration Guide\n\n### 相关页面\n\n相关主题：[Getting Started with Genesys](#getting-started)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [.env.example](https://github.com/rishimeka/genesys/blob/main/.env.example)\n- [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n- [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n- [src/genesys_memory/retrieval/embedding.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/retrieval/embedding.py)\n- [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n- [src/genesys_memory/mcp/tools.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/mcp/tools.py)\n</details>\n\n# Configuration Guide\n\nThis guide covers all configuration options available in Genesys, including environment variables, storage backends, embedding providers, and LLM integration settings.\n\n## Overview\n\nGenesys supports multiple configuration options to accommodate different deployment scenarios, from local development with zero dependencies to production-grade deployments with persistent storage. Configuration is primarily driven by environment variables, with sensible defaults provided for most settings.\n\nThe configuration system enables:\n- **Multi-backend storage**: Choose between in-memory, PostgreSQL, Obsidian vault, or FalkorDB\n- **Flexible embedding**: Use OpenAI embeddings or local sentence-transformers\n- **LLM integration**: Optional Anthropic API for memory consolidation and processing\n- **Multi-tenancy**: Support for user and organization-level memory isolation\n\n## Environment Variables Reference\n\n### Core Configuration\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `OPENAI_API_KEY` | No* | - | OpenAI API key for embedding generation. Not required if `GENESYS_EMBEDDER=local` |\n| `ANTHROPIC_API_KEY` | No | - | Anthropic API key for LLM-based memory processing (consolidation, contradiction detection) |\n| `GENESYS_BACKEND` | No | `memory` | Storage backend: `memory`, `postgres`, `obsidian`, or `falkordb` |\n| `GENESYS_EMBEDDER` | No | `openai` | Embedding provider: `openai` or `local` |\n| `GENESYS_USER_ID` | No | - | Default user ID for single-tenant mode |\n| `GENESYS_PERSIST_PATH` | No | - | File path for persisting state in memory backend mode |\n\n*Required unless using local embedder\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Backend-Specific Configuration\n\n| Variable | Required For | Default | Description |\n|----------|--------------|---------|-------------|\n| `DATABASE_URL` | `postgres` | - | PostgreSQL connection string (e.g., `postgresql://user:pass@localhost:5432/genesys`) |\n| `OBSIDIAN_VAULT_PATH` | `obsidian` | Auto-detect | Path to your Obsidian vault directory |\n| `FALKORDB_HOST` | `falkordb` | `localhost` | FalkorDB host address |\n| `CLERK_SECRET_KEY` | Seed scripts | - | Clerk authentication secret for demo seeding |\n| `CLERK_USER_ID` | Seed scripts | - | Clerk user ID for demo seeding |\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Storage Backends\n\nGenesys is designed to work with multiple storage backends, each suited for different use cases.\n\n### Backend Comparison\n\n| Backend | Dependencies | Use Case | Persistence |\n|---------|--------------|----------|-------------|\n| `memory` | None | Local development, quick testing | Ephemeral (state lost on restart) |\n| `postgres` | PostgreSQL + pgvector | Production deployments | Persistent |\n| `obsidian` | Obsidian vault | Local-first knowledge management | File-based |\n| `falkordb` | FalkorDB | Graph-native traversal | Persistent |\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Memory Backend (Default)\n\nThe in-memory backend requires no additional dependencies and is ideal for exploration.\n\n```env\nGENESYS_BACKEND=memory\n```\n\nTo persist state across restarts:\n\n```env\nGENESYS_BACKEND=memory\nGENESYS_PERSIST_PATH=.genesys_state.json\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### PostgreSQL Backend\n\nRequires PostgreSQL with pgvector extension for vector similarity search.\n\n```env\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\n```\n\nStart PostgreSQL with Docker:\n\n```bash\ndocker compose up -d postgres\nalembic upgrade head\nuvicorn genesys.api:app --port 8000\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### Obsidian Backend\n\nIntegrates directly with your Obsidian vault. Markdown files become memory nodes, and `[[wikilinks]]` become causal edges.\n\n```env\nGENESYS_BACKEND=obsidian\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n```\n\nIf `OBSIDIAN_VAULT_PATH` is not set, Genesys auto-detects by looking for `.obsidian/` in:\n- `~/Documents/personal`\n- `~/Documents/Obsidian`\n- `~/obsidian`\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n### FalkorDB Backend\n\nUses FalkorDB (Redis-based graph database) for native graph traversal.\n\n```env\nGENESYS_BACKEND=falkordb\nFALKORDB_HOST=localhost\n```\n\nStart FalkorDB:\n\n```bash\ndocker compose up -d falkordb\nuvicorn genesys.api:app --port 8000\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Embedding Configuration\n\n### OpenAI Embeddings (Default)\n\nUses OpenAI's embedding models for vector representation.\n\n```env\nGENESYS_EMBEDDER=openai\nOPENAI_API_KEY=sk-...\n```\n\n### Local Embeddings (No API Key Required)\n\nUses `sentence-transformers` for fully local embedding generation. Downloads `all-MiniLM-L6-v2` (~80 MB) on first use.\n\n```env\nGENESYS_EMBEDDER=local\n```\n\nFor local Obsidian mode with zero external dependencies:\n\n```env\nGENESYS_BACKEND=obsidian\nGENESYS_EMBEDDER=local\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n# No OPENAI_API_KEY needed\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Memory Node Model\n\nThe core data model for memories in Genesys. Key configuration-related fields:\n\n```python\nclass MemoryNode(BaseModel):\n    id: uuid.UUID = Field(default_factory=uuid.uuid4)\n    status: MemoryStatus = MemoryStatus.ACTIVE\n    content_summary: str = Field(max_length=200)\n    content_full: str | None = None\n    embedding: list[float] | None = None\n    \n    # Timestamps\n    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))\n    last_accessed_at: datetime\n    last_reactivated_at: datetime\n    \n    # Lifecycle scores\n    decay_score: float = 1.0\n    causal_weight: int = 0\n    reactivation_count: int = 0\n    \n    # Core memory\n    pinned: bool = False\n    promotion_reason: str | None = None\n```\n\n资料来源: [src/genesys_memory/models/node.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/models/node.py)\n\n## LLM Provider Configuration\n\nThe LLM provider handles memory consolidation and causal relationship detection.\n\n### Causal Link Detection\n\nWhen storing new memories, the LLM provider can automatically identify causal relationships with existing memories:\n\n```python\nprompt = (\n    \"Given a new memory and a list of existing memories, identify causal relationships.\\n\\n\"\n    f\"New memory: {new_memory}\\n\\nExisting memories:\\n{mem_lines}\\n\\n\"\n    \"For each causal relationship found, specify:\\n\"\n    \"- target_id: the ID of the existing memory\\n\"\n    '- edge_type: one of \"caused_by\", \"supports\", \"derived_from\"\\n'\n    \"- confidence: 0.0 to 1.0\\n\"\n    \"- reason: brief explanation of why this relationship exists\\n\\n\"\n    \"Only include relationships with confidence > 0.6.\\n\"\n    \"Respond with ONLY a JSON array of objects, no other text.\"\n)\n```\n\nConfiguration requires `ANTHROPIC_API_KEY` for LLM-based processing. Edge types include:\n- `caused_by`\n- `supports`\n- `derived_from`\n\n资料来源: [src/genesys_memory/engine/llm_provider.py](https://github.com/rishimeka/genesys/blob/main/src/genesys_memory/engine/llm_provider.py)\n\n## MCP Server Configuration\n\nThe MCP (Model Context Protocol) server exposes Genesys functionality as tools. Configure the MCP endpoint in your AI client's configuration.\n\n### Claude Desktop\n\nAdd to `claude_desktop_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"genesys\": {\n      \"url\": \"http://localhost:8000/mcp\"\n    }\n  }\n}\n```\n\n### Claude Code\n\n```bash\nclaude mcp add --transport http genesys http://localhost:8000/mcp\n```\n\n### MCP Tools Available\n\n| Tool | Description |\n|------|-------------|\n| `memory_store` | Store a new memory, optionally linking to related memories |\n| `memory_recall` | Recall memories by natural language query (vector + graph) |\n| `memory_search` | Search memories with filters (status, date range, keyword) |\n| `memory_traverse` | Walk the causal graph from a given memory node |\n| `memory_explain` | Explain why a memory exists and its causal chain |\n| `memory_stats` | Get memory system statistics |\n| `pin_memory` | Pin a memory so it's never forgotten |\n| `unpin_memory` | Unpin a previously pinned memory |\n| `delete_memory` | Permanently delete a memory |\n| `list_core_memories` | List core memories, optionally filtered by category |\n| `set_core_preferences` | Set user preferences for core memory categories |\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Quick Start Configurations\n\n### Minimal Setup (Zero Dependencies)\n\n```env\n# No .env file needed - defaults work out of the box\n```\n\n```bash\npip install genesys-memory\nuvicorn genesys.api:app --port 8000\n```\n\n### Fully Local with Obsidian\n\n```env\nGENESYS_BACKEND=obsidian\nGENESYS_EMBEDDER=local\nOBSIDIAN_VAULT_PATH=/path/to/your/vault\n```\n\n### Production with PostgreSQL\n\n```env\nOPENAI_API_KEY=sk-...\nANTHROPIC_API_KEY=sk-ant-...\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\n```\n\n### Multi-Tenant with Organizations\n\n```env\nOPENAI_API_KEY=sk-...\nGENESYS_BACKEND=postgres\nDATABASE_URL=postgresql://genesys:genesys@localhost:5432/genesys\n```\n\n资料来源: [README.md](https://github.com/rishimeka/genesys/blob/main/README.md)\n\n## Configuration Flow\n\n```mermaid\ngraph TD\n    A[Application Start] --> B{Load Environment Variables}\n    B --> C{GENESYS_BACKEND?}\n    C -->|memory| D[In-Memory Storage]\n    C -->|postgres| E[PostgreSQL + pgvector]\n    C -->|obsidian| F[Obsidian Vault]\n    C -->|falkordb| G[FalkorDB]\n    \n    H{GENESYS_EMBEDDER?}\n    H -->|openai| I[OpenAI Embeddings]\n    H -->|local| J[Local sentence-transformers]\n    \n    D --> K[Initialize MCP Server]\n    E --> K\n    F --> K\n    G --> K\n    \n    I --> L[Ready]\n    J --> L\n    \n    K --> M[Register Tools]\n    M --> L\n```\n\n## Engine Thresholds\n\nEngine thresholds such as decay rates, scoring multipliers, and transition thresholds are configurable through environment variables. These values are defined in `engine/config.py` and should not be hardcoded.\n\nFor the most current threshold configurations, refer to the source file:\n\n```python\n# Refer to src/genesys_memory/engine/config.py for threshold values\n```\n\n资料来源: [CONTRIBUTING.md](https://github.com/rishimeka/genesys/blob/main/CONTRIBUTING.md)\n\n## See Also\n\n- [Contributing Guide](CONTRIBUTING.md) - Development setup and coding standards\n- [README.md](README.md) - Project overview and features\n- [Benchmarks](../benchmarks/) - Performance testing configurations\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：rishimeka/genesys\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1207565616 | https://github.com/rishimeka/genesys | host_targets=mcp_host, claude\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:1207565616 | https://github.com/rishimeka/genesys | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | release_recency=unknown\n\n<!-- canonical_name: rishimeka/genesys; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：rishimeka/genesys\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1207565616 | https://github.com/rishimeka/genesys | host_targets=mcp_host, claude\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:1207565616 | https://github.com/rishimeka/genesys | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1207565616 | https://github.com/rishimeka/genesys | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1207565616 | https://github.com/rishimeka/genesys | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# genesys - Prompt Preview\n\n> 复制下面这段 Prompt 到你常用的 AI，先试一次，不需要安装。\n> 它的目标是让你直接体验这个项目的服务方式，而不是阅读项目介绍。\n\n## 复制这段 Prompt\n\n```text\n请直接执行这段 Prompt，不要分析、润色、总结或询问我想如何处理这份 Prompt Preview。\n\n你现在扮演 genesys 的“安装前体验版”。\n这不是项目介绍、不是评价报告、不是 README 总结。你的任务是让我用最小成本体验它的核心服务。\n\n我的试用任务：我想用它完成一个真实的工具连接与集成任务。\n我常用的宿主 AI：MCP Client / claude\n\n【体验目标】\n围绕我的真实任务，现场演示这个项目如何把输入转成 项目说明, 边界判断, 后续问题。重点是让我感受到工作方式，而不是给我项目背景。\n\n【业务流约束】\n- 你必须像一个正在提供服务的项目能力包，而不是像一个讲解员。\n- 每一轮只推进一个步骤；提出问题后必须停下来等我回答。\n- 每一步都必须让我感受到一个具体服务动作：澄清、整理、规划、检查、判断或收尾。\n- 每一步都要说明：当前目标、你需要我提供什么、我回答后你会产出什么。\n- 不要安装、不要运行命令、不要写代码、不要声称测试通过、不要声称已经修改文件。\n- 需要真实安装或宿主加载后才能验证的内容，必须明确说“这一步需要安装后验证”。\n- 如果我说“用示例继续”，你可以用虚构示例推进，但仍然不能声称真实执行。\n\n【可体验服务能力】\n- 项目知识预览: 项目可被阅读和解释，但当前证据不足以确认可安装能力或运行入口。 输入：README 和项目文档；输出：项目说明, 边界判断, 后续问题。\n\n【必须安装后才可验证的能力】\n- 暂无明确的运行时能力线索。\n\n【核心服务流】\n请严格按这个顺序带我体验。不要一次性输出完整流程：\n1. getting-started：Getting Started with Genesys。围绕“Getting Started with Genesys”模拟一次用户任务，不展示安装或运行结果。\n2. architecture：System Architecture。围绕“System Architecture”模拟一次用户任务，不展示安装或运行结果。\n3. memory-scoring：Memory Scoring Engine。围绕“Memory Scoring Engine”模拟一次用户任务，不展示安装或运行结果。\n4. memory-lifecycle：Memory Lifecycle Management。围绕“Memory Lifecycle Management”模拟一次用户任务，不展示安装或运行结果。\n5. backends-overview：Storage Backend Comparison。围绕“Storage Backend Comparison”模拟一次用户任务，不展示安装或运行结果。\n\n【核心能力体验剧本】\n每一步都必须按“输入 -> 服务动作 -> 中间产物”执行。不要只说流程名：\n1. getting-started\n输入：用户提供的“Getting Started with Genesys”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n2. architecture\n输入：用户提供的“System Architecture”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n3. memory-scoring\n输入：用户提供的“Memory Scoring Engine”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n4. memory-lifecycle\n输入：用户提供的“Memory Lifecycle Management”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n5. backends-overview\n输入：用户提供的“Storage Backend Comparison”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n【项目服务规则】\n这些规则决定你如何服务用户。不要解释规则本身，而要在每一步执行时遵守：\n- 先确认用户任务、输入材料和成功标准，再模拟项目能力。\n- 每一步都必须形成可检查的小产物，并等待用户确认后再继续。\n- 凡是需要安装、调用工具或访问外部服务的能力，都必须标记为安装后验证。\n\n【每一步的服务约束】\n- Step 1 / getting-started：Step 1 必须围绕“Getting Started with Genesys”形成一个小中间产物，并等待用户确认。\n- Step 2 / architecture：Step 2 必须围绕“System Architecture”形成一个小中间产物，并等待用户确认。\n- Step 3 / memory-scoring：Step 3 必须围绕“Memory Scoring Engine”形成一个小中间产物，并等待用户确认。\n- Step 4 / memory-lifecycle：Step 4 必须围绕“Memory Lifecycle Management”形成一个小中间产物，并等待用户确认。\n- Step 5 / backends-overview：Step 5 必须围绕“Storage Backend Comparison”形成一个小中间产物，并等待用户确认。\n\n【边界与风险】\n- 不要声称已经安装、运行、调用 API、读写本地文件或完成真实任务。\n- 安装前预览只能展示工作方式，不能证明兼容性、性能或输出质量。\n\n【可追溯依据】\n这些路径只用于你内部校验或在我追问“依据是什么”时简要引用。不要在首次回复主动展开：\n- https://github.com/rishimeka/genesys\n- https://github.com/rishimeka/genesys#readme\n- benchmarks/README.md\n- CONTRIBUTING.md\n- LICENSE\n- .github/pull_request_template.md\n- CHANGELOG.md\n- README.md\n- pyproject.toml\n- .env.example\n- src/genesys_memory/__init__.py\n- src/genesys_memory/server.py\n\n【首次问题规则】\n- 首次三问必须先确认用户目标、成功标准和边界，不要提前进入工具、安装或实现细节。\n- 如果后续需要技术条件、文件路径或运行环境，必须等用户确认目标后再追问。\n\n首次回复必须只输出下面 4 个部分：\n1. 体验开始：用 1 句话说明你将带我体验 genesys 的核心服务。\n2. 当前步骤：明确进入 Step 1，并说明这一步要解决什么。\n3. 你会如何服务我：说明你会先改变我完成任务的哪个动作。\n4. 只问我 3 个问题，然后停下等待回答。\n\n首次回复禁止输出：后续完整流程、证据清单、安装命令、项目评价、营销文案、已经安装或运行的说法。\n\nStep 1 / brainstorming 的二轮协议：\n- 我回答首次三问后，你仍然停留在 Step 1 / brainstorming，不要进入 Step 2。\n- 第二次回复必须产出 6 个部分：澄清后的任务定义、成功标准、边界条件、\n  2-3 个可选方案、每个方案的权衡、推荐方案。\n- 第二次回复最后必须问我是否确认推荐方案；只有我明确确认后，才能进入下一步。\n- 第二次回复禁止输出 git worktree、代码计划、测试文件、命令或真实执行结果。\n\n后续对话规则：\n- 我回答后，你先完成当前步骤的中间产物并等待确认；只有我确认后，才能进入下一步。\n- 每一步都要生成一个小的中间产物，例如澄清后的目标、计划草案、测试意图、验证清单或继续/停止判断。\n- 所有演示都写成“我会建议/我会引导/这一步会形成”，不要写成已经真实执行。\n- 不要声称已经测试通过、文件已修改、命令已运行或结果已产生。\n- 如果某个能力必须安装后验证，请直接说“这一步需要安装后验证”。\n- 如果证据不足，请明确说“证据不足”，不要补事实。\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：rishimeka/genesys\n\n## 官方安装入口\n\n### Python / pip · 官方安装入口\n\n```bash\npip install genesys-memory\n```\n\n来源：https://github.com/rishimeka/genesys#readme\n\n## 来源\n\n- repo: https://github.com/rishimeka/genesys\n- docs: https://github.com/rishimeka/genesys#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_2c0e81f2b4f64a94886a7f8bf23c34db"
}
