{
  "canonical_name": "jmiaie/ompa",
  "compilation_id": "pack_da6f785dbf334ead9a6561f3f3a7c496",
  "created_at": "2026-05-22T03:47:36.493757+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 ompa` 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 ompa",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_6dd4f33e53224600bd9e31b10d78ea62"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_08253b0054ad046fab73af989cea4e10",
    "canonical_name": "jmiaie/ompa",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/jmiaie/ompa",
    "slug": "ompa",
    "source_packet_id": "phit_dbfd6fa991454331a43fbe9a96038b6d",
    "source_validation_id": "dval_f36a29492d3047ee85d07d51a5cc5d62"
  },
  "merchandising": {
    "best_for": "需要信息检索与知识管理能力，并使用 mcp_host的用户",
    "github_forks": 0,
    "github_stars": 2,
    "one_liner_en": "Universal AI agent memory layer — vault + palace + temporal knowledge graph",
    "one_liner_zh": "Universal AI agent memory layer — vault + palace + temporal knowledge graph",
    "primary_category": {
      "category_id": "research-knowledge",
      "confidence": "medium",
      "name_en": "Research & Knowledge",
      "name_zh": "信息检索与知识管理",
      "reason": "matched_keywords:knowledge, graph"
    },
    "target_user": "使用 mcp_host 等宿主 AI 的用户",
    "title_en": "ompa",
    "title_zh": "ompa 能力包",
    "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": "Natural-language Web Actions",
        "label_zh": "自然语言网页操作",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-natural-language-web-actions",
        "type": "core_capability"
      },
      {
        "label_en": "Multi-role Workflow",
        "label_zh": "多角色协作流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-multi-role-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Structured Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-structured-data-extraction",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_dbfd6fa991454331a43fbe9a96038b6d",
  "page_model": {
    "artifacts": {
      "artifact_slug": "ompa",
      "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 ompa",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/jmiaie/ompa#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "安全审查与权限治理",
        "知识库问答",
        "自然语言网页操作",
        "多角色协作流程",
        "结构化数据提取"
      ],
      "eyebrow": "信息检索与知识管理",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要信息检索与知识管理能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Universal AI agent memory layer — vault + palace + temporal knowledge graph"
        },
        {
          "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",
          "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": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OMPA v0.2.0 — The Big Rename",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_ac771ab081be444ab18c5c1963becb64 | https://github.com/jmiaie/ompa/releases/tag/v0.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：OMPA v0.2.0 — The Big Rename",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[P0] agent_integration.py race condition — session.memory attribute not available on cold start",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_db65ef8ac28c41048d74c03c80cbed28 | https://github.com/jmiaie/ompa/issues/6 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[P0] agent_integration.py race condition — session.memory attribute not available on cold start",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:1207151629 | https://github.com/jmiaie/ompa | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "I did an analysis of 44 AI agent frameworks, sharing the result 18 Feb 2026 · One thing missing from most framework comparisons is how they handle failures during agent execution. Tool call retries, error recovery, and ...",
            "category": "运行坑",
            "evidence": [
              "social_signal:reddit | ssig_33233a78090343098fbddbeab9bc927d | https://www.reddit.com/r/LocalLLaMA/comments/1r84o6p/i_did_an_analysis_of_44_ai_agent_frameworks/ | I did an analysis of 44 AI agent frameworks, sharing the result"
            ],
            "severity": "medium",
            "suggested_check": "Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。",
            "title": "社区讨论暴露的待验证问题：I did an analysis of 44 AI agent frameworks, sharing the result",
            "user_impact": "这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。"
          },
          {
            "body": "Your self-hosted AI agents can match closed-source models - I ... - Reddit 24 Nov 2025 · Looking for open-source knowledge management tool ... Let's compare 5 Open-Source AI Agent Tools that everyone cannot stop talking about on Reddit.",
            "category": "运行坑",
            "evidence": [
              "social_signal:reddit | ssig_4fefa11ceedb46d4af5e2ff44e7709e1 | https://www.reddit.com/r/selfhosted/comments/1p5q8f1/your_selfhosted_ai_agents_can_match_closedsource/ | Your self-hosted AI agents can match closed-source models - I ... - Reddit"
            ],
            "severity": "medium",
            "suggested_check": "Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。",
            "title": "社区讨论暴露的待验证问题：Your self-hosted AI agents can match closed-source models - I ... - Reddit",
            "user_impact": "这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | 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:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：OMPA v0.2.1 — Security & Reliability Hardening",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_ab0ad6b963354f2096bef6783c95c289 | https://github.com/jmiaie/ompa/releases/tag/v0.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：OMPA v0.2.1 — Security & Reliability Hardening",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | 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:1207151629 | https://github.com/jmiaie/ompa | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 11 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：OMPA v0.2.0 — The Big Rename。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 4,
        "forks": 0,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 2
      },
      "source_url": "https://github.com/jmiaie/ompa",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Universal AI agent memory layer — vault + palace + temporal knowledge graph",
      "title": "ompa 能力包",
      "trial_prompt": "# ompa - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for jmiaie/ompa.\n\nProject:\n- Name: ompa\n- Repository: https://github.com/jmiaie/ompa\n- Summary: Universal AI agent memory layer — vault + palace + temporal knowledge graph\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Universal AI agent memory layer — vault + palace + temporal knowledge graph\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Universal AI agent memory layer — vault + palace + temporal knowledge graph\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. introduction: Introduction to OMPA. Produce one small intermediate artifact and wait for confirmation.\n2. quickstart: Quick Start Guide. Produce one small intermediate artifact and wait for confirmation.\n3. three-layer-architecture: Three-Layer Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. lifecycle-hooks: Lifecycle Hooks. Produce one small intermediate artifact and wait for confirmation.\n5. vault-system: Vault System. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/jmiaie/ompa\n- https://github.com/jmiaie/ompa#readme\n- README.md\n- ompa/__init__.py\n- ompa/cli.py\n- pyproject.toml\n- ompa/vault.py\n- ompa/palace.py\n- ompa/knowledge_graph.py\n- ompa/hooks.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github, reddit, x。github/github_issue: [P0] agent_integration.py race condition — session.memory attribute not （https://github.com/jmiaie/ompa/issues/6）；github/github_release: OMPA v0.2.1 — Security & Reliability Hardening（https://github.com/jmiaie/ompa/releases/tag/v0.2.1）；github/github_release: OMPA v0.2.0 — The Big Rename（https://github.com/jmiaie/ompa/releases/tag/v0.2.0）；reddit: Anybody who tried Hermes-Agent? : r/LocalLLaMA - Reddit（https://www.reddit.com/r/LocalLLaMA/comments/1ro9lph/anybody_who_tried_hermesagent/）；x: 100+ agentic skills, commands, and plugins for PMs. Designed for ...（https://x.com/PawelHuryn/status/2028902562905416087）；reddit: Your self-hosted AI agents can match closed-source models - I ... - Redd（https://www.reddit.com/r/selfhosted/comments/1p5q8f1/your_selfhosted_ai_agents_can_match_closedsource/）；reddit: I built a free MCP server with Claude Code that gives Claude a Jira-like（https://www.reddit.com/r/ClaudeAI/comments/1rbe1dp/i_built_a_free_mcp_server_with_claude_code_that/）；reddit: I did an analysis of 44 AI agent frameworks, sharing the result（https://www.reddit.com/r/LocalLLaMA/comments/1r84o6p/i_did_an_analysis_of_44_ai_agent_frameworks/）；x: Zero-human company tech Open-source AI Agent orchestration ...（https://x.com/tomosman/status/2029811313182982315）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[P0] agent_integration.py race condition — session.memory attribute not ",
              "url": "https://github.com/jmiaie/ompa/issues/6"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "OMPA v0.2.1 — Security & Reliability Hardening",
              "url": "https://github.com/jmiaie/ompa/releases/tag/v0.2.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "OMPA v0.2.0 — The Big Rename",
              "url": "https://github.com/jmiaie/ompa/releases/tag/v0.2.0"
            },
            {
              "kind": "searxng_indexed",
              "source": "reddit",
              "title": "Anybody who tried Hermes-Agent? : r/LocalLLaMA - Reddit",
              "url": "https://www.reddit.com/r/LocalLLaMA/comments/1ro9lph/anybody_who_tried_hermesagent/"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "100+ agentic skills, commands, and plugins for PMs. Designed for ...",
              "url": "https://x.com/PawelHuryn/status/2028902562905416087"
            },
            {
              "kind": "searxng_indexed",
              "source": "reddit",
              "title": "Your self-hosted AI agents can match closed-source models - I ... - Redd",
              "url": "https://www.reddit.com/r/selfhosted/comments/1p5q8f1/your_selfhosted_ai_agents_can_match_closedsource/"
            },
            {
              "kind": "searxng_indexed",
              "source": "reddit",
              "title": "I built a free MCP server with Claude Code that gives Claude a Jira-like",
              "url": "https://www.reddit.com/r/ClaudeAI/comments/1rbe1dp/i_built_a_free_mcp_server_with_claude_code_that/"
            },
            {
              "kind": "searxng_indexed",
              "source": "reddit",
              "title": "I did an analysis of 44 AI agent frameworks, sharing the result",
              "url": "https://www.reddit.com/r/LocalLLaMA/comments/1r84o6p/i_did_an_analysis_of_44_ai_agent_frameworks/"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "Zero-human company tech Open-source AI Agent orchestration ...",
              "url": "https://x.com/tomosman/status/2029811313182982315"
            }
          ],
          "status": "已收录 9 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "信息检索与知识管理",
      "desc": "Universal AI agent memory layer — vault + palace + temporal knowledge graph",
      "effort": "安装已验证",
      "forks": 0,
      "icon": "search",
      "name": "ompa 能力包",
      "risk": "可发布",
      "slug": "ompa",
      "stars": 2,
      "tags": [
        "安全审查与权限治理",
        "知识库问答",
        "自然语言网页操作",
        "多角色协作流程",
        "结构化数据提取"
      ],
      "thumb": "blue",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/jmiaie/ompa 项目说明书\n\n生成时间：2026-05-15 13:44:18 UTC\n\n## 目录\n\n- [Introduction to OMPA](#introduction)\n- [Quick Start Guide](#quickstart)\n- [Feature Comparison](#comparison)\n- [Three-Layer Architecture](#three-layer-architecture)\n- [Lifecycle Hooks](#lifecycle-hooks)\n- [Vault System](#vault-system)\n- [Palace System](#palace-system)\n- [Knowledge Graph](#knowledge-graph)\n- [Message Classification](#message-classification)\n- [Python API Reference](#python-api)\n\n<a id='introduction'></a>\n\n## Introduction to OMPA\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Quick Start Guide](#quickstart)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n- [ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n- [ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n</details>\n\n# Introduction to OMPA\n\nOMPA (Obsidian-MemPalace-Agnostic) is a lightweight, framework-agnostic memory management system designed for AI agents. It provides persistent storage, semantic search, knowledge graph tracking, and a palace metaphor for organizing notes and memories across sessions.\n\n## Overview\n\nOMPA serves as a **second brain** for AI agents, enabling them to:\n\n- Persist and retrieve information across sessions\n- Classify and automatically route messages to appropriate storage locations\n- Search vault contents using semantic similarity\n- Track temporal knowledge graphs with validity windows\n- Navigate a hierarchical palace structure (wings, rooms, drawers, halls, tunnels)\n\nThe project was renamed from \"AgnosticObsidian\" to OMPA in version 0.2.0, with backward compatibility preserved via an alias. 资料来源：[CHANGELOG.md:1-10]()\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Dual-Vault Architecture** | Separate shared and personal vault storage with isolation modes |\n| **Semantic Search** | Local embedding-based search using sentence-transformers |\n| **Temporal Knowledge Graph** | SQLite-backed triples with validity windows |\n| **Message Classification** | 15 message types with automatic routing |\n| **Lifecycle Hooks** | 5 hooks for extending agent behavior |\n| **MCP Server** | 15 tools exposed via Model Context Protocol |\n| **CLI Interface** | 14 commands for vault operations |\n\n## Architecture\n\nOMPA follows a layered architecture with distinct responsibilities:\n\n```mermaid\ngraph TD\n    subgraph \"OMPA Architecture\"\n        CLI[CLI<br>14 commands]\n        MCP[MCP Server<br>15 tools]\n        Core[Core Module<br>Ompa class]\n        Vault[Vault<br>CRUD operations]\n        Palace[Palace<br>Metadata layers]\n        KG[Knowledge Graph<br>SQLite triples]\n        Semantic[Semantic Index<br>Embeddings]\n        Classifier[Classifier<br>15 message types]\n        Hooks[Hook Manager<br>Lifecycle hooks]\n    end\n    \n    CLI --> Core\n    MCP --> Core\n    Core --> Vault\n    Core --> Palace\n    Core --> KG\n    Core --> Semantic\n    Core --> Classifier\n    Core --> Hooks\n```\n\n### Core Components\n\n#### 1. Vault (`ompa/vault.py`)\n\nThe Vault layer handles file-based storage for notes. It provides:\n\n- Brain/work/org/perf folder organization\n- Note CRUD operations\n- Orphan detection\n- Path traversal protection\n- UTF-8 encoding enforcement\n\n资料来源：[README.md:47-56]()\n\n#### 2. Palace (`ompa/palace.py`)\n\nThe Palace metadata layer provides hierarchical navigation:\n\n- **Wings**: Top-level categories\n- **Rooms**: Secondary divisions within wings\n- **Drawers**: Tertiary storage units\n- **Halls**: Cross-room connections\n- **Tunnels**: Cross-wing shortcuts\n\n#### 3. Knowledge Graph (`ompa/knowledge_graph.py`)\n\nTemporal knowledge graph backed by SQLite:\n\n- Triple storage: `(subject, predicate, object)`\n- Validity windows: `valid_from` and `valid_to` timestamps\n- Timeline queries for entity history\n- Auto-population from vault wikilinks and frontmatter\n\n#### 4. Classifier (`ompa/classifier.py`)\n\nMessage classification engine supporting 15 message types:\n\n| Message Type | Description |\n|--------------|-------------|\n| `DECISION` | Architectural decisions, ADR records |\n| `INCIDENT` | Bugs, outages, debugging events |\n| `WIN` | Achievements, deployments, milestones |\n| `ONE_ON_ONE` | Manager/peer check-ins |\n| `MEETING` | Meeting notes and action items |\n| `PROJECT_UPDATE` | Project status reports |\n| `REFLECTION` | Retrospectives, learnings |\n| `TODO` | Task items |\n| `QUESTION` | Technical questions |\n| `IDEA` | Brainstorming, proposals |\n| `LEARNING` | New information acquired |\n| `BLOCKER` | Impediments |\n| `ARCHITECTURE` | System design discussions |\n| `SECURITY` | Security-related events |\n| `DATA` | Data-related events |\n\n资料来源：[ompa/classifier.py:1-50]()\n\n#### 5. Semantic Search (`ompa/semantic.py`)\n\nLocal semantic search using sentence-transformers:\n\n- Lazy model loading (downloaded on first access)\n- Incremental indexing (tracks file modification times)\n- Cosine similarity scoring\n- Optional feature via `pip install ompa[all]`\n\n#### 6. Hooks (`ompa/hooks.py`)\n\nLifecycle hooks for extending OMPA behavior:\n\n```mermaid\ngraph LR\n    SS[session_start] --> CB[Hook execution]\n    HM[handle_message] --> CB\n    PT[post_tool] --> CB\n    PC[pre_compact] --> CB\n    ST[stop] --> CB\n    \n    CB --> HR[HookResult]\n```\n\n资料来源：[CONTRIBUTING.md:43-54]()\n\n#### 7. MCP Server (`ompa/mcp_server.py`)\n\nModel Context Protocol server exposing 15 tools:\n\n```mermaid\ngraph TD\n    MCP[JSON-RPC<br>stdin/stdout] --> Tools\n    Tools --> ao_session_start\n    Tools --> ao_classify\n    Tools --> ao_search\n    Tools --> ao_kg_query\n    Tools --> ao_kg_add\n    Tools --> ao_kg_stats\n    Tools --> ao_palace_wings\n    Tools --> ao_palace_rooms\n    Tools --> ao_palace_tunnel\n    Tools --> ao_validate\n    Tools --> ao_wrap_up\n    Tools --> ao_status\n    Tools --> ao_orphans\n    Tools --> ao_kg_populate\n    Tools --> ao_init\n```\n\n资料来源：[CLAUDE.md:1-15]()\n\n## Installation\n\n### Package Options\n\n```bash\n# Core only (vault + palace + KG + CLI + MCP)\npip install ompa\n\n# With local semantic search\npip install ompa[all]\n\n# Development dependencies\npip install ompa[dev]\n```\n\nRequirements: Python 3.10+\n\n资料来源：[README.md:36-44]()\n\n### Quick Start\n\n```bash\n# Initialize vault\nao init\n\n# Check vault health\nao status\n\n# Start a session\nao session-start\n\n# Classify a message\nao classify \"We decided to go with Postgres\"\n\n# Search vault\nao search \"authentication decisions\"\n\n# Query knowledge graph\nao kg-query Kai\n\n# End session\nao wrap-up\n```\n\n## Dual-Vault Architecture\n\nOMPA supports separating team/organization content from personal notes:\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\nao = Ompa(config=config)\n```\n\n### Isolation Modes\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified to shared or personal vault based on message type |\n| `STRICT` | Explicit `VaultTarget` routing required for all operations |\n| `MANUAL` | Default vault configurable, explicit routing optional |\n\n资料来源：[README.md:57-71]()\n\n## Python API\n\n### Core Class\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(vault_path=\"./workspace\")\n\n# Lifecycle\ncontext = ao.session_start()              # Returns ~2K token context string\nhint = ao.handle_message(\"We won the enterprise deal!\")\nao.post_tool(\"write\", {\"file_path\": \"work/active/auth.md\"})\nao.wrap_up()                              # alias for stop()\nao.standup()                              # alias for session_start()\n\n# Search\nresults = ao.search(\"authentication decisions\", wing=\"Orion\")\n\n# Classification\nclassification = ao.classify(message)\nrouting_hint = ao.get_routing_hint(message)\n\n# Knowledge graph\nao.kg.add_triple(\"Kai\", \"works_on\", \"Orion\", valid_from=\"2025-06-01\")\ntriples = ao.kg.query_entity(\"Kai\")\ntimeline = ao.kg.timeline(\"Orion\")\n```\n\n资料来源：[STABILITY.md:12-45]()\n\n### Data Classes\n\n```python\nHookResult(hook_name, success, output, tokens_hint, error)\nClassification(message_type, confidence, suggested_action, routing_hints)\nSearchResult(path, content_excerpt, score, match_type)\nTriple(subject, predicate, object, valid_from, valid_to, confidence, source_file)\n```\n\n## MCP Desktop Integration\n\nOMPA integrates with AI coding assistants via MCP:\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"/absolute/path/to/vault\"\n      }\n    }\n  }\n}\n```\n\n### Supported IDEs\n\n| IDE | Configuration Location |\n|-----|------------------------|\n| Claude Desktop | `~/.claude/claude_desktop_config.json` |\n| Cursor | `.cursor/mcp.json` |\n| Windsurf | `.windsurf/mcp.json` |\n\n资料来源：[examples/mcp_desktop/README.md:1-50]()\n\n## Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n| `OMPA_ISOLATION_MODE` | `auto` | Isolation mode (dual-vault) |\n\n## Project Structure\n\n```\nompa/\n├── core.py              # Ompa main class — lifecycle, hooks, dual-vault\n├── vault.py             # Vault management (brain/work/org/perf)\n├── palace.py            # Palace metadata (wings/rooms/drawers/halls/tunnels)\n├── knowledge_graph.py   # Temporal KG (SQLite triples + validity windows)\n├── hooks.py             # 5 lifecycle hooks + HookManager\n├── classifier.py        # 15 message types with auto-routing\n├── semantic.py          # Local semantic search (lazy model loading)\n├── mcp_server.py        # MCP protocol server (15 tools)\n├── config.py            # Dual-vault configuration\n└── cli.py               # typer CLI (14 commands)\n```\n\n资料来源：[README.md:47-56]()\n\n## Security Features\n\n- **Path traversal protection**: All vault file operations resolve and boundary-check paths against vault root 资料来源：[CHANGELOG.md:23-26]()\n- **UTF-8 encoding enforcement**: All vault file writes use UTF-8 explicitly\n- **Security audit**: 8/10 rating with 59/59 tests passing\n\n## API Stability\n\nOMPA follows Semantic Versioning. The stable public API includes:\n\n- `Ompa` core class and all public methods\n- Data classes: `HookResult`, `Classification`, `SearchResult`, `Triple`\n- CLI commands and MCP tools\n- Sync backends and adapters\n\n资料来源：[STABILITY.md:1-50]()\n\n## Framework Compatibility\n\n| Agent Framework | Integration Method |\n|-----------------|-------------------|\n| Claude Code | Python API + MCP server |\n| OpenClaw | Python API + MCP server |\n| Codex | Python API + MCP server |\n| Gemini CLI | Python API + MCP server |\n| LangChain | Python API + adapters |\n\n## CLI Reference\n\n| Command | Description |\n|---------|-------------|\n| `ao init` | Initialize a new vault |\n| `ao status` | Health check and stats |\n| `ao session-start` | Inject memory context |\n| `ao classify <msg>` | Classify and route a message |\n| `ao search <query>` | Semantic search |\n| `ao orphans` | Detect orphaned notes |\n| `ao wrap-up` | Session summary and save |\n| `ao wings` | List palace wings |\n| `ao rooms <wing>` | List rooms in a wing |\n| `ao tunnel` | Create/traverse cross-wing tunnel |\n| `ao kg-query <entity>` | Query knowledge graph |\n| `ao kg-timeline <entity>` | Entity timeline |\n| `ao kg-stats` | KG statistics |\n| `ao validate` | Validate vault structure |\n| `ao rebuild-index` | Rebuild semantic index |\n\n资料来源：[README.md:18-37]()\n\n---\n\n<a id='quickstart'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Python API Reference](#python-api)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n- [pyproject.toml](https://github.com/jmiaie/ompa/blob/main/pyproject.toml)\n</details>\n\n# Quick Start Guide\n\nOMPA (Obsidian-MemPalace-Agnostic) is a local-first memory management system for AI agents. It provides a dual-layer architecture combining a **Vault** for source-of-truth note storage with a **Palace** for retrieval acceleration, plus a temporal **Knowledge Graph** for entity tracking. This guide walks you through installation, vault initialization, CLI usage, Python API integration, and MCP server setup.\n\n---\n\n## Prerequisites\n\nBefore installing OMPA, ensure your environment meets the following requirements:\n\n| Requirement | Version | Notes |\n|-------------|---------|-------|\n| Python | 3.10+ | Required for async/await support |\n| pip | Latest recommended | For package installation |\n| git | Any recent version | For source installation |\n| Disk space | ~100MB minimum | +500MB if enabling semantic search |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Installation\n\nOMPA offers multiple installation options depending on your use case.\n\n### Core Installation\n\nThe core package includes vault management, palace metadata, knowledge graph, CLI, and MCP server:\n\n```bash\npip install ompa\n```\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### With Semantic Search\n\nInstall with local semantic search support (adds sentence-transformers and numpy):\n\n```bash\npip install ompa[all]\n```\n\n> **Note:** First run downloads the `all-MiniLM-L6-v2` model (~90MB). Subsequent runs are instant. 资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n### Development Installation\n\nFor contributing or modifying OMPA:\n\n```bash\ngit clone https://github.com/jmiaie/ompa\ncd ompa\npip install -e \".[dev,all]\"\n```\n\n资料来源：[CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n\n---\n\n## Initializing the Vault\n\nAfter installation, initialize your vault to create the required directory structure:\n\n```bash\nao init\n```\n\nThe vault structure is created with the following organization:\n\n```\n.vault/\n├── brain/           # Brain notes (agent memory)\n├── work/            # Work-related notes\n├── org/             # Organizational notes\n├── perf/            # Performance metrics\n├── .palace/         # Palace metadata (internal)\n│   ├── wings/\n│   ├── rooms/\n│   └── tunnels/\n└── .kg/             # Knowledge graph (SQLite)\n    └── knowledge.db\n```\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n### Verify Vault Health\n\nCheck that everything is properly configured:\n\n```bash\nao status\n```\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## CLI Command Reference\n\nOMPA provides 14 CLI commands for vault operations. All commands are prefixed with `ao`.\n\n### Session Lifecycle Commands\n\n| Command | Description |\n|---------|-------------|\n| `ao session-start` | Inject memory context at session start (~2K token context) |\n| `ao wrap-up` | Session summary and persist to vault |\n| `ao stop` | Clean session shutdown |\n| `ao status` | Vault health status and statistics |\n\n### Note Management Commands\n\n| Command | Description |\n|---------|-------------|\n| `ao classify <msg>` | Classify and route a message to the correct folder |\n| `ao search <query>` | Semantic search across vault notes |\n| `ao orphans` | Detect orphaned notes (broken wikilinks) |\n| `ao init` | Initialize a new vault |\n| `ao validate` | Validate vault structure integrity |\n\n### Knowledge Graph Commands\n\n| Command | Description |\n|---------|-------------|\n| `ao kg-query <entity>` | Query knowledge graph for entity |\n| `ao kg-timeline <entity>` | Entity timeline view |\n| `ao kg-stats` | Knowledge graph statistics |\n\n### Palace Navigation Commands\n\n| Command | Description |\n|---------|-------------|\n| `ao wings` | List palace wings |\n| `ao rooms <wing>` | List rooms in a wing |\n| `ao tunnel` | Create/traverse cross-wing tunnel |\n\n### Index Management\n\n| Command | Description |\n|---------|-------------|\n| `ao rebuild-index` | Rebuild the semantic index (skips unchanged files) |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Python API Quick Start\n\n### Basic Usage\n\n```python\nfrom ompa import Ompa\n\n# Initialize with vault path\nao = Ompa(vault_path=\"./workspace\")\n\n# Start a session\ncontext = ao.session_start()\n\n# Classify and route a message\nhint = ao.handle_message(\"We decided to go with Postgres\")\n\n# Use tools\nao.post_tool(\"write\", {\"file_path\": \"work/active/auth.md\"})\n\n# Clean shutdown\nao.stop()\n```\n\n### Semantic Search\n\n```python\n# Search with optional wing filter\nresults = ao.search(\"authentication decisions\", wing=\"Orion\")\n\n# Each result contains: path, content_excerpt, score, match_type\nfor result in results:\n    print(f\"{result.path}: {result.score}\")\n```\n\n### Knowledge Graph Operations\n\n```python\n# Add temporal triples\nao.kg.add_triple(\n    \"Kai\", \n    \"works_on\", \n    \"Orion\", \n    valid_from=\"2025-06-01\"\n)\n\n# Query entity history\ntriples = ao.kg.query_entity(\"Kai\")\n\n# Get entity timeline\ntimeline = ao.kg.timeline(\"Orion\")\n```\n\n### Palace Navigation\n\n```python\n# Create a wing\nao.palace.create_wing(\"Orion\")\n\n# Create a room in a wing\nao.palace.create_room(\"Orion\", \"authentication\")\n\n# Create cross-wing tunnels\nao.palace.create_tunnel(\"Orion\", \"Pegasus\", room=\"shared\")\n```\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## MCP Server Integration\n\nThe MCP (Model Context Protocol) server enables OMPA tools to be used directly within AI coding assistants like Claude Desktop, Cursor, and Windsurf.\n\n### Claude Desktop Setup\n\n**Option 1: CLI (Recommended)**\n\n```bash\nclaude mcp add ompa -- python -m ompa.mcp_server\n```\n\n**Option 2: Manual Configuration**\n\nEdit `~/.claude/claude_desktop_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"/absolute/path/to/your/vault\"\n      }\n    }\n  }\n}\n```\n\n### Cursor / Windsurf Setup\n\nCreate `.cursor/mcp.json` in your project root:\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"${workspaceFolder}/.ompa-vault\",\n        \"OMPA_ENABLE_SEMANTIC\": \"false\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n### Available MCP Tools\n\n| Tool | Description |\n|------|-------------|\n| `ao_session_start` | Inject memory context |\n| `ao_classify` | Classify and route message |\n| `ao_search` | Semantic search |\n| `ao_kg_query` | Query knowledge graph |\n| `ao_kg_add` | Add knowledge triple |\n| `ao_kg_stats` | KG statistics |\n| `ao_palace_wings` | List wings |\n| `ao_palace_rooms` | List rooms in wing |\n| `ao_palace_tunnel` | Create/traverse tunnels |\n| `ao_validate` | Validate vault |\n| `ao_wrap_up` | Session summary |\n| `ao_status` | Vault health |\n| `ao_orphans` | Find orphaned notes |\n| `ao_kg_populate` | Populate KG from vault |\n| `ao_sync` | Sync vault |\n| `ao_write` | Write note |\n| `ao_export` | Export note |\n| `ao_import` | Import note |\n| `ao_init` | Initialize vault |\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n| `OMPA_ISOLATION_MODE` | `auto` | Isolation mode (auto/strict) |\n\n### Verifying Connection\n\nOnce connected, ask your AI assistant:\n\n> \"Use the `ao_status` tool to check my OMPA vault health\"\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md), [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n---\n\n## Dual-Vault Mode\n\nOMPA supports isolating team/organizational content from personal notes using a dual-vault architecture.\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\n\nao = Ompa(config=config)\n```\n\n### Isolation Modes\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified to shared or personal vault based on message type |\n| `STRICT` | Strict isolation, no cross-vault access |\n| `MANUAL` | Explicit `VaultTarget` routing per operation |\n\n### MCP Dual-Vault Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_SHARED_VAULT\": \"/path/to/shared-vault\",\n        \"OMPA_PERSONAL_VAULT\": \"/path/to/personal-vault\",\n        \"OMPA_ISOLATION_MODE\": \"auto\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[AI Agent] --> B[OMPA Core]\n    B --> C[Vault Layer]\n    B --> D[Palace Layer]\n    B --> E[Knowledge Graph]\n    \n    C --> C1[brain/]\n    C --> C2[work/]\n    C --> C3[org/]\n    C --> C4[perf/]\n    \n    D --> D1[Wings]\n    D --> D2[Rooms]\n    D --> D3[Tunnels]\n    \n    E --> E1[SQLite DB]\n    E --> E2[Temporal Triples]\n    \n    F[MCP Server] --> B\n    F --> G[Claude Desktop]\n    F --> H[Cursor]\n    F --> I[Windsurf]\n```\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n---\n\n## Framework Compatibility\n\nOMPA integrates with multiple AI agent frameworks:\n\n| Agent Framework | Integration Method |\n|-----------------|-------------------|\n| Claude Code | Python API + MCP server |\n| OpenClaw | Python API + MCP server |\n| Codex | Python API + MCP server |\n| Gemini CLI | Python API + MCP server |\n| LangChain | Python API adapter |\n| LlamaIndex | Python API adapter |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Typical Session Workflow\n\n```mermaid\ngraph LR\n    A[Session Start] --> B[ao session-start]\n    B --> C[Memory Context Injected]\n    C --> D[Work Session]\n    D --> E[ao classify]\n    D --> F[ao search]\n    D --> G[ao kg-query]\n    E --> H[Notes Created]\n    F --> H\n    G --> H\n    H --> I[Session End]\n    I --> J[ao wrap-up]\n    J --> K[Notes Persisted]\n    K --> L[KG Updated]\n```\n\n1. **Start session**: `ao session-start` injects ~2K tokens of relevant context\n2. **Classify messages**: `ao classify` routes content to appropriate folders\n3. **Search**: `ao search` finds relevant past notes semantically\n4. **Query KG**: `ao kg-query` retrieves entity relationships\n5. **Wrap up**: `ao wrap-up` summarizes and persists everything\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Testing Your Installation\n\nRun the test suite to verify everything works:\n\n```bash\npytest tests/ -v\n```\n\nAll 77+ tests should pass. Tests are located in `tests/test_ompa.py`.\n\n资料来源：[CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n\n---\n\n## Next Steps\n\n- **Explore CLI**: Run `ao --help` for all available commands\n- **Configure MCP**: Set up your preferred AI assistant integration\n- **Add message types**: Extend the classifier for custom routing 资料来源：[CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- **Add hooks**: Implement custom lifecycle hooks for your workflow\n- **API stability**: Review [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md) for public API commitments\n\n---\n\n<a id='comparison'></a>\n\n## Feature Comparison\n\n### 相关页面\n\n相关主题：[Introduction to OMPA](#introduction)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n- [ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n- [ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n</details>\n\n# Feature Comparison\n\nOMPA (Obsidian-MemPalace-Agnostic) is a memory management system for AI agents that provides persistent context injection, semantic search, temporal knowledge graphs, and palace-style memory navigation. This page compares the various features, components, and integration options available in the project.\n\n## Architecture Overview\n\nOMPA follows a dual-layer architecture where the **Vault** serves as the source of truth for notes, and the **Palace** provides retrieval acceleration through metadata organization.\n\n```mermaid\ngraph TD\n    A[Agent Session] --> B[Ompa Core]\n    B --> C[Vault Layer]\n    B --> D[Palace Layer]\n    B --> E[Knowledge Graph]\n    B --> F[Semantic Index]\n    C --> G[brain/ work/ org/ perf/]\n    D --> H[Wings → Rooms → Drawers]\n    E --> I[SQLite Triples]\n    F --> J[Local Embeddings]\n```\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## Core Components\n\n### Package Structure\n\nThe codebase is organized into modular components, each handling a specific responsibility.\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| Core | `core.py` | Main class, lifecycle management, dual-vault support |\n| Vault | `vault.py` | Note CRUD, folder structure, path traversal guards |\n| Palace | `palace.py` | Wings/rooms/drawers metadata, tunnel navigation |\n| Knowledge Graph | `knowledge_graph.py` | Temporal SQLite triples with validity windows |\n| Semantic | `semantic.py` | Local embedding-based search with lazy model loading |\n| Classifier | `classifier.py` | 15 message types with auto-routing |\n| Hooks | `hooks.py` | 5 lifecycle hooks with HookManager |\n| MCP Server | `mcp_server.py` | JSON-RPC protocol over stdin/stdout |\n| CLI | `cli.py` | 14 typer commands |\n| Config | `config.py` | DualVaultConfig, IsolationMode, VaultTarget |\n\n资料来源：[README.md:70-83](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## Installation Options\n\nOMPA offers tiered installation to accommodate different use cases.\n\n| Option | Command | Included Features |\n|--------|---------|-------------------|\n| Core | `pip install ompa` | Vault, palace, KG, CLI, MCP server |\n| Full | `pip install ompa[all]` | Core + sentence-transformers + numpy (semantic search) |\n| Dev | `pip install ompa[dev]` | Development dependencies |\n| Source | `pip install -e \".[all]\"` | Latest features from main branch |\n\n资料来源：[README.md:52-60](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### Environment Variables\n\n| Variable | Default | Description |\n|---|---|---|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n## Dual-Vault Architecture\n\nOMPA supports isolating team/organization content from personal or private notes through a dual-vault architecture.\n\n### Isolation Modes\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified to shared or personal vault based on message type |\n| `MANUAL` | Explicit `VaultTarget` routing per operation |\n| `STRICT` | Enforced separation with sanitization on export |\n\n资料来源：[CHANGELOG.md:2026-04-10](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n### Configuration\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\nao = Ompa(config=config)\n```\n\n资料来源：[README.md:28-36](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### Dual-Vault MCP Tools\n\n| Tool | Purpose |\n|------|---------|\n| `ao_dual_vault_*` | Shared vault operations |\n| Export | Cross-vault export with sanitization |\n| Import | Cross-vault import |\n\n资料来源：[CHANGELOG.md:2026-04-10](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Message Classification\n\nThe classifier categorizes incoming agent messages into 15 types with auto-routing.\n\n### Message Types\n\n| Type | Detected Patterns | Suggested Folder |\n|------|-------------------|------------------|\n| `DECISION` | ADR, agreed to, settled on, defer | org/decisions |\n| `INCIDENT` | incident, outage, bug, crash, debug | work/incidents |\n| `WIN` | won, shipped, launched, deployed | org/wins |\n| `ONE_ON_ONE` | 1:1, check-in, feedback, career | personal/1on1 |\n| `MEETING` | meeting, agenda, takeaways | work/meetings |\n| `PROJECT_UPDATE` | project, initiative, blocked on | work/projects |\n| `PERSON_INFO` | teammate, joined, role change | org/people |\n| `QUESTION` | how do, what is, explain | brain/questions |\n| `TASK` | task, todo, action item | work/tasks |\n| `ARCHITECTURE` | architecture, design, ADR | org/architecture |\n| `CODE` | function, class, PR, commit | work/code |\n| `BRAIN_DUMP` | dump, stream, btw | brain/dumps |\n| `WRAP_UP` | wrap up, end session | brain/sessions |\n| `STANDUP` | standup, daily, morning | work/standups |\n| `GENERAL` | Fallback for unmatched | brain/misc |\n\n资料来源：[ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n\n## CLI Commands\n\nThe `ao` CLI provides 14 commands for vault operations.\n\n| Command | Description |\n|---------|-------------|\n| `ao init` | Initialize a new vault |\n| `ao status` | Health check and statistics |\n| `ao session-start` | Inject memory context (~2K tokens) |\n| `ao classify <msg>` | Classify and route a message |\n| `ao search <query>` | Semantic search |\n| `ao orphans` | Detect orphaned notes |\n| `ao wrap-up` | Session summary and save |\n| `ao wings` | List palace wings |\n| `ao rooms <wing>` | List rooms in a wing |\n| `ao tunnel` | Create/traverse cross-wing tunnel |\n| `ao kg-query <entity>` | Query knowledge graph |\n| `ao kg-timeline <entity>` | Entity timeline |\n| `ao kg-stats` | Knowledge graph statistics |\n| `ao validate` | Validate vault structure |\n| `ao rebuild-index` | Rebuild the semantic index |\n\n资料来源：[README.md:42-57](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## MCP Server Tools\n\nThe MCP server exposes 15 tools via JSON-RPC protocol over stdin/stdout.\n\n### Tool List\n\n| Tool | Category | Purpose |\n|------|----------|---------|\n| `ao_session_start` | Lifecycle | Session initialization |\n| `ao_classify` | Classifier | Message classification |\n| `ao_search` | Search | Semantic search in vault |\n| `ao_kg_query` | KG | Entity query |\n| `ao_kg_add` | KG | Add triple |\n| `ao_kg_stats` | KG | KG statistics |\n| `ao_kg_timeline` | KG | Entity timeline |\n| `ao_kg_populate` | KG | Populate from vault |\n| `ao_palace_wings` | Palace | List wings |\n| `ao_palace_rooms` | Palace | List rooms |\n| `ao_palace_tunnel` | Palace | Cross-wing navigation |\n| `ao_validate` | Vault | Validate structure |\n| `ao_wrap_up` | Lifecycle | Session wrap-up |\n| `ao_status` | Vault | Health status |\n| `ao_orphans` | Vault | Orphan detection |\n\n资料来源：[ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n\n### MCP Protocol Version\n\n| Property | Value |\n|----------|-------|\n| Protocol Version | `2024-11-05` |\n| Server Name | `ompa` |\n| Transport | stdin/stdout JSON-RPC |\n\n## Framework Compatibility\n\nOMPA is designed to be framework-agnostic with no agent SDK dependencies.\n\n| Agent Framework | Integration Method |\n|---|---|\n| Claude Code | Python API + MCP server |\n| OpenClaw | Python API + MCP server |\n| Codex | Python API + MCP server |\n| Gemini CLI | Python API + MCP server |\n| LangChain | Python API (adapters) |\n\n资料来源：[README.md:88-94](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### MCP Desktop Integration\n\n| Desktop IDE | Configuration File |\n|-------------|-------------------|\n| Claude Desktop | `~/.claude/claude_desktop_config.json` |\n| Cursor | `.cursor/mcp.json` |\n| Windsurf | `.windsurf/mcp.json` |\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n## Lifecycle Hooks\n\nOMPA provides 5 lifecycle hooks for extensibility.\n\n| Hook | Trigger | Token Budget | Purpose |\n|------|---------|--------------|---------|\n| `session_start` | Session begin | 2000 | Context injection |\n| `user_message` | Each user message | 100 | Pre-process hints |\n| `post_tool` | After tool execution | 100 | Result capture |\n| `pre_compact` | Before context compaction | 500 | Summary generation |\n| `stop` | Session end | 200 | Persist and cleanup |\n\n资料来源：[ompa/hooks.py](https://github.com/jmiaie/ompa/blob/main/ompa/hooks.py)\n\n### Hook Data Structures\n\n```python\nHookResult(hook_name, success, output, tokens_hint, error)\nHookContext(vault_path, session_id, timestamp, agent_name, memory)\n```\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n\n## Knowledge Graph\n\n### Data Model\n\n```mermaid\ngraph LR\n    A[Subject] -->|Predicate| B[Object]\n    B -->|valid_from| C[Start Date]\n    B -->|valid_to| D[End Date]\n    B -->|confidence| E[Score]\n    B -->|source| F[File]\n```\n\n### API Methods\n\n| Method | Description |\n|--------|-------------|\n| `kg.add_triple()` | Add temporal triple |\n| `kg.query_entity()` | Query entity relationships |\n| `kg.timeline()` | Query entity history |\n| `kg.populate_from_vault()` | Extract from notes |\n\n资料来源：[ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n\n## Semantic Search\n\n### Features\n\n| Feature | Description |\n|---------|-------------|\n| Incremental indexing | Tracks file modification times, re-embeds only changed notes |\n| Lazy model loading | Model download deferred until first access |\n| Local embeddings | No API calls required |\n\n资料来源：[CHANGELOG.md:2026-04-08](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Stable APIs\n\nThe following APIs are guaranteed stable within major versions.\n\n### Data Classes\n\n```python\nHookResult(hook_name, success, output, tokens_hint, error)\nClassification(message_type, confidence, suggested_action, routing_hints)\nSearchResult(path, content_excerpt, score, match_type)\nTriple(subject, predicate, object, valid_from, valid_to, confidence, source_file)\nSyncResult(success, backend, direction, files_changed, message, error, details)\n```\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n\n### Enums\n\n```python\nMessageType      # 15 values: DECISION, INCIDENT, WIN, ...\nIsolationMode    # AUTO, STRICT, MANUAL\nVaultTarget      # SHARED, PERSONAL\n```\n\n## Security Features\n\n| Feature | Implementation |\n|---------|----------------|\n| Path traversal protection | All vault file operations resolve and boundary-check paths |\n| Dual-vault isolation | Content separation with sanitization |\n| UTF-8 enforcement | Explicit encoding for all file writes |\n| Security audit | 8/10 rating with 59/59 tests passing |\n\n资料来源：[CHANGELOG.md:2026-04-11](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Python Version Requirements\n\n| Version | Status |\n|---------|--------|\n| Python 3.10+ | Required |\n| Earlier versions | Not supported |\n\n资料来源：[README.md:65](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n<a id='three-layer-architecture'></a>\n\n## Three-Layer Architecture\n\n### 相关页面\n\n相关主题：[Vault System](#vault-system), [Palace System](#palace-system), [Knowledge Graph](#knowledge-graph)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [ompa/vault.py](https://github.com/jmiaie/ompa/blob/main/ompa/vault.py)\n- [ompa/palace.py](https://github.com/jmiaie/ompa/blob/main/ompa/palace.py)\n- [ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n- [ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n- [ompa/config.py](https://github.com/jmiaie/ompa/blob/main/ompa/config.py)\n- [ompa/cli.py](https://github.com/jmiaie/ompa/blob/main/ompa/cli.py)\n</details>\n\n# Three-Layer Architecture\n\nOMPA implements a three-layer architecture designed for AI agent memory management. Each layer serves a distinct purpose while maintaining loose coupling through well-defined interfaces. This architecture separates storage (Vault), retrieval acceleration (Palace), and temporal relationship tracking (Knowledge Graph).\n\n## Overview\n\nThe three layers work in concert to provide comprehensive memory capabilities for AI agents:\n\n| Layer | Primary Role | Technology | Purpose |\n|-------|--------------|------------|---------|\n| **Vault** | Source of truth | File system (Markdown) | Persistent storage of notes and context |\n| **Palace** | Retrieval acceleration | Metadata + indexing | Fast navigation through spatial metaphors |\n| **Knowledge Graph** | Temporal relationships | SQLite | Track entity relationships over time |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)  \n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## Architecture Diagram\n\n```mermaid\ngraph TB\n    subgraph \"Layer 1: Vault\"\n        V[Vault Manager]\n        VF[Vault Folders<br/>brain/work/org/perf]\n        VP[Path Traversal Guards]\n    end\n    \n    subgraph \"Layer 2: Palace\"\n        P[Palace Manager]\n        PW[Wings/Rooms/Drawers]\n        PT[Tunnels]\n    end\n    \n    subgraph \"Layer 3: Knowledge Graph\"\n        KG[Knowledge Graph]\n        KGS[SQLite Triples]\n        KGT[Temporal Validity Windows]\n    end\n    \n    A[Agent/AI] --> C[Ompa Core]\n    C --> V\n    C --> P\n    C --> KG\n    \n    V --> VF\n    P --> PW\n    KG --> KGS\n    \n    C --> CI[Classifier]\n    CI --> VF\n    \n    style V fill:#e1f5fe\n    style P fill:#fff3e0\n    style KG fill:#e8f5e9\n```\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## Layer 1: Vault\n\nThe Vault layer serves as the source of truth for all memory content. Notes are stored as Markdown files with YAML frontmatter on the file system.\n\n### Purpose and Scope\n\nThe Vault layer handles all CRUD operations for notes, enforces path security boundaries, and organizes content into logical folders based on message type classification. Every piece of information stored in OMPA ultimately lives in the Vault.\n\n资料来源：[ompa/vault.py](https://github.com/jmiaie/ompa/blob/main/ompa/vault.py)\n\n### Folder Structure\n\nNotes are automatically routed to appropriate folders based on the `MessageType` classifier:\n\n| Folder | Message Types | Content Category |\n|--------|---------------|------------------|\n| `brain/` | Brain-related | Core memories, session context |\n| `work/` | Work-related | Professional decisions, projects |\n| `org/` | Organization-related | Team information, processes |\n| `perf/` | Performance-related | Metrics, evaluations |\n\n资料来源：[CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n\n### Security Features\n\nAll Vault file operations implement path traversal protection:\n\n```python\ndef _safe_resolve(vault_root: str, file_path: str) -> Path:\n    # Resolves path and validates it stays within vault boundary\n    # Raises SecurityError if traversal detected\n```\n\nPath boundaries are checked before any file read or write operation, preventing unauthorized access to files outside the vault directory. 资料来源：[CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n### Dual-Vault Mode\n\nThe Vault layer supports dual-vault isolation for separating personal and shared content:\n\n```python\nfrom ompa import DualVaultConfig, IsolationMode, VaultTarget\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\n```\n\n**Isolation Modes:**\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified based on message type |\n| `MANUAL` | Explicit `VaultTarget` routing per operation |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## Layer 2: Palace\n\nThe Palace layer provides spatial organization and retrieval acceleration using the memory palace metaphor. It adds metadata structure on top of the Vault for fast navigation.\n\n### Purpose and Scope\n\nThe Palace layer enables agents to navigate memories using spatial concepts (wings, rooms, drawers). This mirrors the ancient method of loci technique, proven effective for memory retrieval.\n\n> \"Verbatim storage: No summarization (proven 96.6% R@5 by MemPalace)\"\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n### Palace Components\n\n| Component | Description | Purpose |\n|-----------|-------------|---------|\n| **Wing** | Top-level organizational unit | Group related rooms |\n| **Room** | Contains drawers and notes | Thematic organization |\n| **Drawer** | Container within rooms | Fine-grained categorization |\n| **Hall** | Cross-cutting collection | Shared resources |\n| **Tunnel** | Connections between wings | Navigate across domains |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### Palace Operations\n\n```python\n# Create organizational structure\nao.palace.create_wing(\"Orion\")\nao.palace.create_room(\"Orion\", \"decisions\")\nao.palace.create_drawer(\"Orion\", \"decisions\", \"auth\")\n\n# Navigate with tunnels\nao.palace.create_tunnel(\"Orion\", \"Phoenix\", room=\"shared\")\n```\n\n### Relationship to Vault\n\nThe Palace layer does not store content directly—it maintains metadata references to Vault notes. This separation allows the Palace structure to evolve independently of note content.\n\n```mermaid\ngraph LR\n    V[Vault Notes] --> P[Palace Metadata]\n    P --> P1[Wings/Rooms Index]\n    P --> P2[Note References]\n    \n    S[Search Query] --> P\n    P --> R[Matched Notes]\n```\n\n资料来源：[ompa/palace.py](https://github.com/jmiaie/ompa/blob/main/ompa/palace.py)\n\n## Layer 3: Knowledge Graph\n\nThe Knowledge Graph layer maintains temporal relationships between entities using SQLite-backed triple storage.\n\n### Purpose and Scope\n\nThe Knowledge Graph tracks facts about entities (subjects) and their relationships (predicates) to other entities (objects), with validity time windows for temporal queries.\n\n> \"Temporal KG: SQLite triples with validity windows\"\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n### Data Model\n\nEach triple consists of:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `subject` | string | Source entity |\n| `predicate` | string | Relationship type |\n| `object` | string | Target entity |\n| `valid_from` | datetime | Start of validity period |\n| `valid_to` | datetime | End of validity period (nullable) |\n| `source` | string | Origin of the fact |\n\n### Knowledge Graph Operations\n\n```python\n# Add a fact with temporal validity\nao.kg.add_triple(\n    subject=\"Kai\",\n    predicate=\"works_on\",\n    object=\"Orion\",\n    valid_from=\"2025-06-01\"\n)\n\n# Query entity history\ntriples = ao.kg.query_entity(\"Kai\")\n\n# Get entity timeline\ntimeline = ao.kg.timeline(\"Orion\")\n```\n\n### Temporal Queries\n\nThe Knowledge Graph supports querying state as of a specific point in time:\n\n```python\n# Query historical state\ntriples = ao.kg.query_entity(\"Kai\", as_of=\"2025-07-15\")\n```\n\nThis enables agents to reason about past states of knowledge without needing to track version history manually.\n\n## Layer Interactions\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant A as Agent\n    participant C as Ompa Core\n    participant CL as Classifier\n    participant V as Vault\n    participant P as Palace\n    participant KG as Knowledge Graph\n    \n    A->>C: handle_message(\"We decided...\")\n    C->>CL: classify(content)\n    CL-->>C: Classification(WorkDecision)\n    C->>V: save_note(WorkDecision)\n    V-->>C: Note saved\n    C->>P: update_structure(content)\n    C->>KG: extract_entities(content)\n    \n    Note over C: Dual-vault routing<br/>applies if configured\n```\n\n### Content Lifecycle\n\n1. **Ingestion**: Message arrives at `Ompa.handle_message()`\n2. **Classification**: `Classifier` determines message type and routing\n3. **Storage**: Note saved to appropriate Vault (shared or personal)\n4. **Organization**: Palace metadata updated\n5. **Relationship**: Entities extracted and added to Knowledge Graph\n\n```mermaid\ngraph TD\n    I[Ingest Message] --> C[Classify]\n    C --> R{Routing Mode}\n    R -->|AUTO| A[Auto-classify]\n    R -->|MANUAL| M[Manual Target]\n    A --> VT{Vault Target}\n    M --> VT\n    VT -->|Shared| VS[Write to Shared Vault]\n    VT -->|Personal| VP[Write to Personal Vault]\n    \n    VS --> P[Update Palace]\n    VP --> P\n    P --> KG[Extract Entities]\n    KG --> KGA[Add to KG]\n```\n\n### Search Integration\n\n```mermaid\ngraph TD\n    SQ[Search Query] --> C[Ompa Core]\n    C -->|Semantic| SI[Semantic Index]\n    C -->|Hybrid| H[Combine]\n    C -->|KG| KGQ[KG Query]\n    \n    SI --> I[Incremental Index]\n    H --> RE[Rank Results]\n    KGQ --> RE\n    \n    RE --> R[Return Results]\n```\n\nThe Semantic Index tracks file modification times and only re-embeds changed notes. 资料来源：[CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Configuration\n\n### Constructor Parameters\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(\n    vault_path=\"./workspace\",           # Primary vault path\n    agent_name=\"agent\",                 # Scopes KG entries\n    enable_semantic=True,              # Enable local semantic search\n    embedding_backend=None,            # Custom embedding backend\n    shared_vault_path=None,            # Dual-vault shared vault\n    personal_vault_path=None,          # Dual-vault personal vault\n    isolation_mode=\"strict\",           # AUTO, MANUAL, or STRICT\n)\n```\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n## CLI Commands by Layer\n\n| Command | Layer | Description |\n|---------|-------|-------------|\n| `ao init` | Vault | Initialize vault structure |\n| `ao status` | Vault | Health check and stats |\n| `ao classify <msg>` | Classifier | Classify and route message |\n| `ao search <query>` | Palace/Semantic | Semantic search |\n| `ao wings` | Palace | List palace wings |\n| `ao rooms <wing>` | Palace | List rooms in wing |\n| `ao tunnel` | Palace | Create/traverse tunnel |\n| `ao kg-query <entity>` | Knowledge Graph | Query entity history |\n| `ao kg-timeline <entity>` | Knowledge Graph | Entity timeline |\n| `ao kg-stats` | Knowledge Graph | KG statistics |\n| `ao orphans` | Vault | Detect orphaned notes |\n| `ao validate` | Vault | Validate vault structure |\n| `ao rebuild-index` | Palace/Semantic | Rebuild semantic index |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## Design Principles\n\nThe three-layer architecture adheres to the following principles documented in the project:\n\n| Principle | Implementation |\n|-----------|-----------------|\n| **Lazy semantic loading** | `SemanticIndex._model` loaded on first access |\n| **Framework-agnostic** | Pure Python, no agent SDK dependencies |\n| **Verbatim storage** | No summarization—proven 96.6% R@5 on LongMemEval |\n| **Path traversal guards** | All vault file ops resolve + boundary-check paths |\n| **Context managers** | All SQLite connections use `with` for leak-free operation |\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## See Also\n\n- [API Stability](STABILITY.md) — Public API guarantees\n- [MCP Server](ompa/mcp_server.py) — MCP protocol integration\n- [CLI Reference](README.md) — Command reference\n- [Contributing Guide](CONTRIBUTING.md) — Development setup\n\n---\n\n<a id='lifecycle-hooks'></a>\n\n## Lifecycle Hooks\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Python API Reference](#python-api)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/hooks.py](https://github.com/jmiaie/ompa/blob/main/ompa/hooks.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n</details>\n\n# Lifecycle Hooks\n\n## Overview\n\nLifecycle Hooks provide a plugin-based extensibility mechanism for the OMPA memory system. They allow developers to intercept and respond to key events during an agent session, such as session initialization, message handling, tool execution, context compaction, and shutdown.\n\nHooks operate as an event-driven layer between the `Ompa` core class and the underlying vault, knowledge graph, and palace subsystems. Each hook receives a `HookContext` containing session metadata and returns a `HookResult` with execution status and token budget information.\n\n## Architecture\n\n### Component Hierarchy\n\n```mermaid\ngraph TD\n    subgraph \"Ompa Core\"\n        A[Ompa Instance] --> B[HookManager]\n    end\n    \n    subgraph \"Hook System\"\n        B --> C[SessionStartHook]\n        B --> D[UserMessageHook]\n        B --> E[PostToolHook]\n        B --> F[PreCompactHook]\n        B --> G[StopHook]\n        B --> H[Custom Hooks]\n    end\n    \n    subgraph \"Hook Infrastructure\"\n        C --> I[HookContext]\n        D --> I\n        E --> I\n        F --> I\n        G --> I\n        I --> J[HookResult]\n    end\n```\n\n### Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant Ompa as Ompa Core\n    participant HookManager\n    participant Hook as Concrete Hook\n    \n    Agent->>Ompa: session_start()\n    Ompa->>HookManager: run_session_start(memory)\n    HookManager->>HookContext: create context\n    HookManager->>Hook: execute(context, **kwargs)\n    Hook-->>HookManager: HookResult\n    HookManager-->>Ompa: HookResult\n    Ompa-->>Agent: context string (~2K tokens)\n    \n    Agent->>Ompa: handle_message(msg)\n    Ompa->>HookManager: run_user_message(message)\n    HookManager->>Hook: execute(context, message)\n    Hook-->>HookManager: HookResult\n```\n\n## Core Data Models\n\n### HookContext\n\nPassed to every hook execution, providing runtime context.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `vault_path` | `Path` | Absolute path to the active vault |\n| `session_id` | `str` | Session identifier in `YYYYMMDD_HHMMSS` format |\n| `timestamp` | `datetime` | Session start time |\n| `agent_name` | `str` | Name of the agent (default: `\"agent\"`) |\n| `memory` | `dict` | Optional memory/context dictionary |\n\n资料来源：[ompa/hooks.py:10-17]()\n\n### HookResult\n\nReturn type from all hook executions.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `hook_name` | `str` | Name of the hook that produced this result |\n| `success` | `bool` | Whether hook execution succeeded |\n| `output` | `str` | Hook output (e.g., context string, summary) |\n| `tokens_hint` | `int` | Estimated token count for LLM context |\n| `error` | `str` | Optional error message if `success=False` |\n\n资料来源：[ompa/hooks.py:19-23]()\n\n### Hook (Base Class)\n\n```python\nclass Hook(ABC):\n    def __init__(self, name: str, token_budget: int = 200):\n        self.name = name\n        self.token_budget = token_budget\n    \n    @abstractmethod\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        ...\n```\n\n资料来源：[ompa/hooks.py:3-12]()\n\n## Default Hooks\n\nOMPA ships with five built-in lifecycle hooks, each handling a specific phase of the agent session.\n\n| Hook | Trigger | Token Budget | Purpose |\n|------|---------|--------------|---------|\n| `session_start` | `Ompa.session_start()` | 200 | Session initialization, context injection |\n| `user_message` | `Ompa.handle_message()` | 50 | Message classification and routing |\n| `post_tool` | `Ompa.post_tool()` | 50 | Tool execution logging |\n| `pre_compact` | `Ompa.pre_compact()` | 200 | Context compression preparation |\n| `stop` | `Ompa.stop()` / `Ompa.wrap_up()` | 200 | Session summary and persistence |\n\n### SessionStartHook\n\nExecutes at session initialization. Collects vault statistics, knowledge graph status, and palace structure to build a ~2K token context for LLM injection.\n\n```python\nclass SessionStartHook(Hook):\n    def __init__(self):\n        super().__init__(\"session_start\", token_budget=200)\n    \n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        # Collect brain notes count\n        # Fetch KG stats (triple count)\n        # Gather palace wing/room structure\n        # Return context string for LLM injection\n```\n\n### StopHook\n\nExecutes during graceful shutdown. Generates a session summary, warns if the knowledge graph is empty, and persists state.\n\n```python\nclass StopHook(Hook):\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        lines = []\n        lines.append(f\"## Session {context.session_id} Summary\")\n        lines.append(f\"Agent: {context.agent_name}\")\n        lines.append(f\"Timestamp: {context.timestamp}\")\n        \n        # KG health warning\n        if kg_stats[\"triple_count\"] == 0:\n            lines.append(\"**WARNING:** KG is empty — run `ao kg-populate`\")\n        \n        return HookResult(hook_name=self.name, success=True, output=output)\n```\n\n资料来源：[ompa/hooks.py:77-119]()\n\n## HookManager\n\nThe `HookManager` class orchestrates hook registration and execution.\n\n```python\nclass HookManager:\n    def __init__(self, vault_path: str | Path, agent_name: str = \"agent\"):\n        self.vault_path = Path(vault_path)\n        self.agent_name = agent_name\n        self.session_id = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n        self.timestamp = datetime.now()\n        \n        # Register default hooks\n        self.hooks = {\n            \"session_start\": SessionStartHook(),\n            \"user_message\": UserMessageHook(),\n            \"post_tool\": PostToolHook(),\n            \"pre_compact\": PreCompactHook(),\n            \"stop\": StopHook(),\n        }\n```\n\n资料来源：[ompa/hooks.py:121-139]()\n\n### Key Methods\n\n| Method | Signature | Description |\n|--------|-----------|-------------|\n| `register_hook` | `register_hook(name: str, hook: Hook)` | Add or replace a hook |\n| `unregister_hook` | `unregister_hook(name: str)` | Remove a hook |\n| `run_session_start` | `run_session_start(memory=None)` | Execute session_start hooks |\n| `run_user_message` | `run_user_message(message: str)` | Execute user_message hooks |\n| `run_post_tool` | `run_post_tool(tool_name, tool_input)` | Execute post_tool hooks |\n| `run_pre_compact` | `run_pre_compact(transcript: str)` | Execute pre_compact hooks |\n| `run_stop` | `run_stop()` | Execute stop hooks |\n\n## Integration with Ompa Core\n\nThe `Ompa` class exposes lifecycle methods that delegate to `HookManager`.\n\n```mermaid\ngraph LR\n    A[Ompa.session_start] --> B[HookManager.run_session_start]\n    C[Ompa.handle_message] --> D[HookManager.run_user_message]\n    E[Ompa.post_tool] --> F[HookManager.run_post_tool]\n    G[Ompa.pre_compact] --> H[HookManager.run_pre_compact]\n    I[Ompa.stop] --> J[HookManager.run_stop]\n    \n    B --> K[HookResult]\n    D --> L[HookResult]\n    F --> M[HookResult]\n    H --> N[HookResult]\n    J --> O[HookResult]\n```\n\n### Ompa Lifecycle Methods\n\n| Method | Alias | Hook Triggered | Returns |\n|--------|-------|-----------------|---------|\n| `ao.session_start()` | `ao.standup()` | `session_start` | `HookResult` |\n| `ao.handle_message(msg)` | — | `user_message` | `HookResult` |\n| `ao.post_tool(name, input)` | — | `post_tool` | `HookResult` |\n| `ao.pre_compact(transcript)` | — | `pre_compact` | `HookResult` |\n| `ao.stop()` | `ao.wrap_up()` | `stop` | `HookResult` |\n\n资料来源：[ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py) (referenced in STABILITY.md)\n\n## Custom Hooks\n\n### Creating a Custom Hook\n\n```python\nfrom ompa.hooks import Hook, HookContext, HookResult\n\nclass MetricsHook(Hook):\n    def __init__(self):\n        super().__init__(\"metrics\", token_budget=50)\n    \n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        session_duration = datetime.now() - context.timestamp\n        output = f\"Session duration: {session_duration}\"\n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=output,\n            tokens_hint=50\n        )\n```\n\n### Registering Custom Hooks\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(\"./workspace\")\nao.hooks.register_hook(\"metrics\", MetricsHook())\n```\n\n### Replacing Default Hooks\n\nOverride default hooks by registering with the same name:\n\n```python\nclass CustomSessionStartHook(Hook):\n    def __init__(self):\n        super().__init__(\"session_start\", token_budget=300)  # Higher budget\n    \n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        # Custom session initialization\n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=\"Custom context...\",\n            tokens_hint=300\n        )\n\nao.hooks.register_hook(\"session_start\", CustomSessionStartHook())\n```\n\n## Hook Execution Patterns\n\n### Pattern: Always Execute\n\nHooks execute on every invocation unless an exception is raised:\n\n```python\nclass PostToolHook(Hook):\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        tool_name = kwargs.get(\"tool_name\")\n        tool_input = kwargs.get(\"tool_input\", {})\n        \n        # Always log tool execution\n        log_entry = f\"[{context.session_id}] {tool_name}: {tool_input}\"\n        append_to_log(context.vault_path / \"tools.log\", log_entry)\n        \n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=\"Tool logged\",\n            tokens_hint=50\n        )\n```\n\n### Pattern: Conditional Execution\n\nHooks can inspect context and conditionally produce output:\n\n```python\nclass UserMessageHook(Hook):\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        message = kwargs.get(\"message\", \"\")\n        \n        if is_sensitive_content(message):\n            return HookResult(\n                hook_name=self.name,\n                success=True,\n                output=\"\",  # No output for sensitive messages\n                tokens_hint=0\n            )\n        \n        # Normal processing for non-sensitive messages\n        ...\n```\n\n## Configuration\n\n### Token Budget\n\nEach hook declares a `token_budget` indicating its expected output size for context window management:\n\n| Budget | Use Case |\n|--------|----------|\n| 0-50 | Simple notifications, acknowledgments |\n| 50-100 | Tool logs, message classifications |\n| 200-300 | Session context, summaries |\n\n### Agent Name Scoping\n\nThe `agent_name` parameter scopes knowledge graph entries and session identifiers:\n\n```python\nao = Ompa(\n    vault_path=\"./workspace\",\n    agent_name=\"coding-agent\"\n)\n\n# HookContext will receive agent_name=\"coding-agent\"\n```\n\n## API Stability\n\nThe hook system follows OMPA's semantic versioning policy. The following are considered stable:\n\n- `Hook` base class (public interface)\n- `HookContext` data class\n- `HookResult` data class\n- `HookManager.register_hook()` method\n\n**Note:** Internal hook implementations (e.g., `*Hook` classes) may change. Use `HookManager.register_hook()` for custom hooks rather than subclassing internal implementations.\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n\n## CLI Integration\n\nWhile hooks operate at the Python API level, they are invoked through CLI commands:\n\n| CLI Command | Hook Invoked |\n|-------------|--------------|\n| `ao session-start` | `session_start` |\n| `ao classify <msg>` | `user_message` |\n| `ao wrap-up` | `stop` |\n| `ao status` | `session_start` (read-only) |\n\n## Error Handling\n\nHooks should return `HookResult` with `success=False` on failure:\n\n```python\ndef execute(self, context: HookContext, **kwargs) -> HookResult:\n    try:\n        result = risky_operation()\n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=str(result),\n            tokens_hint=50\n        )\n    except Exception as e:\n        logger.error(\"Hook %s failed: %s\", self.name, e)\n        return HookResult(\n            hook_name=self.name,\n            success=False,\n            output=\"\",\n            error=str(e)\n        )\n```\n\nThe `HookManager` logs hook failures but continues execution of subsequent hooks.\n\n---\n\n<a id='vault-system'></a>\n\n## Vault System\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Message Classification](#message-classification)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/vault.py](https://github.com/jmiaie/ompa/blob/main/ompa/vault.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [ompa/config.py](https://github.com/jmiaie/ompa/blob/main/ompa/config.py)\n- [ompa/semantic.py](https://github.com/jmiaie/ompa/blob/main/ompa/semantic.py)\n- [ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n</details>\n\n# Vault System\n\n## Overview\n\nThe Vault System is the core data persistence layer in OMPA (Obsidian-MemPalace-Agnostic). It provides structured storage for notes with a multi-category organization model, semantic indexing capabilities, and dual-vault isolation for separating personal and shared content.\n\n**Primary Responsibilities:**\n- Store and retrieve markdown notes with frontmatter metadata\n- Enforce path traversal security boundaries\n- Manage semantic search indices\n- Support dual-vault architecture for content isolation\n- Track knowledge graph relationships from note content\n\n**资料来源：** [README.md](README.md)()\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Vault Layer\"\n        VAULT[Ompa.vault]\n        BRAIN[Brain Notes]\n        WORK[Work Notes]\n        ORG[Org Notes]\n        PERF[Performance Notes]\n    end\n    \n    subgraph \"Dual-Vault Mode\"\n        SHARED[Shared Vault]\n        PERSONAL[Personal Vault]\n        ISOLATION[IsolationMode]\n    end\n    \n    subgraph \"Index Layer\"\n        SEMANTIC[SemanticIndex]\n        KG[KnowledgeGraph]\n    end\n    \n    VAULT --> BRAIN\n    VAULT --> WORK\n    VAULT --> ORG\n    VAULT --> PERF\n    \n    VAULT --> SEMANTIC\n    VAULT --> KG\n    \n    VAULT --> SHARED\n    VAULT --> PERSONAL\n    SHARED --> ISOLATION\n    PERSONAL --> ISOLATION\n```\n\n## Note Categories\n\nThe vault organizes notes into four primary categories based on content type and access patterns.\n\n### Brain Notes\n\nPersonal knowledge, insights, and unstructured information. Brain notes form the foundation of the memory palace and are typically used for capturing ideas, learnings, and personal context.\n\n**资料来源：** [ompa/vault.py](ompa/vault.py)()\n\n### Work Notes\n\nNotes related to professional activities, projects, and work-related decisions. These notes often contain sensitive business information.\n\n**资料来源：** [ompa/vault.py](ompa/vault.py)()\n\n### Org Notes\n\nOrganizational-level notes containing team decisions, processes, and shared knowledge that may be exported to the shared vault.\n\n**资料来源：** [ompa/vault.py](ompa/vault.py)()\n\n### Performance Notes\n\nTime-bounded notes tracking performance metrics, goals, and accomplishments. These notes support the temporal knowledge graph features.\n\n**资料来源：** [ompa/vault.py](ompa/vault.py)()\n\n## Dual-Vault Architecture\n\nThe dual-vault architecture enables isolation between personal and shared content using `DualVaultConfig` and `IsolationMode`.\n\n### Isolation Modes\n\n| Mode | Behavior | Use Case |\n|------|----------|----------|\n| `AUTO` | Content auto-classified based on message type | Automated routing based on classifier results |\n| `MANUAL` | Explicit `VaultTarget` routing per operation | User-controlled content placement |\n| `STRICT` | Strict separation, no cross-vault operations | Maximum isolation requirements |\n\n**资料来源：** [ompa/config.py](ompa/config.py)()\n\n### Vault Targets\n\n```mermaid\ngraph LR\n    MSG[Message] --> CLASSIFY[Classifier]\n    CLASSIFY --> TARGET{IsolationMode}\n    TARGET -->|AUTO| AUTO[Auto-classify]\n    TARGET -->|MANUAL| MANUAL[Manual VaultTarget]\n    TARGET -->|STRICT| STRICT[Strict Mode]\n    \n    AUTO --> SHARED[Shared Vault]\n    AUTO --> PERSONAL[Personal Vault]\n    MANUAL --> SHARED\n    MANUAL --> PERSONAL\n```\n\n### Configuration\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\nao = Ompa(config=config)\n```\n\n**资料来源：** [README.md](README.md)()\n\n### Export/Sanitization\n\nWhen exporting content from personal to shared vault, OMPA automatically sanitizes sensitive information:\n\n- `sk-*` (OpenAI-style API keys)\n- `AKIA*` (AWS access key IDs)\n- `token:`, `password:`, `secret:`, `api_key:`, `api-key:` patterns\n\n**资料来源：** [SECURITY_AUDIT.md](SECURITY_AUDIT.md)()\n\n## Security: Path Traversal Protection\n\nAll vault file operations resolve and boundary-check paths against the vault root before proceeding. This prevents malicious or accidental file access outside the designated vault directory.\n\n### Implementation\n\n| Function | Purpose |\n|----------|---------|\n| `_safe_resolve(vault_root, user_path)` | Resolves path and validates boundaries |\n| Path boundary checks | Raise `ValueError` if path escapes vault root |\n\n**Flow:**\n```mermaid\ngraph TD\n    INPUT[User Path Input] --> RESOLVE[_safe_resolve]\n    RESOLVE --> CHECK{Within Vault Root?}\n    CHECK -->|Yes| PROCEED[Proceed with Operation]\n    CHECK -->|No| REJECT[Raise ValueError]\n```\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)(), [SECURITY_AUDIT.md](SECURITY_AUDIT.md)()\n\n## Note Storage Format\n\nNotes are stored as Markdown files with YAML frontmatter.\n\n### Frontmatter Structure\n\n```yaml\n---\ndate: 2025-06-01\ntags: [tag1, tag2]\nvault: shared  # or \"personal\"\n---\n```\n\n**Content follows frontmatter**\n\n**资料来源：** [ompa/core.py](ompa/core.py)()\n\n### File Naming\n\nWhen creating notes automatically, the system:\n1. Uses the classifier to determine the appropriate folder\n2. Sanitizes content for filename generation\n3. Creates a kebab-case filename from the first 40 characters\n\n**资料来源：** [ompa/core.py](ompa/core.py)()\n\n## Semantic Index\n\nThe `SemanticIndex` class provides local semantic search capabilities using sentence transformers.\n\n### Lazy Initialization\n\nThe embedding model is not loaded until first access, preventing unnecessary downloads during import.\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)()\n\n### Incremental Updates\n\nThe semantic index tracks file modification times and only re-embeds changed notes during rebuilds.\n\n```mermaid\ngraph TD\n    REBUILD[Rebuild Index] --> CHECK{File Changed?}\n    CHECK -->|Modified| RE_EMBED[Re-embed Content]\n    CHECK -->|Unchanged| SKIP[Skip File]\n    RE_EMBED --> UPDATE[Update Index]\n```\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)()\n\n## Knowledge Graph Integration\n\nThe vault integrates with the temporal knowledge graph through automatic population from note content.\n\n### Population Sources\n\n| Source | Description |\n|--------|-------------|\n| Frontmatter tags | Extracted as entities |\n| Folder paths | Used for context |\n| Wikilinks `[[...]]` | Resolved as entity relationships |\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)()\n\n### Triple Extraction\n\nNotes automatically contribute triples to the knowledge graph with:\n- Subject: Extracted entity\n- Predicate: Relationship type\n- Object: Related entity\n- Validity window: Based on note dates\n\n**资料来源：** [ompa/knowledge_graph.py](ompa/knowledge_graph.py)()\n\n## CLI Commands\n\n### Vault Operations\n\n| Command | Description |\n|---------|-------------|\n| `ao init` | Initialize a new vault with required structure |\n| `ao status` | Display vault health check and statistics |\n| `ao validate` | Validate vault structure integrity |\n| `ao orphans` | Detect notes with broken wikilinks |\n| `ao rebuild-index` | Rebuild the semantic search index |\n\n**资料来源：** [README.md](README.md)()\n\n### Index and Search\n\n| Command | Description |\n|---------|-------------|\n| `ao search <query>` | Perform semantic search across notes |\n| `ao kg-query <entity>` | Query knowledge graph for entity |\n| `ao kg-stats` | Display knowledge graph statistics |\n\n**资料来源：** [README.md](README.md)()\n\n## Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n\n**资料来源：** [examples/mcp_desktop/README.md](examples/mcp_desktop/README.md)()\n\n## MCP Server Integration\n\nThe vault is accessible through MCP (Model Context Protocol) tools when integrated with AI assistants.\n\n### Available Tools\n\n```python\nao_init         # Initialize vault\nao_status       # Health check\nao_write        # Write note to vault\nao_export       # Export between vaults\nao_import       # Import into vault\nao_orphans      # Detect orphaned notes\nao_validate     # Validate structure\n```\n\n**资料来源：** [ompa/mcp_server.py](ompa/mcp_server.py)()\n\n## Encoding and Storage\n\nAll vault file writes explicitly enforce UTF-8 encoding to ensure cross-platform compatibility and proper handling of international characters.\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)()\n\n## Class Hierarchy\n\n```mermaid\nclassDiagram\n    class Vault {\n        +vault_path: str\n        +notes: list~Note~\n        +create_note()\n        +read_note()\n        +update_note()\n        +delete_note()\n        +list_notes()\n    }\n    \n    class Note {\n        +path: Path\n        +frontmatter: dict\n        +content: str\n        +save()\n        +load()\n    }\n    \n    class SemanticIndex {\n        +_model: EmbeddingModel\n        +embed()\n        +search()\n        +rebuild()\n    }\n    \n    class KnowledgeGraph {\n        +add_triple()\n        +query_entity()\n        +populate_from_vault()\n    }\n    \n    Vault --> Note\n    Vault --> SemanticIndex\n    Vault --> KnowledgeGraph\n```\n\n## Workflow: Session Lifecycle\n\n```mermaid\ngraph TD\n    START[Session Start] --> CONTEXT[ao.session_start]\n    CONTEXT --> CLASSIFY[Message Classification]\n    CLASSIFY --> HANDLE[ao.handle_message]\n    HANDLE --> WRITE[Write to Vault]\n    WRITE --> INDEX[Update Semantic Index]\n    INDEX --> KG[Update Knowledge Graph]\n    KG --> TOOL[Post-tool Hook]\n    TOOL --> WRAP[ao.wrap_up]\n    WRAP --> STOP[ao.stop]\n```\n\n**资料来源：** [ompa/core.py](ompa/core.py)(), [README.md](README.md)()\n\n## Related Documentation\n\n- [Core System](ompa/core.py) — Main Ompa class integrating vault\n- [Classifier System](ompa/classifier.py) — Message classification and routing\n- [Knowledge Graph](ompa/knowledge_graph.py) — Temporal triple storage\n- [Semantic Search](ompa/semantic.py) — Local embedding-based search\n- [MCP Server](ompa/mcp_server.py) — Protocol integration for AI assistants\n\n---\n\n<a id='palace-system'></a>\n\n## Palace System\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Vault System](#vault-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/palace.py](https://github.com/jmiaie/ompa/blob/main/ompa/palace.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n- [ompa/cli.py](https://github.com/jmiaie/ompa/blob/main/ompa/cli.py)\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n</details>\n\n# Palace System\n\nThe Palace System is a metadata layer within OMPA (Obsidian-MemPalace-Agnostic) that provides retrieval acceleration for information stored in the vault. It operates on top of the Vault layer, which serves as the source of truth for all notes, to enable efficient navigation and traversal of memory structures.\n\n## Overview\n\nThe Palace System implements a spatial metaphor for organizing and accessing notes, inspired by the memory palace technique. It provides hierarchical organizational structures (wings, rooms, drawers, halls) and traversal mechanisms (tunnels) that allow agents to navigate complex information spaces efficiently.\n\nThe system follows the architecture decision that the Vault serves as the source of truth while the Palace provides retrieval acceleration. This dual-layer design ensures data persistence alongside fast access patterns.\n\n资料来源：[CLAUDE.md:3]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph OMPA[\"OMPA Core\"]\n        subgraph VaultLayer[\"Vault Layer\"]\n            V[Vault - Source of Truth]\n        end\n        subgraph PalaceLayer[\"Palace Layer - Retrieval Acceleration\"]\n            W[Wings]\n            R[Rooms]\n            D[Drawers]\n            H[Halls]\n            T[Tunnels]\n        end\n    end\n    U[User/Agent] --> API\n    API[CLI / MCP / Python API]\n    API --> PalaceLayer\n    PalaceLayer --> VaultLayer\n```\n\n### Core Components\n\n| Component | Purpose | Storage |\n|-----------|--------|---------|\n| Wings | Top-level organizational units | SQLite metadata |\n| Rooms | Sub-categories within wings | SQLite metadata |\n| Drawers | Fine-grained containers | SQLite metadata |\n| Halls | High-traffic connection paths | SQLite metadata |\n| Tunnels | Cross-wing navigation shortcuts | SQLite metadata |\n\n资料来源：[README.md:1]()\n\n## Palace Metadata Storage\n\nThe Palace System uses SQLite for storing all metadata, with connections managed via context managers to prevent leaks. All temporal data supports validity windows, allowing the system to track how structures evolve over time.\n\n```python\n# Temporal KG with validity windows\n# From ompa/knowledge_graph.py pattern\n```\n\nThe architecture follows lazy semantic loading principles, where palace structures are initialized on first access rather than at import time.\n\n资料来源：[CLAUDE.md:3]()\n\n## Wing Management\n\nWings represent the top-level organizational units in the Palace System. Each wing can contain multiple rooms and serves as a primary navigation anchor.\n\n### Creating Wings\n\n```python\nao.palace.create_wing(\"Orion\")\n```\n\n### Listing Wings\n\n```python\nwings = ao.palace.list_wings()\n```\n\n### Wing Operations via CLI\n\n```bash\nao wings  # List all palace wings\n```\n\n资料来源：[README.md:1]()\n资料来源：[ompa/cli.py](https://github.com/jmiaie/ompa/blob/main/ompa/cli.py)\n\n## Room Management\n\nRooms are sub-categories that belong to specific wings. They provide a second level of hierarchy for organizing palace structures.\n\n### Listing Rooms in a Wing\n\n```python\nrooms = ao.palace.list_rooms(\"Orion\")\n```\n\n### Room Operations via CLI\n\n```bash\nao rooms <wing>  # List rooms in a specific wing\n```\n\n资料来源：[README.md:1]()\n\n## Tunnel System\n\nTunnels enable cross-wing navigation, creating shortcuts between different wings of the palace. This allows agents to traverse between seemingly unrelated areas efficiently.\n\n### Creating Tunnels\n\n```python\nao.palace.create_tunnel(wing_a, wing_b, room=\"shared\")\n```\n\n### Tunnel Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| wing_a | str | Yes | Source wing identifier |\n| wing_b | str | Yes | Target wing identifier |\n| room | str | No | Room through which tunnel passes (default: \"shared\") |\n\n### CLI Tunnel Command\n\n```bash\nao tunnel  # Create/traverse cross-wing tunnel\n```\n\n资料来源：[README.md:1]()\n\n## MCP Server Integration\n\nThe Palace System is exposed via the MCP (Model Context Protocol) server, allowing integration with AI agents like Claude Code, Cursor, and Windsurf.\n\n### Available MCP Tools\n\n| Tool Name | Function | Source |\n|-----------|----------|--------|\n| `ao_palace_wings` | List all palace wings | mcp_server.py:70-73 |\n| `ao_palace_rooms` | List rooms in a wing | mcp_server.py:75-79 |\n| `ao_palace_tunnel` | Create tunnel between wings | mcp_server.py:81-89 |\n\n### MCP Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"/path/to/vault\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[examples/mcp_desktop/README.md:1]()\n\n## CLI Commands\n\nThe Palace System can be accessed through the `ao` CLI utility:\n\n```bash\n# List all palace wings\nao wings\n\n# List rooms in a specific wing\nao rooms <wing>\n\n# Create or traverse a tunnel\nao tunnel\n```\n\n资料来源：[README.md:1]()\n\n## Integration with Core OMPA\n\nThe Palace System is instantiated as part of the main `Ompa` class:\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(vault_path=\"./workspace\")\n# Palace is available at ao.palace\nwings = ao.palace.list_wings()\n```\n\nThe `Ompa` class manages the lifecycle of the Palace instance, ensuring it shares the same vault path and configuration.\n\n资料来源：[ompa/core.py:1]()\n\n## Statistics and Monitoring\n\nThe Palace System provides statistics about its current state:\n\n```python\n# Via Python API\nstats = ao.palace.stats()\n\n# Via MCP\nresult = ao_palace_stats(vault_path)\n\n# Via CLI (combined with vault and KG stats)\nao status\n```\n\nThe status command returns a combined view of vault health, palace metadata, and knowledge graph statistics.\n\n资料来源：[ompa/mcp_server.py:70-73]()\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI\n    participant MCP\n    participant Ompa\n    participant Palace\n    participant Vault\n    participant SQLite\n    \n    User->>CLI: ao wings\n    CLI->>Ompa: list_wings()\n    Ompa->>Palace: list_wings()\n    Palace->>SQLite: Query wings metadata\n    SQLite-->>Palace: Wing list\n    Palace-->>Ompa: Wing list\n    Ompa-->>CLI: Wing list\n    CLI-->>User: Display wings\n    \n    User->>MCP: ao_palace_rooms(wing=\"Orion\")\n    MCP->>Ompa: list_rooms(\"Orion\")\n    Ompa->>Palace: list_rooms()\n    Palace->>SQLite: Query rooms WHERE wing=\"Orion\"\n    SQLite-->>Palace: Room list\n    Palace-->>Ompa: Room list\n    Ompa-->>MCP: Room list\n    MCP-->>User: Display rooms\n```\n\n## Design Principles\n\n1. **Vault + Palace Dual-Layer**: The vault serves as the source of truth while the palace provides retrieval acceleration\n2. **Context Managers**: All SQLite connections use `with` statements for leak-free operation\n3. **Lazy Initialization**: Palace structures are loaded on first access rather than at import time\n4. **Temporal Support**: Palace metadata supports validity windows for tracking structural changes over time\n\n资料来源：[CLAUDE.md:3]()\n\n## See Also\n\n- [Vault System](vault.md) - Source of truth layer\n- [Knowledge Graph](knowledge_graph.md) - Temporal triple storage\n- [Classifier](classifier.md) - Message type classification and routing\n- [MCP Server Setup](examples/mcp_desktop/README.md) - Agent integration guide\n\n---\n\n<a id='knowledge-graph'></a>\n\n## Knowledge Graph\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Palace System](#palace-system)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n- [ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n</details>\n\n# Knowledge Graph\n\nThe Knowledge Graph (KG) is a core temporal data storage component in OMPA that maintains structured relationships between entities using SQLite-backed triple storage. It enables agents to query historical information, track entity validity windows, and maintain a persistent memory of facts across sessions.\n\n## Overview\n\nThe Knowledge Graph stores facts as **triples** (subject, predicate, object) with temporal validity windows, allowing queries like \"What was the state of X at time Y?\" or \"Show me all relationships involving entity Z.\"\n\n| Property | Value |\n|----------|-------|\n| Storage Backend | SQLite |\n| Data Model | RDF-like triples with validity windows |\n| Temporal Support | `valid_from` / `valid_to` timestamps |\n| Location | `~/.ompa/knowledge_graph.db` |\n| Population | Auto-populates from vault notes and wikilinks |\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Vault Notes] --> B[populate_from_vault]\n    C[User Message] --> D[add_triple]\n    B --> E[(SQLite DB)]\n    D --> E\n    E --> F[query_entity]\n    E --> G[timeline]\n    E --> H[get_predicates]\n    E --> I[stats]\n    F --> J[Triple Results]\n    G --> K[Timeline View]\n    I --> L[Statistics]\n```\n\nThe KG operates as a layer above the vault, extracting structured data from unstructured notes and providing temporal query capabilities.\n\n资料来源：[ompa/core.py:1-50](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n\n## Core Data Model\n\n### Triple Structure\n\nEach fact in the Knowledge Graph is stored as a triple with temporal metadata:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `subject` | str | Entity name (e.g., \"Kai\", \"Orion\") |\n| `predicate` | str | Relationship type (e.g., \"works_on\", \"owns\") |\n| `object` | str | Target entity or value |\n| `valid_from` | datetime | Start of validity period (nullable) |\n| `valid_to` | datetime | End of validity period (nullable) |\n| `source` | str | Note path that contained this fact |\n\n### Temporal Validity Windows\n\nThe KG supports temporal reasoning through validity windows:\n\n- **Point-in-time facts**: Both `valid_from` and `valid_to` set\n- **Current facts**: Only `valid_from` set (open-ended)\n- **Historical facts**: Both timestamps set to past dates\n\nThis enables queries like retrieving the state of relationships at any past point.\n\n资料来源：[ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n\n## KnowledgeGraph API\n\n### Constructor\n\n```python\nclass KnowledgeGraph:\n    def __init__(self, vault_path: str = \"~/.ompa\"):\n        self.db_path = Path(vault_path) / \"knowledge_graph.db\"\n```\n\nInitializes the KG with a database path under the OMPA config directory. The SQLite database is created automatically on first access.\n\n资料来源：[ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n\n### add_triple\n\nAdds a new fact to the knowledge graph:\n\n```python\ndef add_triple(\n    self,\n    subject: str,\n    predicate: str,\n    object_: str,\n    valid_from: str | None = None,\n    source: str | None = None,\n) -> Triple:\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `subject` | str | Yes | Source entity |\n| `predicate` | str | Yes | Relationship verb |\n| `object_` | str | Yes | Target entity/value |\n| `valid_from` | str | No | ISO date string for start validity |\n| `source` | str | No | Source note path |\n\n**Example:**\n```python\nkg.add_triple(\n    subject=\"Kai\",\n    predicate=\"works_on\",\n    object_=\"Orion\",\n    valid_from=\"2025-06-01\",\n    source=\"brain/people/Kai.md\"\n)\n```\n\n资料来源：[ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n\n### query_entity\n\nRetrieves all triples involving a specific entity:\n\n```python\ndef query_entity(self, entity: str) -> list[Triple]:\n```\n\nReturns all triples where the entity appears as subject or object. Results are ordered by validity window.\n\n### timeline\n\nGets temporal history for an entity:\n\n```python\ndef timeline(self, entity: str) -> list[dict]:\n```\n\nReturns a chronological view of all facts involving the entity, including temporal metadata for each relationship.\n\n### get_predicates\n\nLists all relationship types in the graph:\n\n```python\ndef get_predicates(self, subject: str | None = None) -> list[str]:\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `subject` | str | No | Filter predicates by subject |\n\n### stats\n\nReturns knowledge graph statistics:\n\n```python\ndef stats(self) -> dict:\n```\n\nReturns:\n| Stat | Description |\n|------|-------------|\n| `total_triples` | Total number of stored facts |\n| `unique_subjects` | Count of unique source entities |\n| `unique_predicates` | Count of unique relationship types |\n| `unique_objects` | Count of unique target entities |\n\n### populate_from_vault\n\nScans existing vault notes and extracts structured facts:\n\n```python\ndef populate_from_vault(self, vault_path: str) -> dict:\n```\n\nExtracts entities from:\n- Frontmatter tags\n- Folder paths\n- `[[wikilinks]]` cross-references\n\nThis enables automatic KG initialization from existing note content.\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## MCP Server Integration\n\nThe Knowledge Graph is exposed through MCP tools for agent integration:\n\n```mermaid\ngraph LR\n    A[MCP Client] -->|ao_kg_add| B[Add Triple]\n    A -->|ao_kg_query| C[Query Entity]\n    A -->|ao_kg_stats| D[Get Stats]\n    A -->|ao_kg_populate| E[Populate from Vault]\n    B --> F[KnowledgeGraph]\n    C --> F\n    D --> F\n    E --> F\n```\n\n### Available MCP Tools\n\n| Tool | Parameters | Description |\n|------|------------|-------------|\n| `ao_kg_add` | `subject`, `predicate`, `object_`, `valid_from?`, `source?` | Add a fact |\n| `ao_kg_query` | `entity` | Query entity relationships |\n| `ao_kg_stats` | — | Get KG statistics |\n\n资料来源：[ompa/mcp_server.py:1-50](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n\n### MCP Tool Implementation\n\n```python\ndef ao_kg_add(arguments: dict, vault_path: str = \".\") -> dict:\n    \"\"\"Add a triple to the knowledge graph.\"\"\"\n    ao = Ompa(vault_path=vault_path, enable_semantic=False)\n    ao.kg.add_triple(\n        subject=arguments[\"subject\"],\n        predicate=arguments[\"predicate\"],\n        object_=arguments[\"object\"],\n        valid_from=arguments.get(\"valid_from\"),\n        source=arguments.get(\"source\"),\n        vault_path=vault_path,\n    )\n    return {\"success\": True, \"added\": f\"{subject} --{predicate}--> {object_}\"}\n\ndef ao_kg_stats(vault_path: str = \".\") -> dict:\n    \"\"\"Get knowledge graph statistics.\"\"\"\n    ao = Ompa(vault_path=vault_path, enable_semantic=False)\n    return ao.kg.stats()\n```\n\n资料来源：[ompa/mcp_server.py:50-100](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n\n## Usage Examples\n\n### Python API\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(vault_path=\"./workspace\")\n\n# Add facts\nao.kg.add_triple(\"Kai\", \"works_on\", \"Orion\", valid_from=\"2025-06-01\")\nao.kg.add_triple(\"Orion\", \"has_status\", \"active\")\nao.kg.add_triple(\"Kai\", \"reports_to\", \"Sarah\")\n\n# Query entity\ntriples = ao.kg.query_entity(\"Kai\")\n# Returns: [Triple(subject='Kai', predicate='works_on', object_='Orion', ...), ...]\n\n# Get timeline\ntimeline = ao.kg.timeline(\"Kai\")\n# Returns chronological history of all Kai-related facts\n\n# Get statistics\nstats = ao.kg.stats()\n# Returns: {'total_triples': 3, 'unique_subjects': 2, 'unique_predicates': 3, ...}\n```\n\n### CLI Usage\n\n```bash\n# Query entity in knowledge graph\nao kg-query Kai\n\n# Get entity timeline\nao kg-timeline Orion\n\n# Get knowledge graph statistics\nao kg-stats\n```\n\n### MCP Integration\n\nIn Claude Desktop or Cursor, the KG tools are available as:\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"/absolute/path/to/vault\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n## Relationship to Other Components\n\n```mermaid\ngraph TD\n    subgraph OMPA Core\n        A[Ompa Class] --> B[KnowledgeGraph]\n        A --> C[Vault]\n        A --> D[SemanticIndex]\n        A --> E[Palace]\n    end\n    \n    B --> F[(SQLite DB)]\n    C --> G[Markdown Notes]\n    D --> H[Sentence Embeddings]\n    E --> I[Metadata Cache]\n    \n    J[MCP Server] --> B\n    J --> C\n    J --> D\n    J --> E\n```\n\n| Component | Relationship | Data Flow |\n|-----------|--------------|-----------|\n| **Vault** | Source of truth | KG populates from vault wikilinks and tags |\n| **SemanticIndex** | Companion retrieval | KG + Index together enable hybrid search |\n| **Palace** | Metadata layer | Palace stores spatial metadata for navigation |\n| **Classifier** | Auto-tagging | Classifier helps route content to vault locations |\n\nThe Knowledge Graph complements the vault by adding structure to unstructured note content.\n\n资料来源：[ompa/core.py:1-100](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n\n## Security Considerations\n\n- **Path traversal guards**: All vault file operations resolve and boundary-check paths\n- **SQLite isolation**: Each KG instance uses separate database file\n- **Source tracking**: Every triple records its source note for auditability\n\n资料来源：[CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Changelog\n\n| Version | Date | Change |\n|---------|------|--------|\n| 0.4.0 | 2026-04-10 | Added `populate_from_vault()` for auto-extraction |\n| 0.3.0 | 2026-04-08 | Initial KG implementation with temporal windows |\n| 0.3.1 | 2026-04-09 | Bug fixes in wikilink resolution |\n\n资料来源：[CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n---\n\n<a id='message-classification'></a>\n\n## Message Classification\n\n### 相关页面\n\n相关主题：[Vault System](#vault-system), [Python API Reference](#python-api)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n</details>\n\n# Message Classification\n\nMessage Classification is a core feature of OMPA that automatically categorizes incoming messages into 15 distinct types and routes them to appropriate locations within the vault structure. This system enables intelligent, automated memory management for AI agents working across different contexts.\n\n## Overview\n\nThe classifier uses regex pattern matching to identify message types based on linguistic cues, then provides routing hints to guide content placement. It integrates deeply with the vault architecture, suggesting target folders and actions for each classified message type.\n\n资料来源：[ompa/classifier.py:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Incoming Message] --> B[Classifier.classify]\n    B --> C{Pattern Matching}\n    C -->|Decision| D[MessageType.DECISION]\n    C -->|Incident| E[MessageType.INCIDENT]\n    C -->|Meeting| F[MessageType.MEETING]\n    C -->|Win| G[MessageType.WIN]\n    C -->|...| H[Other Types]\n    \n    D --> I[Routing Hints]\n    E --> I\n    F --> I\n    G --> I\n    H --> I\n    \n    I --> J[Suggested Folder]\n    I --> K[Suggested Action]\n    \n    J --> L[Vault Storage]\n    K --> M[Knowledge Graph]\n```\n\n资料来源：[ompa/classifier.py:60-120]()\n\n## Message Types\n\nOMPA defines 15 distinct `MessageType` values for classifying different kinds of agent communications:\n\n| Message Type | Purpose | Suggested Folder |\n|--------------|---------|------------------|\n| `DECISION` | Architectural or team decisions | `brain/` |\n| `INCIDENT` | Outages, bugs, failures, debugging | `work/incidents/` |\n| `WIN` | Achievements, successes, milestones | `perf/` |\n| `ONE_ON_ONE` | Manager/peer check-ins | `work/1-1/` |\n| `MEETING` | Meeting notes and takeaways | `work/meetings/` |\n| `PROJECT_UPDATE` | Project status changes | `work/active/` |\n| `PERSON_INFO` | Team member information | `org/people/` |\n| `QUESTION` | Clarifying questions | `brain/questions/` |\n| `TASK` | Action items and todos | `work/tasks/` |\n| `ARCHITECTURE` | System design decisions | `brain/architecture/` |\n| `CODE` | Code-related discussions | `work/code/` |\n| `BRAIN_DUMP` | Stream of consciousness notes | `brain/dumps/` |\n| `WRAP_UP` | Session end summaries | `brain/sessions/` |\n| `STANDUP` | Daily standup entries | `work/standups/` |\n| `GENERAL` | Uncategorized content | `brain/` |\n\n资料来源：[ompa/classifier.py:1-30]()\n资料来源：[CLAUDE.md:1-20]()\n\n## Pattern Matching System\n\nThe classifier uses regex patterns to identify message types. Each `MessageType` has an associated list of regex patterns:\n\n```python\nPATTERNS = {\n    MessageType.DECISION: [\n        r\"\\b(decided|decision|made a choice|going with|settled on|agreed to)\\b\",\n        r\"\\b(defer|postpone|push to|revisit)\\b.*\\b(Q\\d|quarter|sprint)\\b\",\n        r\"(?:ADR|decision record)\",\n    ],\n    MessageType.INCIDENT: [\n        r\"\\b(incident|outage|bug|crash|failure|error|broken)\\b\",\n        r\"\\b(debug|root cause|RCA|mitigation|hotfix)\\b\",\n        r\"(?:on-call|pagerduty|statuspage)\",\n    ],\n    MessageType.WIN: [\n        r\"\\b(won|praised|success|achieved|shipped|launched|deployed)\\b\",\n        r\"\\b(great work|nice job|excellent|well done)\\b\",\n        r\"\\b(milestone|feature complete|released)\\b\",\n    ],\n    # ... additional patterns\n}\n```\n\n资料来源：[ompa/classifier.py:30-100]()\n\n### Pattern Priority\n\nPatterns are evaluated in order, and the first matching pattern determines the message type. This allows for specific patterns to take precedence over general ones.\n\n## Routing Hints\n\nEach message type includes `ROUTING_HINTS` that provide guidance on how to handle classified content:\n\n```python\nROUTING_HINTS = {\n    MessageType.DECISION: [\n        \"This is a decision. Record it in brain/Key Decisions.md\",\n        \"Update relevant project notes with the decision\",\n        \"Add to Decision Log if formal ADR needed\",\n    ],\n    MessageType.INCIDENT: [\n        \"Create incident note in work/incidents/\",\n        \"Run /om-incident-capture for structured capture\",\n        \"Update brain/Gotchas.md with lessons learned\",\n    ],\n    MessageType.WIN: [\n        \"Add to perf/Brag Doc.md immediately\",\n        \"This is a win worth capturing for performance review\",\n        \"Update relevant competency notes with evidence\",\n    ],\n    # ... additional hints\n}\n```\n\n资料来源：[ompa/classifier.py:100-180]()\n\n## Classification API\n\n### Core Classification Method\n\n```python\nfrom ompa.classifier import Classifier, Classification\n\nclassifier = Classifier()\nresult: Classification = classifier.classify(\"We decided to go with Postgres\")\n```\n\n### Return Type\n\nThe `classify()` method returns a `Classification` object containing:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `message_type` | `MessageType` | The identified message type |\n| `confidence` | `float` | Confidence score (0.0 - 1.0) |\n| `routing_hints` | `List[str]` | Actionable suggestions |\n| `suggested_folder` | `str` | Target folder for storage |\n\n资料来源：[ompa/classifier.py:120-150]()\n资料来源：[STABILITY.md:10-20]()\n\n## Dual-Vault Integration\n\nWhen running in dual-vault mode, the classifier also supports content classification for vault routing:\n\n```python\nfrom ompa.config import DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\n\ntarget = config.classify_content(content, tags=tags, file_path=path)\n```\n\n资料来源：[ompa/core.py:50-80]()\n\n### Classification Factors\n\nContent is classified to shared or personal vaults based on:\n\n1. **Content analysis** - Keywords indicating personal vs. work content\n2. **Tags** - Frontmatter tags that may indicate classification\n3. **File path** - Existing location hints in vault structure\n\n## Adding Custom Message Types\n\nTo extend the classifier with new message types, follow this process:\n\n### Step 1: Add Enum Value\n\n```python\n# ompa/classifier.py\nclass MessageType(str, Enum):\n    # ... existing types\n    YOUR_NEW_TYPE = \"your_new_type\"\n```\n\n### Step 2: Add Regex Patterns\n\n```python\nPATTERNS[MessageType.YOUR_NEW_TYPE] = [\n    r\"\\b(keyword1|keyword2)\\b\",\n    r\"\\b(phrase pattern)\\b\",\n]\n```\n\n### Step 3: Add Routing Hints\n\n```python\nROUTING_HINTS[MessageType.YOUR_NEW_TYPE] = [\n    \"Action hint 1\",\n    \"Action hint 2\",\n]\n```\n\n### Step 4: Add Folder Mapping\n\n```python\nFOLDER_MAP[MessageType.YOUR_NEW_TYPE] = \"brain/your-type/\"\n```\n\n### Step 5: Add Tests\n\n```python\n# tests/test_ompa.py\nclass TestClassifier:\n    def test_your_new_type(self):\n        # Add test cases\n```\n\n资料来源：[CONTRIBUTING.md:20-40]()\n\n## CLI Integration\n\nThe classifier is accessible via the CLI:\n\n```bash\n# Classify a single message\nao classify \"We decided to go with Postgres\"\n\n# Classify with context\nao classify \"The deployment failed with a timeout error\"\n```\n\n## MCP Tools\n\nThe following MCP tools expose classification functionality:\n\n| Tool | Purpose |\n|------|---------|\n| `ao_classify` | Classify a message and return routing hints |\n\n资料来源：[ompa/mcp_server.py:1-30]()\n\n## Confidence Scoring\n\nThe classifier assigns confidence scores based on:\n\n1. **Pattern match count** - More pattern matches = higher confidence\n2. **Pattern specificity** - More specific patterns score higher\n3. **Keyword density** - Higher density of type-specific keywords\n\nConfidence is normalized to a 0.0-1.0 range for downstream processing.\n\n## Extensibility Points\n\nThe classification system can be extended through:\n\n1. **Custom patterns** - Add regex patterns per message type\n2. **Custom routing hints** - Extend action suggestions\n3. **Custom folders** - Define target locations per type\n4. **Hook integration** - Execute hooks on classification events\n\n资料来源：[CLAUDE.md:30-50]()\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI as CLI/API\n    participant Classifier\n    participant Vault\n    participant KG as Knowledge Graph\n    \n    User->>CLI: ao classify \"message\"\n    CLI->>Classifier: classify(message)\n    Classifier->>Classifier: Pattern matching\n    Classifier-->>CLI: Classification result\n    CLI-->>User: Type + routing hints\n    \n    User->>CLI: ao handle_message \"message\"\n    CLI->>Classifier: classify(message)\n    Classifier-->>CLI: Classification + folder\n    CLI->>Vault: Save to suggested folder\n    CLI->>KG: Add extracted entities\n    Vault-->>CLI: Note saved\n    KG-->>CLI: Triples added\n```\n\nThis comprehensive classification system enables OMPA to automatically organize agent communications, maintain structured memory, and provide intelligent routing for all types of work content.\n\n---\n\n<a id='python-api'></a>\n\n## Python API Reference\n\n### 相关页面\n\n相关主题：[Lifecycle Hooks](#lifecycle-hooks)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [ompa/__init__.py](https://github.com/jmiaie/ompa/blob/main/ompa/__init__.py)\n- [ompa/config.py](https://github.com/jmiaie/ompa/blob/main/ompa/config.py)\n- [ompa/async_api.py](https://github.com/jmiaie/ompa/blob/main/ompa/async_api.py)\n</details>\n\n# Python API Reference\n\nThe Python API provides programmatic access to OMPA's core functionality, enabling integration with AI agents, custom workflows, and external applications. The API is designed around the `Ompa` class as the primary entry point, offering lifecycle management, semantic search, knowledge graph operations, and dual-vault isolation.\n\n---\n\n## Installation and Setup\n\n```bash\n# Core package\npip install ompa\n\n# With semantic search (sentence-transformers)\npip install ompa[all]\n\n# Development installation\npip install ompa[dev]\n```\n\nRequires Python 3.10 or higher.\n\n---\n\n## Core Class: `Ompa`\n\nThe `Ompa` class is the main interface for all OMPA operations. It manages the vault, palace, knowledge graph, and lifecycle hooks.\n\n### Constructor\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(\n    vault_path=\"./workspace\",\n    agent_name=\"agent\",\n    enable_semantic=True,\n    embedding_backend=None,\n    shared_vault_path=None,\n    personal_vault_path=None,\n    isolation_mode=\"strict\",\n)\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `vault_path` | `str` | `\".\"` | Absolute path to vault directory |\n| `agent_name` | `str` | `\"agent\"` | Agent identifier for KG scoping |\n| `enable_semantic` | `bool` | `True` | Enable semantic search functionality |\n| `embedding_backend` | `EmbeddingBackend \\| None` | `None` | Custom embedding backend |\n| `shared_vault_path` | `str \\| None` | `None` | Path for shared vault (dual-vault mode) |\n| `personal_vault_path` | `str \\| None` | `None` | Path for personal vault (dual-vault mode) |\n| `isolation_mode` | `IsolationMode \\| str` | `\"strict\"` | Vault isolation mode |\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)()\n\n### Alternative Constructor: Dual-Vault Configuration\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\nao = Ompa(config=config)\n```\n\n---\n\n## Lifecycle Methods\n\nThe lifecycle API manages session boundaries and hook execution for AI agent memory integration.\n\n```mermaid\ngraph TD\n    A[session_start] --> B[handle_message / post_tool]\n    B --> C[pre_compact]\n    C --> D[stop / wrap_up]\n    D --> E[Session Complete]\n```\n\n### `session_start()`\n\nInjects memory context at the start of an agent session.\n\n```python\nresult = ao.session_start()\n```\n\n**Returns:** `HookResult` — Contains `success`, `output`, and `tokens_hint` fields.\n\n**Output:** Approximately 2,000 token context string with session history.\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)()\n\n### `handle_message(message: str)`\n\nProcess and classify an incoming message.\n\n```python\nresult = ao.handle_message(\"We decided to go with Postgres\")\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `message` | `str` | The message content to classify |\n\n**Returns:** `HookResult`\n\n资料来源：[ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)()\n\n### `post_tool(tool_name: str, tool_input: dict)`\n\nExecute after a tool call to record the action.\n\n```python\nresult = ao.post_tool(\"write\", {\"file_path\": \"work/active/auth.md\"})\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `tool_name` | `str` | Name of the executed tool |\n| `tool_input` | `dict` | Tool input parameters |\n\n**Returns:** `HookResult`\n\n### `pre_compact(transcript: str)`\n\nCalled before context compaction (context window reduction).\n\n```python\nresult = ao.pre_compact(transcript)\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `transcript` | `str` | Full session transcript |\n\n**Returns:** `HookResult`\n\n### `stop()` / `wrap_up()`\n\nEnd the session and persist state. `wrap_up()` is an alias for `stop()`.\n\n```python\nresult = ao.stop()\n# or\nresult = ao.wrap_up()\n```\n\n**Returns:** `HookResult` with session summary and persistence status.\n\n### `standup()`\n\nAlias for `session_start()`. Provides symmetry with `wrap_up()`.\n\n```python\nresult = ao.standup()\n```\n\n---\n\n## Search API\n\n### `search(query, limit, hybrid, wing, room, vaults)`\n\nPerform semantic search across vault notes.\n\n```python\nresults = ao.search(\n    \"authentication decisions\",\n    limit=10,\n    hybrid=True,\n    wing=\"Orion\",\n    room=None,\n    vaults=None\n)\n```\n\n**Parameters:**\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `query` | `str` | Required | Search query string |\n| `limit` | `int` | `5` | Maximum results to return |\n| `hybrid` | `bool` | `False` | Enable hybrid keyword + semantic search |\n| `wing` | `str \\| None` | `None` | Filter by palace wing |\n| `room` | `str \\| None` | `None` | Filter by palace room |\n| `vaults` | `list[str] \\| None` | `None` | Target specific vaults |\n\n**Returns:** `list[SearchResult]` — List of matching notes with relevance scores.\n\n**Cost:** Zero API cost (local semantic search).\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)()\n\n### `rebuild_index()`\n\nRebuild the semantic index from vault contents.\n\n```python\ncount = ao.rebuild_index()\n```\n\n**Returns:** `int` — Number of notes indexed.\n\n---\n\n## Classification API\n\n### `classify(message: str)`\n\nClassify a message into one of 15 message types.\n\n```python\nclassification = ao.classify(\"We decided to go with Postgres\")\n```\n\n**Returns:** `Classification` — Contains `message_type`, `confidence`, `suggested_folder`, and routing hints.\n\n### `get_routing_hint(message: str)`\n\nGet routing hints for a message.\n\n```python\nhint = ao.get_routing_hint(\"We won the enterprise deal!\")\n```\n\n**Returns:** `str` — Routing hint for vault placement.\n\n---\n\n## Knowledge Graph API\n\nThe temporal knowledge graph stores entity relationships with validity windows.\n\n```mermaid\ngraph LR\n    A[Subject] -->|Predicate| B[Object]\n    B -->|valid_from| C[Start Date]\n    B -->|valid_to| D[End Date]\n```\n\n### `kg.add_triple(subject, predicate, object, valid_from, source)`\n\nAdd a triple to the knowledge graph.\n\n```python\nao.kg.add_triple(\n    \"Kai\",\n    \"works_on\",\n    \"Orion\",\n    valid_from=\"2025-06-01\",\n    source=\"session\"\n)\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `subject` | `str` | Source entity |\n| `predicate` | `str` | Relationship type |\n| `object` | `str` | Target entity |\n| `valid_from` | `str \\| None` | Validity start date (YYYY-MM-DD) |\n| `valid_to` | `str \\| None` | Validity end date (YYYY-MM-DD) |\n| `source` | `str \\| None` | Source of this knowledge |\n\n### `kg.query_entity(entity, as_of)`\n\nQuery an entity's history at a point in time.\n\n```python\ntriples = ao.kg.query_entity(\"Kai\")\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `entity` | `str` | Entity name to query |\n| `as_of` | `str \\| None` | Point-in-time filter (YYYY-MM-DD) |\n\n**Returns:** `list[Triple]` — All triples involving the entity.\n\n### `kg.timeline(entity)`\n\nGet timeline of an entity's relationships.\n\n```python\ntimeline = ao.kg.timeline(\"Orion\")\n```\n\n**Returns:** `list[dict]` — Chronological relationship history.\n\n### `kg.stats()`\n\nGet knowledge graph statistics.\n\n```python\nstats = ao.kg.stats()\n```\n\n**Returns:** `dict` — Contains `triple_count`, `entity_count`, `predicate_types`, etc.\n\n---\n\n## Palace API\n\nThe palace provides spatial organization for memories using a metaphor of wings, rooms, drawers, halls, and tunnels.\n\n### `palace.create_wing(name)`\n\nCreate a new wing.\n\n```python\nao.palace.create_wing(\"Orion\")\n```\n\n### `palace.list_wings()`\n\nList all wings.\n\n```python\nwings = ao.palace.list_wings()\n```\n\n### `palace.create_tunnel(wing_a, wing_b, room)`\n\nCreate a cross-wing tunnel for navigation.\n\n```python\nao.palace.create_tunnel(\"Alpha\", \"Beta\", \"Central Hub\")\n```\n\n### `palace.stats()`\n\nGet palace statistics.\n\n```python\nstats = ao.palace.stats()\n```\n\n---\n\n## Vault API\n\n### `get_stats()`\n\nGet vault statistics.\n\n```python\nstats = ao.get_stats()\n```\n\n**Returns:** `dict` containing:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `total_notes` | `int` | Total note count |\n| `brain_notes` | `int` | Brain note count |\n| `by_folder` | `dict` | Notes per folder |\n\n### `write(content, file_path, tags, vault)`\n\nWrite a note to the vault.\n\n```python\nresult = ao.write(\n    content=\"# Decision\\n\\nUsing PostgreSQL\",\n    file_path=\"work/active/db-choice.md\",\n    tags=[\"decision\", \"database\"],\n    vault=None\n)\n```\n\n### `export_to_shared(note_path, confirm, sanitize)`\n\nExport a note from personal vault to shared vault.\n\n```python\nresult = ao.export_to_shared(\n    note_path=\"work/active/auth.md\",\n    confirm=True,\n    sanitize=True\n)\n```\n\n### `import_to_personal(note_path, link_back)`\n\nImport a note from shared vault to personal vault.\n\n```python\nresult = ao.import_to_personal(\n    note_path=\"work/active/auth.md\",\n    link_back=True\n)\n```\n\n### `find_orphans()`\n\nDetect orphaned notes (notes not linked from anywhere).\n\n```python\norphans = ao.find_orphans()\n```\n\n**Returns:** `list[Note]` — Orphaned note objects.\n\n---\n\n## Hooks System\n\nCustom hooks can be registered for lifecycle events.\n\n```python\nfrom ompa.hooks import Hook, HookContext, HookResult\n\nclass MyHook(Hook):\n    def __init__(self):\n        super().__init__(\"my_hook\", token_budget=50)\n\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=\"...\",\n            tokens_hint=50\n        )\n\nao = Ompa(\"./workspace\")\nao.hooks.register_hook(\"my_hook\", MyHook())\n```\n\n### Available Hooks\n\n| Hook | Token Budget | Purpose |\n|------|--------------|---------|\n| `session_start` | ~2000 | Context injection at session start |\n| `handle_message` | ~200 | Message processing |\n| `post_tool` | ~100 | Tool execution recording |\n| `pre_compact` | ~500 | Pre-compaction processing |\n| `stop` | ~200 | Session termination |\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)()\n\n---\n\n## Dual-Vault Configuration\n\nThe dual-vault system separates shared and personal notes.\n\n```python\nfrom ompa.config import DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n    default_vault=VaultTarget.PERSONAL\n)\n```\n\n### Isolation Modes\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified to shared or personal vault based on message type |\n| `MANUAL` | Explicit `VaultTarget` routing per operation |\n| `STRICT` | Enforce isolation boundaries |\n\n### VaultTarget Enum\n\n```python\nfrom ompa.config import VaultTarget\n\nVaultTarget.SHARED    # Team/organizational content\nVaultTarget.PERSONAL # Private/personal content\n```\n\n---\n\n## Async API\n\nFor async applications, use `ompa/async_api.py`:\n\n```python\nfrom ompa.async_api import AsyncOmpa\n\nasync with AsyncOmpa(vault_path=\"./workspace\") as ao:\n    await ao.session_start()\n    result = await ao.search(\"authentication\")\n    await ao.stop()\n```\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)()\n\n---\n\n## Configuration Options\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n\n---\n\n## Return Types\n\n### `HookResult`\n\n```python\n@dataclass\nclass HookResult:\n    success: bool\n    output: str\n    tokens_hint: int\n    hook_name: str\n```\n\n### `Classification`\n\n```python\n@dataclass\nclass Classification:\n    message_type: MessageType\n    confidence: float\n    suggested_folder: str\n    routing_hint: str\n```\n\n### `SearchResult`\n\n```python\n@dataclass\nclass SearchResult:\n    path: Path\n    content: str\n    score: float\n    frontmatter: dict\n```\n\n### `Triple`\n\n```python\n@dataclass\nclass Triple:\n    subject: str\n    predicate: str\n    object: str\n    valid_from: str | None\n    valid_to: str | None\n    source: str | None\n```\n\n---\n\n## Usage Examples\n\n### Basic Session Workflow\n\n```python\nfrom ompa import Ompa\n\n# Initialize\nao = Ompa(vault_path=\"./workspace\")\n\n# Start session\ncontext = ao.session_start()\nprint(context.output)\n\n# Process messages\nao.handle_message(\"We decided to go with Postgres\")\nao.post_tool(\"write\", {\"file_path\": \"work/active/db-choice.md\"})\n\n# Search\nresults = ao.search(\"authentication decisions\")\n\n# End session\nao.stop()\n```\n\n### Dual-Vault Workflow\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\n\nao = Ompa(config=config)\n\n# Auto-routed writes\nao.write(\"Team decision about API design\", tags=[\"decision\"])\n\n# Manual routing\nfrom ompa.config import VaultTarget\nao.write(\"Personal note\", vault=VaultTarget.PERSONAL)\n\n# Export to shared vault\nao.export_to_shared(\"personal/note.md\", sanitize=True)\n```\n\n### Knowledge Graph Usage\n\n```python\nao = Ompa(vault_path=\"./workspace\")\n\n# Add relationships\nao.kg.add_triple(\"Kai\", \"works_on\", \"Orion\", valid_from=\"2025-06-01\")\nao.kg.add_triple(\"Orion\", \"uses\", \"PostgreSQL\", valid_from=\"2025-06-15\")\n\n# Query history\ntriples = ao.kg.query_entity(\"Kai\")\ntimeline = ao.kg.timeline(\"Orion\")\n\n# Get stats\nprint(ao.kg.stats())\n```\n\n---\n\n## Stable Public API\n\nThe following API surface is stable per Semantic Versioning:\n\n- `Ompa` class and all public methods\n- `DualVaultConfig`, `IsolationMode`, `VaultTarget`\n- `HookResult`, `Classification`, `SearchResult`, `Triple`\n- `SemanticIndex`, `SyncBackend`, adapters\n- `count_tokens()` utility\n\nInternal implementation details may change in minor versions.\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)()\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: jmiaie/ompa\n\nSummary: Found 11 potential pitfall items; 0 are high/blocking. Highest priority: installation - 来源证据：OMPA v0.2.0 — The Big Rename.\n\n## 1. installation · 来源证据：OMPA v0.2.0 — The Big Rename\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OMPA v0.2.0 — The Big Rename\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ac771ab081be444ab18c5c1963becb64 | https://github.com/jmiaie/ompa/releases/tag/v0.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. configuration · 来源证据：[P0] agent_integration.py race condition — session.memory attribute not available on cold start\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[P0] agent_integration.py race condition — session.memory attribute not available on cold start\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_db65ef8ac28c41048d74c03c80cbed28 | https://github.com/jmiaie/ompa/issues/6 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1207151629 | https://github.com/jmiaie/ompa | README/documentation is current enough for a first validation pass.\n\n## 4. runtime · 社区讨论暴露的待验证问题：I did an analysis of 44 AI agent frameworks, sharing the result\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: I did an analysis of 44 AI agent frameworks, sharing the result 18 Feb 2026 · One thing missing from most framework comparisons is how they handle failures during agent execution. Tool call retries, error recovery, and ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:reddit | ssig_33233a78090343098fbddbeab9bc927d | https://www.reddit.com/r/LocalLLaMA/comments/1r84o6p/i_did_an_analysis_of_44_ai_agent_frameworks/ | I did an analysis of 44 AI agent frameworks, sharing the result\n\n## 5. runtime · 社区讨论暴露的待验证问题：Your self-hosted AI agents can match closed-source models - I ... - Reddit\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Your self-hosted AI agents can match closed-source models - I ... - Reddit 24 Nov 2025 · Looking for open-source knowledge management tool ... Let's compare 5 Open-Source AI Agent Tools that everyone cannot stop talking about on Reddit.\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:reddit | ssig_4fefa11ceedb46d4af5e2ff44e7709e1 | https://www.reddit.com/r/selfhosted/comments/1p5q8f1/your_selfhosted_ai_agents_can_match_closedsource/ | Your self-hosted AI agents can match closed-source models - I ... - Reddit\n\n## 6. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | last_activity_observed missing\n\n## 7. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium\n\n## 8. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium\n\n## 9. security_permissions · 来源证据：OMPA v0.2.1 — Security & Reliability Hardening\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：OMPA v0.2.1 — Security & Reliability Hardening\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ab0ad6b963354f2096bef6783c95c289 | https://github.com/jmiaie/ompa/releases/tag/v0.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 10. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | issue_or_pr_quality=unknown\n\n## 11. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | release_recency=unknown\n\n<!-- canonical_name: jmiaie/ompa; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "ompa",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1207151629",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/jmiaie/ompa"
        },
        {
          "evidence_id": "art_9e131103caf84e66a7ff3a59a0d43757",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/jmiaie/ompa#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "ompa 说明书",
      "toc": [
        "https://github.com/jmiaie/ompa 项目说明书",
        "目录",
        "Introduction to OMPA",
        "Overview",
        "Key Features",
        "Architecture",
        "Installation",
        "Core only (vault + palace + KG + CLI + MCP)",
        "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": "40ff3e241490825d6dc8714c2d5594316e0cb69c",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "README.md",
      "docs/index.md",
      "docs/quickstart.md",
      "docs/changelog.md",
      "docs/api/cli.md",
      "docs/api/vault.md",
      "docs/api/kg.md",
      "docs/api/ompa.md",
      "docs/api/palace.md",
      "docs/guides/dual-vault.md",
      "docs/guides/hooks.md",
      "docs/guides/message-types.md",
      "docs/guides/mcp.md",
      "examples/simple_vault/demo.py",
      "examples/mcp_desktop/README.md",
      "examples/langchain_agent/ompa_memory.py",
      "examples/multi_agent/swarm_memory.py"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "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": "# ompa - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 ompa 编译的 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- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`CLAUDE.md`, `README.md`, `docs/quickstart.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `pip install ompa` 证据：`README.md` Claim：`clm_0003` supported 0.86, `clm_0004` supported 0.86, `clm_0005` supported 0.86, `clm_0007` supported 0.86 等\n- `pip install ompa          # Core only` 证据：`README.md` Claim：`clm_0004` supported 0.86, `clm_0011` supported 0.86\n- `pip install ompa[all]     # Includes local semantic search` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `claude mcp add ompa -- python -m ompa.mcp_server` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `pip install ompa[all]` 证据：`README.md` Claim：`clm_0005` supported 0.86, `clm_0007` supported 0.86, `clm_0012` supported 0.86, `clm_0013` supported 0.86\n- `pip install ompa[dev]` 证据：`README.md` Claim：`clm_0008` supported 0.86\n- `git clone https://github.com/jmiaie/ompa && cd ompa` 证据：`README.md` Claim：`clm_0009` supported 0.86\n- `pip install -e \".[all]\"` 证据：`README.md` Claim：`clm_0010` supported 0.86, `clm_0014` supported 0.86\n- `pip install ompa          # Core only (vault + palace + KG + CLI + MCP)` 证据：`docs/quickstart.md` Claim：`clm_0011` supported 0.86\n- `pip install ompa[all]     # Adds local semantic search (sentence-transformers)` 证据：`docs/quickstart.md` Claim：`clm_0012` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：先做角色匹配试用\n- **为什么**：这个项目更像角色库，核心风险是选错角色或把角色文案当执行能力；先用 Prompt Preview 试角色匹配，再决定是否沙盒导入。\n\n### 30 秒判断\n\n- **现在怎么做**：先做角色匹配试用\n- **最小安全下一步**：先用 Prompt Preview 试角色匹配；满意后再隔离导入\n- **先别相信**：角色质量和任务匹配不能直接相信。\n- **继续会触碰**：角色选择偏差、命令执行、宿主 AI 配置\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`CLAUDE.md`, `README.md`, `docs/quickstart.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86, `clm_0004` supported 0.86, `clm_0005` supported 0.86, `clm_0007` supported 0.86\n\n### 现在还不能相信\n\n- **角色质量和任务匹配不能直接相信。**（unverified）：角色库证明有很多角色，不证明每个角色都适合你的具体任务，也不证明角色能产生高质量结果。\n- **不能把角色文案当成真实执行能力。**（unverified）：安装前只能判断角色描述和任务画像是否匹配，不能证明它能在宿主 AI 里完成任务。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`CLAUDE.md`\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **角色选择偏差**：用户对任务应该由哪个专家角色处理的判断。 原因：选错角色会让 AI 从错误专业视角回答，浪费时间或误导决策。\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`CLAUDE.md`, `README.md`, `docs/quickstart.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`CLAUDE.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`CLAUDE.md`, `README.md`, `docs/quickstart.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：先用交互式试用验证任务画像和角色匹配，不要先导入整套角色库。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\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_0016` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`CLAUDE.md`, `README.md`, `docs/quickstart.md` Claim：`clm_0017` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\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- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`CLAUDE.md`, `README.md`, `docs/quickstart.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：63\n- 重要文件覆盖：40/63\n- 证据索引条目：44\n- 角色 / Skill 条目：22\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请基于 ompa 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 ompa 当作安装前体验资产，而不是已安装工具或真实运行环境。\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请基于 ompa 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 22 个角色 / Skill / 项目文档条目。\n\n- **CLAUDE.md — OMPA**（project_doc）：You are building OMPA Obsidian-MemPalace-Agnostic — a universal AI agent memory layer. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CLAUDE.md`\n- **Why OMPA?**（project_doc）：OMPA Universal AI Agent Memory Layer Vault · Palace · Temporal Knowledge Graph 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **MCP Desktop Setup**（project_doc）：Step-by-step guide for connecting OMPA to Claude Desktop, Cursor, or Windsurf via MCP. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/mcp_desktop/README.md`\n- **Contributing to OMPA**（project_doc）：Thanks for your interest in contributing. Here's everything you need to get started. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **Changelog**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/changelog.md`\n- **OMPA**（project_doc）：Universal AI Agent Memory Layer — Vault · Palace · Temporal Knowledge Graph 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/index.md`\n- **Quickstart**（project_doc）：This guide walks you from zero to a running OMPA vault in under 5 minutes. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/quickstart.md`\n- **CLI Reference**（project_doc）：All CLI commands are available via ao . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api/cli.md`\n- **Knowledge Graph**（project_doc）：The KnowledgeGraph stores temporal triples: subject → predicate → object with optional validity windows. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api/kg.md`\n- **Ompa**（project_doc）：The Ompa class is the main entry point. It integrates all three layers Vault, Palace, Knowledge Graph with lifecycle hooks, message classification, and semantic search. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api/ompa.md`\n- **Palace**（project_doc）：The Palace is the agent-accessible metadata layer — a navigational index over the vault. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api/palace.md`\n- **Vault**（project_doc）：The Vault class manages the markdown note storage layer. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api/vault.md`\n- **Dual-Vault**（project_doc）：Dual-vault mode separates shared team/org content from personal private/sensitive content into two isolated vaults. Each vault has its own palace, knowledge graph, and semantic index. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/dual-vault.md`\n- **Lifecycle Hooks**（project_doc）：OMPA provides 5 lifecycle hooks that wrap your agent's natural event loop. Each hook has a token budget — the maximum context it injects into your agent. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/hooks.md`\n- **MCP Server**（project_doc）：OMPA exposes all of its capabilities as an MCP Model Context Protocol server with 15 tools. This lets Claude Desktop, Cursor, Windsurf, and any MCP-compatible client access your vault directly — no code changes needed. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/mcp.md`\n- **Message Types**（project_doc）：OMPA classifies messages into 15 types, each with auto-routing rules that file content in the right vault folder. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/message-types.md`\n- **Summary**（project_doc）：- Bug fix - New feature - Breaking change - Documentation - Refactor / chore 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/pull_request_template.md`\n- **Changelog**（project_doc）：All notable changes to OMPA are documented here. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CHANGELOG.md`\n- **Security Audit — OMPA v1.0.0**（project_doc）：Date: 2026-05-07 Version: 1.0.0 Tool versions: bandit 1.8.x, mypy 1.x, manual review 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY_AUDIT.md`\n- **API Stability**（project_doc）：OMPA follows Semantic Versioning https://semver.org/ starting at v1.0.0. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`STABILITY.md`\n- **Bug report**（project_doc）：Describe the bug A clear description of what went wrong. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/bug_report.md`\n- **Feature request**（project_doc）：Problem this solves What problem or gap is this feature addressing? Be specific. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/feature_request.md`\n\n## 证据索引\n\n- 共索引 44 条证据。\n\n- **CLAUDE.md — OMPA**（documentation）：You are building OMPA Obsidian-MemPalace-Agnostic — a universal AI agent memory layer. 证据：`CLAUDE.md`\n- **Why OMPA?**（documentation）：OMPA Universal AI Agent Memory Layer Vault · Palace · Temporal Knowledge Graph 证据：`README.md`\n- **MCP Desktop Setup**（documentation）：Step-by-step guide for connecting OMPA to Claude Desktop, Cursor, or Windsurf via MCP. 证据：`examples/mcp_desktop/README.md`\n- **Contributing to OMPA**（documentation）：Thanks for your interest in contributing. Here's everything you need to get started. 证据：`CONTRIBUTING.md`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`\n- **Changelog**（documentation）：Changelog 证据：`docs/changelog.md`\n- **OMPA**（documentation）：Universal AI Agent Memory Layer — Vault · Palace · Temporal Knowledge Graph 证据：`docs/index.md`\n- **Quickstart**（documentation）：This guide walks you from zero to a running OMPA vault in under 5 minutes. 证据：`docs/quickstart.md`\n- **CLI Reference**（documentation）：All CLI commands are available via ao . 证据：`docs/api/cli.md`\n- **Knowledge Graph**（documentation）：The KnowledgeGraph stores temporal triples: subject → predicate → object with optional validity windows. 证据：`docs/api/kg.md`\n- **Ompa**（documentation）：The Ompa class is the main entry point. It integrates all three layers Vault, Palace, Knowledge Graph with lifecycle hooks, message classification, and semantic search. 证据：`docs/api/ompa.md`\n- **Palace**（documentation）：The Palace is the agent-accessible metadata layer — a navigational index over the vault. 证据：`docs/api/palace.md`\n- **Vault**（documentation）：The Vault class manages the markdown note storage layer. 证据：`docs/api/vault.md`\n- **Dual-Vault**（documentation）：Dual-vault mode separates shared team/org content from personal private/sensitive content into two isolated vaults. Each vault has its own palace, knowledge graph, and semantic index. 证据：`docs/guides/dual-vault.md`\n- **Lifecycle Hooks**（documentation）：OMPA provides 5 lifecycle hooks that wrap your agent's natural event loop. Each hook has a token budget — the maximum context it injects into your agent. 证据：`docs/guides/hooks.md`\n- **MCP Server**（documentation）：OMPA exposes all of its capabilities as an MCP Model Context Protocol server with 15 tools. This lets Claude Desktop, Cursor, Windsurf, and any MCP-compatible client access your vault directly — no code changes needed. 证据：`docs/guides/mcp.md`\n- **Message Types**（documentation）：OMPA classifies messages into 15 types, each with auto-routing rules that file content in the right vault folder. 证据：`docs/guides/message-types.md`\n- **Summary**（documentation）：- Bug fix - New feature - Breaking change - Documentation - Refactor / chore 证据：`.github/pull_request_template.md`\n- **Changelog**（documentation）：All notable changes to OMPA are documented here. 证据：`CHANGELOG.md`\n- **Security Audit — OMPA v1.0.0**（documentation）：Date: 2026-05-07 Version: 1.0.0 Tool versions: bandit 1.8.x, mypy 1.x, manual review 证据：`SECURITY_AUDIT.md`\n- **API Stability**（documentation）：OMPA follows Semantic Versioning https://semver.org/ starting at v1.0.0. 证据：`STABILITY.md`\n- **Minimal code that reproduces the issue**（documentation）：Describe the bug A clear description of what went wrong. 证据：`.github/ISSUE_TEMPLATE/bug_report.md`\n- **What the API/CLI might look like**（documentation）：Problem this solves What problem or gap is this feature addressing? Be specific. 证据：`.github/ISSUE_TEMPLATE/feature_request.md`\n- **.Markdownlint**（structured_config）：{ \"MD013\": false, \"MD024\": { \"siblings only\": true } } 证据：`.markdownlint.json`\n- **Byte-compiled / optimized / DLL files**（source_file）：Byte-compiled / optimized / DLL files pycache / .py cod $py.class 证据：`.gitignore`\n- **---------------------------------------------------------------------------**（source_file）：Measures Recall@5 on a subset of LongMemEval-style questions using OMPA's verbatim storage + semantic search. Reports the headline metric that OMPA claims: 96.6% R@5 established by MemPalace on the same storage approach . 证据：`benchmarks/longmemeval.py`\n- **Demo**（source_file）：{\"version\": 2, \"width\": 80, \"height\": 24, \"duration\": 7.89794135093689, \"command\": \"ao demo\", \"title\": \"AgnosticObsidian \\u2014 Universal AI Agent Memory\", \"env\": {\"TERM\": \"xterm-256color\", \"SHELL\": \"/bin/bash\"}} 0.5000827312469482, \"o\", \"\\u001b 1;36m\\u2554\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2550\\u2557\\u001b 0m\\r\\n\" 0.5000901222229004, \"o\", \"\\u001b 1;36m\\u2551 AgnosticObsidian \\u2014 Universal AI Age… 证据：`demo.cast`\n- **Mkdocs**（source_file）：site name: OMPA site description: Universal AI agent memory layer — vault + palace + temporal knowledge graph site author: Micap AI repo url: https://github.com/jmiaie/ompa repo name: jmiaie/ompa edit uri: edit/main/docs/ 证据：`mkdocs.yml`\n- **Backward compatibility alias**（source_file）：\"\"\" OMPA — Obsidian-MemPalace-Agnostic 证据：`ompa/__init__.py`\n- **Main**（source_file）：\"\"\"Allow running OMPA as a module: python -m ompa\"\"\" 证据：`ompa/__main__.py`\n- **Or manually:**（source_file）：\"\"\" AsyncOmpa — async-native wrapper around Ompa. 证据：`ompa/async_api.py`\n- **Regex patterns for classification**（source_file）：\"\"\" Message classification for routing and context injection. Classifies user messages into categories and injects routing hints. Also classifies content for dual-vault routing shared vs personal . \"\"\" 证据：`ompa/classifier.py`\n- **Dual-vault init**（source_file）：\"\"\" CLI for OMPA. Run with: ao or ao-mcp \"\"\" 证据：`ompa/cli.py`\n- **Default classification indicators**（source_file）：\"\"\" OMPA Configuration — Dual-vault settings and content classification rules. 证据：`ompa/config.py`\n- **Dual-vault parameters**（source_file）：\"\"\" OMPA — Universal AI Agent Memory Layer Core module integrating vault, palace, KG, hooks, classifier, and semantic search. Supports single-vault legacy and dual-vault shared + personal architecture. \"\"\" 证据：`ompa/core.py`\n- **North Star**（source_file）：\"\"\" Lifecycle hooks for OMPA. Handles session start, user message, post tool, pre compact, and stop events. \"\"\" 证据：`ompa/hooks.py`\n- **WAL mode: readers don't block writers; writers don't block readers.**（source_file）：\"\"\" Knowledge Graph — Temporal Entity-Relationship Graph for OMPA. Inspired by MemPalace's knowledge graph.py. SQLite-based triples with validity windows. 证据：`ompa/knowledge_graph.py`\n- **Claude Desktop**（source_file）：\"\"\" OMPA MCP Server Provides 15+ tools via the Model Context Protocol. Works with Claude Desktop, Cursor, Windsurf, and any MCP-compatible client. 证据：`ompa/mcp_server.py`\n- **Increment this when new migrations are added.**（source_file）：Detects the version of an existing vault and applies any needed schema upgrades: KG index additions, palace rebuilds, semantic index refreshes. 证据：`ompa/migration.py`\n- **Wing operations**（source_file）：\"\"\" Palace — Wing/Room/Closet/Drawer metadata layer for OMPA. Inspired by MemPalace. Manages the structured metadata that accelerates retrieval. \"\"\" 证据：`ompa/palace.py`\n- **Accept a pre-built backend e.g. NIMEmbeddingBackend or load lazily**（source_file）：\"\"\" Semantic search for OMPA. Provides hybrid keyword + semantic search across the vault. Supports a pluggable embedding backend sentence-transformers by default, or any object with an encode text: str - array interface . \"\"\" 证据：`ompa/semantic.py`\n- **Heuristic: ~1.3 tokens per whitespace-delimited word conservative for code**（source_file）：\"\"\" Token counting with tiktoken precise or word-count heuristic fallback . 证据：`ompa/token_counter.py`\n- **Shared exclude patterns for vault traversal**（source_file）：\"\"\" Vault management for OMPA. Handles note organization, templates, wikilinks, and frontmatter validation. \"\"\" 证据：`ompa/vault.py`\n- **Pyproject**（source_file）：project name = \"ompa\" version = \"1.0.8\" description = \"Universal AI agent memory layer — vault + palace + temporal knowledge graph\" readme = \"README.md\" license = {text = \"MIT\"} requires-python = \" =3.10\" authors = {name = \"Micap AI\", email = \"info@micap.ai\"}, keywords = \"ai\", \"agent\", \"memory\", \"obsidian\", \"knowledge-graph\", \"mcp\", \"claude\", \"llm\", \"rag\", \"semantic-search\", \"langchain\", \"llamaindex\", \"nvidia\", \"nim\", \"multi-agent\" classifiers = \"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: MIT License\", \"Programming Language :: Python :: 3.10\", \"Programming Language :: Python :: 3.11\", \"Programming Language :: Python :: 3.12\",… 证据：`pyproject.toml`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`CLAUDE.md`, `README.md`, `examples/mcp_desktop/README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`CLAUDE.md`, `README.md`, `examples/mcp_desktop/README.md`\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\nThe following material strengthens the Repomix/AI Context Pack body. Human Manual is only a reading skeleton; pitfall logs become hard operating constraints for the host AI.\n\n## Human Manual Skeleton\n\nUsage rule: this is only a reading path and salience signal, not factual authority. Concrete facts must still come from repo evidence / Claim Graph.\n\nHard rules for the host AI:\n- Do not treat page titles, order, summaries, or importance as project facts.\n- When explaining the Human Manual skeleton, state that it is only a reading path / salience signal.\n- Capability, installation, compatibility, runtime status, and risk judgments must cite repo evidence, source paths, or Claim Graph.\n\n- **Introduction to OMPA**：importance `high`\n  - source_paths: README.md, ompa/__init__.py\n- **Quick Start Guide**：importance `high`\n  - source_paths: README.md, ompa/cli.py, pyproject.toml\n- **Feature Comparison**：importance `medium`\n  - source_paths: README.md\n- **Three-Layer Architecture**：importance `high`\n  - source_paths: ompa/vault.py, ompa/palace.py, ompa/knowledge_graph.py\n- **Lifecycle Hooks**：importance `high`\n  - source_paths: ompa/hooks.py, ompa/core.py\n- **Vault System**：importance `high`\n  - source_paths: ompa/vault.py, ompa/core.py\n- **Palace System**：importance `high`\n  - source_paths: ompa/palace.py\n- **Knowledge Graph**：importance `high`\n  - source_paths: ompa/knowledge_graph.py\n\n## Repo Inspection Evidence\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `40ff3e241490825d6dc8714c2d5594316e0cb69c`\n- inspected_files: `pyproject.toml`, `README.md`, `docs/index.md`, `docs/quickstart.md`, `docs/changelog.md`, `docs/api/cli.md`, `docs/api/vault.md`, `docs/api/kg.md`, `docs/api/ompa.md`, `docs/api/palace.md`, `docs/guides/dual-vault.md`, `docs/guides/hooks.md`, `docs/guides/message-types.md`, `docs/guides/mcp.md`, `examples/simple_vault/demo.py`, `examples/mcp_desktop/README.md`, `examples/langchain_agent/ompa_memory.py`, `examples/multi_agent/swarm_memory.py`\n\nHard rules for the host AI:\n- Without repo_clone_verified=true, do not claim the source code has been read.\n- Without repo_inspection_verified=true, do not turn README/docs/package observations into facts.\n- Without quick_start_verified=true, do not claim the Quick Start has been successfully run.\n\n## Doramagic Pitfall Constraints\n\nThese rules come from Doramagic discovery, validation, or compilation pitfalls. The host AI must treat them as operating constraints, not general background notes.\n\n### Constraint 1: 来源证据：OMPA v0.2.0 — The Big Rename\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OMPA v0.2.0 — The Big Rename\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_ac771ab081be444ab18c5c1963becb64 | https://github.com/jmiaie/ompa/releases/tag/v0.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 2: 来源证据：[P0] agent_integration.py race condition — session.memory attribute not available on cold start\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[P0] agent_integration.py race condition — session.memory attribute not available on cold start\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_db65ef8ac28c41048d74c03c80cbed28 | https://github.com/jmiaie/ompa/issues/6 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 3: 能力判断依赖假设\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:1207151629 | https://github.com/jmiaie/ompa | README/documentation is current enough for a first validation pass.\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 4: 社区讨论暴露的待验证问题：I did an analysis of 44 AI agent frameworks, sharing the result\n\n- Trigger: I did an analysis of 44 AI agent frameworks, sharing the result 18 Feb 2026 · One thing missing from most framework comparisons is how they handle failures during agent execution. Tool call retries, error recovery, and ...\n- Host AI rule: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Why it matters: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Evidence: social_signal:reddit | ssig_33233a78090343098fbddbeab9bc927d | https://www.reddit.com/r/LocalLLaMA/comments/1r84o6p/i_did_an_analysis_of_44_ai_agent_frameworks/ | I did an analysis of 44 AI agent frameworks, sharing the result\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 5: 社区讨论暴露的待验证问题：Your self-hosted AI agents can match closed-source models - I ... - Reddit\n\n- Trigger: Your self-hosted AI agents can match closed-source models - I ... - Reddit 24 Nov 2025 · Looking for open-source knowledge management tool ... Let's compare 5 Open-Source AI Agent Tools that everyone cannot stop talking about on Reddit.\n- Host AI rule: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Why it matters: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Evidence: social_signal:reddit | ssig_4fefa11ceedb46d4af5e2ff44e7709e1 | https://www.reddit.com/r/selfhosted/comments/1p5q8f1/your_selfhosted_ai_agents_can_match_closedsource/ | Your self-hosted AI agents can match closed-source models - I ... - Reddit\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 6: 维护活跃度未知\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:1207151629 | https://github.com/jmiaie/ompa | last_activity_observed missing\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 7: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 8: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 9: 来源证据：OMPA v0.2.1 — Security & Reliability Hardening\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：OMPA v0.2.1 — Security & Reliability Hardening\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_ab0ad6b963354f2096bef6783c95c289 | https://github.com/jmiaie/ompa/releases/tag/v0.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 10: 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:1207151629 | https://github.com/jmiaie/ompa | issue_or_pr_quality=unknown\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n",
      "summary": "Context and operating boundaries for host AI agents.",
      "title": "AI Context Pack"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card\n\nProject: jmiaie/ompa\n\n## Doramagic Trial Decision\n\nCurrent decision: it can enter pre-publication recommendation checks. First use should still start with least privilege, a temporary directory, and reversible configuration.\n\n## What The User Can Do Now\n\n- Read the Human Manual first to understand the project purpose and main workflows.\n- Use Prompt Preview for pre-install exploration; it validates interaction shape, not real execution.\n- Run official Quick Start commands only inside an isolated environment, not a primary setup.\n\n## Do Not Do Yet\n\n- Do not treat Prompt Preview as a real project execution result.\n- Do not treat metadata-only validation as sandbox installation validation.\n- Do not describe unverified capabilities as supported, working, or safe to install.\n- Do not provide production data, private files, real secrets, or primary host configuration on first trial.\n\n## Pre-Install Checklist\n\n- Host AI match: mcp_host\n- Official installation entry status: official entry point found\n- Isolated temporary directory, temporary host, or container validation: required\n- Configuration rollback path: required\n- API keys, network access, file access, or host configuration changes: treat as high risk until confirmed\n- Installation command, actual output, and failure logs: must be recorded\n\n## Current Blockers\n\n- No blockers.\n\n## Project-Specific Pitfalls\n\n- 来源证据：OMPA v0.2.0 — The Big Rename (medium): 可能阻塞安装或首次运行。 Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：[P0] agent_integration.py race condition — session.memory attribute not available on cold start (medium): 可能阻塞安装或首次运行。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 能力判断依赖假设 (medium): 假设不成立时，用户拿不到承诺的能力。 Suggested check: 将假设转成下游验证清单。\n- 社区讨论暴露的待验证问题：I did an analysis of 44 AI agent frameworks, sharing the result (medium): 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。 Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 社区讨论暴露的待验证问题：Your self-hosted AI agents can match closed-source models - I ... - Reddit (medium): 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。 Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n\n## Risk And Permission Notes\n\n- no_demo: medium\n\n## Evidence Gaps\n\n- No structured evidence gaps are currently visible.\n",
      "summary": "Installation, permission, validation, and pre-recommendation risks.",
      "title": "Boundary & Risk Card"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/jmiaie/ompa 项目说明书\n\n生成时间：2026-05-15 13:44:18 UTC\n\n## 目录\n\n- [Introduction to OMPA](#introduction)\n- [Quick Start Guide](#quickstart)\n- [Feature Comparison](#comparison)\n- [Three-Layer Architecture](#three-layer-architecture)\n- [Lifecycle Hooks](#lifecycle-hooks)\n- [Vault System](#vault-system)\n- [Palace System](#palace-system)\n- [Knowledge Graph](#knowledge-graph)\n- [Message Classification](#message-classification)\n- [Python API Reference](#python-api)\n\n<a id='introduction'></a>\n\n## Introduction to OMPA\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Quick Start Guide](#quickstart)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n- [ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n- [ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n</details>\n\n# Introduction to OMPA\n\nOMPA (Obsidian-MemPalace-Agnostic) is a lightweight, framework-agnostic memory management system designed for AI agents. It provides persistent storage, semantic search, knowledge graph tracking, and a palace metaphor for organizing notes and memories across sessions.\n\n## Overview\n\nOMPA serves as a **second brain** for AI agents, enabling them to:\n\n- Persist and retrieve information across sessions\n- Classify and automatically route messages to appropriate storage locations\n- Search vault contents using semantic similarity\n- Track temporal knowledge graphs with validity windows\n- Navigate a hierarchical palace structure (wings, rooms, drawers, halls, tunnels)\n\nThe project was renamed from \"AgnosticObsidian\" to OMPA in version 0.2.0, with backward compatibility preserved via an alias. 资料来源：[CHANGELOG.md:1-10]()\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Dual-Vault Architecture** | Separate shared and personal vault storage with isolation modes |\n| **Semantic Search** | Local embedding-based search using sentence-transformers |\n| **Temporal Knowledge Graph** | SQLite-backed triples with validity windows |\n| **Message Classification** | 15 message types with automatic routing |\n| **Lifecycle Hooks** | 5 hooks for extending agent behavior |\n| **MCP Server** | 15 tools exposed via Model Context Protocol |\n| **CLI Interface** | 14 commands for vault operations |\n\n## Architecture\n\nOMPA follows a layered architecture with distinct responsibilities:\n\n```mermaid\ngraph TD\n    subgraph \"OMPA Architecture\"\n        CLI[CLI<br>14 commands]\n        MCP[MCP Server<br>15 tools]\n        Core[Core Module<br>Ompa class]\n        Vault[Vault<br>CRUD operations]\n        Palace[Palace<br>Metadata layers]\n        KG[Knowledge Graph<br>SQLite triples]\n        Semantic[Semantic Index<br>Embeddings]\n        Classifier[Classifier<br>15 message types]\n        Hooks[Hook Manager<br>Lifecycle hooks]\n    end\n    \n    CLI --> Core\n    MCP --> Core\n    Core --> Vault\n    Core --> Palace\n    Core --> KG\n    Core --> Semantic\n    Core --> Classifier\n    Core --> Hooks\n```\n\n### Core Components\n\n#### 1. Vault (`ompa/vault.py`)\n\nThe Vault layer handles file-based storage for notes. It provides:\n\n- Brain/work/org/perf folder organization\n- Note CRUD operations\n- Orphan detection\n- Path traversal protection\n- UTF-8 encoding enforcement\n\n资料来源：[README.md:47-56]()\n\n#### 2. Palace (`ompa/palace.py`)\n\nThe Palace metadata layer provides hierarchical navigation:\n\n- **Wings**: Top-level categories\n- **Rooms**: Secondary divisions within wings\n- **Drawers**: Tertiary storage units\n- **Halls**: Cross-room connections\n- **Tunnels**: Cross-wing shortcuts\n\n#### 3. Knowledge Graph (`ompa/knowledge_graph.py`)\n\nTemporal knowledge graph backed by SQLite:\n\n- Triple storage: `(subject, predicate, object)`\n- Validity windows: `valid_from` and `valid_to` timestamps\n- Timeline queries for entity history\n- Auto-population from vault wikilinks and frontmatter\n\n#### 4. Classifier (`ompa/classifier.py`)\n\nMessage classification engine supporting 15 message types:\n\n| Message Type | Description |\n|--------------|-------------|\n| `DECISION` | Architectural decisions, ADR records |\n| `INCIDENT` | Bugs, outages, debugging events |\n| `WIN` | Achievements, deployments, milestones |\n| `ONE_ON_ONE` | Manager/peer check-ins |\n| `MEETING` | Meeting notes and action items |\n| `PROJECT_UPDATE` | Project status reports |\n| `REFLECTION` | Retrospectives, learnings |\n| `TODO` | Task items |\n| `QUESTION` | Technical questions |\n| `IDEA` | Brainstorming, proposals |\n| `LEARNING` | New information acquired |\n| `BLOCKER` | Impediments |\n| `ARCHITECTURE` | System design discussions |\n| `SECURITY` | Security-related events |\n| `DATA` | Data-related events |\n\n资料来源：[ompa/classifier.py:1-50]()\n\n#### 5. Semantic Search (`ompa/semantic.py`)\n\nLocal semantic search using sentence-transformers:\n\n- Lazy model loading (downloaded on first access)\n- Incremental indexing (tracks file modification times)\n- Cosine similarity scoring\n- Optional feature via `pip install ompa[all]`\n\n#### 6. Hooks (`ompa/hooks.py`)\n\nLifecycle hooks for extending OMPA behavior:\n\n```mermaid\ngraph LR\n    SS[session_start] --> CB[Hook execution]\n    HM[handle_message] --> CB\n    PT[post_tool] --> CB\n    PC[pre_compact] --> CB\n    ST[stop] --> CB\n    \n    CB --> HR[HookResult]\n```\n\n资料来源：[CONTRIBUTING.md:43-54]()\n\n#### 7. MCP Server (`ompa/mcp_server.py`)\n\nModel Context Protocol server exposing 15 tools:\n\n```mermaid\ngraph TD\n    MCP[JSON-RPC<br>stdin/stdout] --> Tools\n    Tools --> ao_session_start\n    Tools --> ao_classify\n    Tools --> ao_search\n    Tools --> ao_kg_query\n    Tools --> ao_kg_add\n    Tools --> ao_kg_stats\n    Tools --> ao_palace_wings\n    Tools --> ao_palace_rooms\n    Tools --> ao_palace_tunnel\n    Tools --> ao_validate\n    Tools --> ao_wrap_up\n    Tools --> ao_status\n    Tools --> ao_orphans\n    Tools --> ao_kg_populate\n    Tools --> ao_init\n```\n\n资料来源：[CLAUDE.md:1-15]()\n\n## Installation\n\n### Package Options\n\n```bash\n# Core only (vault + palace + KG + CLI + MCP)\npip install ompa\n\n# With local semantic search\npip install ompa[all]\n\n# Development dependencies\npip install ompa[dev]\n```\n\nRequirements: Python 3.10+\n\n资料来源：[README.md:36-44]()\n\n### Quick Start\n\n```bash\n# Initialize vault\nao init\n\n# Check vault health\nao status\n\n# Start a session\nao session-start\n\n# Classify a message\nao classify \"We decided to go with Postgres\"\n\n# Search vault\nao search \"authentication decisions\"\n\n# Query knowledge graph\nao kg-query Kai\n\n# End session\nao wrap-up\n```\n\n## Dual-Vault Architecture\n\nOMPA supports separating team/organization content from personal notes:\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\nao = Ompa(config=config)\n```\n\n### Isolation Modes\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified to shared or personal vault based on message type |\n| `STRICT` | Explicit `VaultTarget` routing required for all operations |\n| `MANUAL` | Default vault configurable, explicit routing optional |\n\n资料来源：[README.md:57-71]()\n\n## Python API\n\n### Core Class\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(vault_path=\"./workspace\")\n\n# Lifecycle\ncontext = ao.session_start()              # Returns ~2K token context string\nhint = ao.handle_message(\"We won the enterprise deal!\")\nao.post_tool(\"write\", {\"file_path\": \"work/active/auth.md\"})\nao.wrap_up()                              # alias for stop()\nao.standup()                              # alias for session_start()\n\n# Search\nresults = ao.search(\"authentication decisions\", wing=\"Orion\")\n\n# Classification\nclassification = ao.classify(message)\nrouting_hint = ao.get_routing_hint(message)\n\n# Knowledge graph\nao.kg.add_triple(\"Kai\", \"works_on\", \"Orion\", valid_from=\"2025-06-01\")\ntriples = ao.kg.query_entity(\"Kai\")\ntimeline = ao.kg.timeline(\"Orion\")\n```\n\n资料来源：[STABILITY.md:12-45]()\n\n### Data Classes\n\n```python\nHookResult(hook_name, success, output, tokens_hint, error)\nClassification(message_type, confidence, suggested_action, routing_hints)\nSearchResult(path, content_excerpt, score, match_type)\nTriple(subject, predicate, object, valid_from, valid_to, confidence, source_file)\n```\n\n## MCP Desktop Integration\n\nOMPA integrates with AI coding assistants via MCP:\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"/absolute/path/to/vault\"\n      }\n    }\n  }\n}\n```\n\n### Supported IDEs\n\n| IDE | Configuration Location |\n|-----|------------------------|\n| Claude Desktop | `~/.claude/claude_desktop_config.json` |\n| Cursor | `.cursor/mcp.json` |\n| Windsurf | `.windsurf/mcp.json` |\n\n资料来源：[examples/mcp_desktop/README.md:1-50]()\n\n## Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n| `OMPA_ISOLATION_MODE` | `auto` | Isolation mode (dual-vault) |\n\n## Project Structure\n\n```\nompa/\n├── core.py              # Ompa main class — lifecycle, hooks, dual-vault\n├── vault.py             # Vault management (brain/work/org/perf)\n├── palace.py            # Palace metadata (wings/rooms/drawers/halls/tunnels)\n├── knowledge_graph.py   # Temporal KG (SQLite triples + validity windows)\n├── hooks.py             # 5 lifecycle hooks + HookManager\n├── classifier.py        # 15 message types with auto-routing\n├── semantic.py          # Local semantic search (lazy model loading)\n├── mcp_server.py        # MCP protocol server (15 tools)\n├── config.py            # Dual-vault configuration\n└── cli.py               # typer CLI (14 commands)\n```\n\n资料来源：[README.md:47-56]()\n\n## Security Features\n\n- **Path traversal protection**: All vault file operations resolve and boundary-check paths against vault root 资料来源：[CHANGELOG.md:23-26]()\n- **UTF-8 encoding enforcement**: All vault file writes use UTF-8 explicitly\n- **Security audit**: 8/10 rating with 59/59 tests passing\n\n## API Stability\n\nOMPA follows Semantic Versioning. The stable public API includes:\n\n- `Ompa` core class and all public methods\n- Data classes: `HookResult`, `Classification`, `SearchResult`, `Triple`\n- CLI commands and MCP tools\n- Sync backends and adapters\n\n资料来源：[STABILITY.md:1-50]()\n\n## Framework Compatibility\n\n| Agent Framework | Integration Method |\n|-----------------|-------------------|\n| Claude Code | Python API + MCP server |\n| OpenClaw | Python API + MCP server |\n| Codex | Python API + MCP server |\n| Gemini CLI | Python API + MCP server |\n| LangChain | Python API + adapters |\n\n## CLI Reference\n\n| Command | Description |\n|---------|-------------|\n| `ao init` | Initialize a new vault |\n| `ao status` | Health check and stats |\n| `ao session-start` | Inject memory context |\n| `ao classify <msg>` | Classify and route a message |\n| `ao search <query>` | Semantic search |\n| `ao orphans` | Detect orphaned notes |\n| `ao wrap-up` | Session summary and save |\n| `ao wings` | List palace wings |\n| `ao rooms <wing>` | List rooms in a wing |\n| `ao tunnel` | Create/traverse cross-wing tunnel |\n| `ao kg-query <entity>` | Query knowledge graph |\n| `ao kg-timeline <entity>` | Entity timeline |\n| `ao kg-stats` | KG statistics |\n| `ao validate` | Validate vault structure |\n| `ao rebuild-index` | Rebuild semantic index |\n\n资料来源：[README.md:18-37]()\n\n---\n\n<a id='quickstart'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Python API Reference](#python-api)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n- [pyproject.toml](https://github.com/jmiaie/ompa/blob/main/pyproject.toml)\n</details>\n\n# Quick Start Guide\n\nOMPA (Obsidian-MemPalace-Agnostic) is a local-first memory management system for AI agents. It provides a dual-layer architecture combining a **Vault** for source-of-truth note storage with a **Palace** for retrieval acceleration, plus a temporal **Knowledge Graph** for entity tracking. This guide walks you through installation, vault initialization, CLI usage, Python API integration, and MCP server setup.\n\n---\n\n## Prerequisites\n\nBefore installing OMPA, ensure your environment meets the following requirements:\n\n| Requirement | Version | Notes |\n|-------------|---------|-------|\n| Python | 3.10+ | Required for async/await support |\n| pip | Latest recommended | For package installation |\n| git | Any recent version | For source installation |\n| Disk space | ~100MB minimum | +500MB if enabling semantic search |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Installation\n\nOMPA offers multiple installation options depending on your use case.\n\n### Core Installation\n\nThe core package includes vault management, palace metadata, knowledge graph, CLI, and MCP server:\n\n```bash\npip install ompa\n```\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### With Semantic Search\n\nInstall with local semantic search support (adds sentence-transformers and numpy):\n\n```bash\npip install ompa[all]\n```\n\n> **Note:** First run downloads the `all-MiniLM-L6-v2` model (~90MB). Subsequent runs are instant. 资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n### Development Installation\n\nFor contributing or modifying OMPA:\n\n```bash\ngit clone https://github.com/jmiaie/ompa\ncd ompa\npip install -e \".[dev,all]\"\n```\n\n资料来源：[CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n\n---\n\n## Initializing the Vault\n\nAfter installation, initialize your vault to create the required directory structure:\n\n```bash\nao init\n```\n\nThe vault structure is created with the following organization:\n\n```\n.vault/\n├── brain/           # Brain notes (agent memory)\n├── work/            # Work-related notes\n├── org/             # Organizational notes\n├── perf/            # Performance metrics\n├── .palace/         # Palace metadata (internal)\n│   ├── wings/\n│   ├── rooms/\n│   └── tunnels/\n└── .kg/             # Knowledge graph (SQLite)\n    └── knowledge.db\n```\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n### Verify Vault Health\n\nCheck that everything is properly configured:\n\n```bash\nao status\n```\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## CLI Command Reference\n\nOMPA provides 14 CLI commands for vault operations. All commands are prefixed with `ao`.\n\n### Session Lifecycle Commands\n\n| Command | Description |\n|---------|-------------|\n| `ao session-start` | Inject memory context at session start (~2K token context) |\n| `ao wrap-up` | Session summary and persist to vault |\n| `ao stop` | Clean session shutdown |\n| `ao status` | Vault health status and statistics |\n\n### Note Management Commands\n\n| Command | Description |\n|---------|-------------|\n| `ao classify <msg>` | Classify and route a message to the correct folder |\n| `ao search <query>` | Semantic search across vault notes |\n| `ao orphans` | Detect orphaned notes (broken wikilinks) |\n| `ao init` | Initialize a new vault |\n| `ao validate` | Validate vault structure integrity |\n\n### Knowledge Graph Commands\n\n| Command | Description |\n|---------|-------------|\n| `ao kg-query <entity>` | Query knowledge graph for entity |\n| `ao kg-timeline <entity>` | Entity timeline view |\n| `ao kg-stats` | Knowledge graph statistics |\n\n### Palace Navigation Commands\n\n| Command | Description |\n|---------|-------------|\n| `ao wings` | List palace wings |\n| `ao rooms <wing>` | List rooms in a wing |\n| `ao tunnel` | Create/traverse cross-wing tunnel |\n\n### Index Management\n\n| Command | Description |\n|---------|-------------|\n| `ao rebuild-index` | Rebuild the semantic index (skips unchanged files) |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Python API Quick Start\n\n### Basic Usage\n\n```python\nfrom ompa import Ompa\n\n# Initialize with vault path\nao = Ompa(vault_path=\"./workspace\")\n\n# Start a session\ncontext = ao.session_start()\n\n# Classify and route a message\nhint = ao.handle_message(\"We decided to go with Postgres\")\n\n# Use tools\nao.post_tool(\"write\", {\"file_path\": \"work/active/auth.md\"})\n\n# Clean shutdown\nao.stop()\n```\n\n### Semantic Search\n\n```python\n# Search with optional wing filter\nresults = ao.search(\"authentication decisions\", wing=\"Orion\")\n\n# Each result contains: path, content_excerpt, score, match_type\nfor result in results:\n    print(f\"{result.path}: {result.score}\")\n```\n\n### Knowledge Graph Operations\n\n```python\n# Add temporal triples\nao.kg.add_triple(\n    \"Kai\", \n    \"works_on\", \n    \"Orion\", \n    valid_from=\"2025-06-01\"\n)\n\n# Query entity history\ntriples = ao.kg.query_entity(\"Kai\")\n\n# Get entity timeline\ntimeline = ao.kg.timeline(\"Orion\")\n```\n\n### Palace Navigation\n\n```python\n# Create a wing\nao.palace.create_wing(\"Orion\")\n\n# Create a room in a wing\nao.palace.create_room(\"Orion\", \"authentication\")\n\n# Create cross-wing tunnels\nao.palace.create_tunnel(\"Orion\", \"Pegasus\", room=\"shared\")\n```\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## MCP Server Integration\n\nThe MCP (Model Context Protocol) server enables OMPA tools to be used directly within AI coding assistants like Claude Desktop, Cursor, and Windsurf.\n\n### Claude Desktop Setup\n\n**Option 1: CLI (Recommended)**\n\n```bash\nclaude mcp add ompa -- python -m ompa.mcp_server\n```\n\n**Option 2: Manual Configuration**\n\nEdit `~/.claude/claude_desktop_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"/absolute/path/to/your/vault\"\n      }\n    }\n  }\n}\n```\n\n### Cursor / Windsurf Setup\n\nCreate `.cursor/mcp.json` in your project root:\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"${workspaceFolder}/.ompa-vault\",\n        \"OMPA_ENABLE_SEMANTIC\": \"false\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n### Available MCP Tools\n\n| Tool | Description |\n|------|-------------|\n| `ao_session_start` | Inject memory context |\n| `ao_classify` | Classify and route message |\n| `ao_search` | Semantic search |\n| `ao_kg_query` | Query knowledge graph |\n| `ao_kg_add` | Add knowledge triple |\n| `ao_kg_stats` | KG statistics |\n| `ao_palace_wings` | List wings |\n| `ao_palace_rooms` | List rooms in wing |\n| `ao_palace_tunnel` | Create/traverse tunnels |\n| `ao_validate` | Validate vault |\n| `ao_wrap_up` | Session summary |\n| `ao_status` | Vault health |\n| `ao_orphans` | Find orphaned notes |\n| `ao_kg_populate` | Populate KG from vault |\n| `ao_sync` | Sync vault |\n| `ao_write` | Write note |\n| `ao_export` | Export note |\n| `ao_import` | Import note |\n| `ao_init` | Initialize vault |\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n| `OMPA_ISOLATION_MODE` | `auto` | Isolation mode (auto/strict) |\n\n### Verifying Connection\n\nOnce connected, ask your AI assistant:\n\n> \"Use the `ao_status` tool to check my OMPA vault health\"\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md), [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n---\n\n## Dual-Vault Mode\n\nOMPA supports isolating team/organizational content from personal notes using a dual-vault architecture.\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\n\nao = Ompa(config=config)\n```\n\n### Isolation Modes\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified to shared or personal vault based on message type |\n| `STRICT` | Strict isolation, no cross-vault access |\n| `MANUAL` | Explicit `VaultTarget` routing per operation |\n\n### MCP Dual-Vault Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_SHARED_VAULT\": \"/path/to/shared-vault\",\n        \"OMPA_PERSONAL_VAULT\": \"/path/to/personal-vault\",\n        \"OMPA_ISOLATION_MODE\": \"auto\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[AI Agent] --> B[OMPA Core]\n    B --> C[Vault Layer]\n    B --> D[Palace Layer]\n    B --> E[Knowledge Graph]\n    \n    C --> C1[brain/]\n    C --> C2[work/]\n    C --> C3[org/]\n    C --> C4[perf/]\n    \n    D --> D1[Wings]\n    D --> D2[Rooms]\n    D --> D3[Tunnels]\n    \n    E --> E1[SQLite DB]\n    E --> E2[Temporal Triples]\n    \n    F[MCP Server] --> B\n    F --> G[Claude Desktop]\n    F --> H[Cursor]\n    F --> I[Windsurf]\n```\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n---\n\n## Framework Compatibility\n\nOMPA integrates with multiple AI agent frameworks:\n\n| Agent Framework | Integration Method |\n|-----------------|-------------------|\n| Claude Code | Python API + MCP server |\n| OpenClaw | Python API + MCP server |\n| Codex | Python API + MCP server |\n| Gemini CLI | Python API + MCP server |\n| LangChain | Python API adapter |\n| LlamaIndex | Python API adapter |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Typical Session Workflow\n\n```mermaid\ngraph LR\n    A[Session Start] --> B[ao session-start]\n    B --> C[Memory Context Injected]\n    C --> D[Work Session]\n    D --> E[ao classify]\n    D --> F[ao search]\n    D --> G[ao kg-query]\n    E --> H[Notes Created]\n    F --> H\n    G --> H\n    H --> I[Session End]\n    I --> J[ao wrap-up]\n    J --> K[Notes Persisted]\n    K --> L[KG Updated]\n```\n\n1. **Start session**: `ao session-start` injects ~2K tokens of relevant context\n2. **Classify messages**: `ao classify` routes content to appropriate folders\n3. **Search**: `ao search` finds relevant past notes semantically\n4. **Query KG**: `ao kg-query` retrieves entity relationships\n5. **Wrap up**: `ao wrap-up` summarizes and persists everything\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n## Testing Your Installation\n\nRun the test suite to verify everything works:\n\n```bash\npytest tests/ -v\n```\n\nAll 77+ tests should pass. Tests are located in `tests/test_ompa.py`.\n\n资料来源：[CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n\n---\n\n## Next Steps\n\n- **Explore CLI**: Run `ao --help` for all available commands\n- **Configure MCP**: Set up your preferred AI assistant integration\n- **Add message types**: Extend the classifier for custom routing 资料来源：[CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- **Add hooks**: Implement custom lifecycle hooks for your workflow\n- **API stability**: Review [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md) for public API commitments\n\n---\n\n<a id='comparison'></a>\n\n## Feature Comparison\n\n### 相关页面\n\n相关主题：[Introduction to OMPA](#introduction)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n- [ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n- [ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n</details>\n\n# Feature Comparison\n\nOMPA (Obsidian-MemPalace-Agnostic) is a memory management system for AI agents that provides persistent context injection, semantic search, temporal knowledge graphs, and palace-style memory navigation. This page compares the various features, components, and integration options available in the project.\n\n## Architecture Overview\n\nOMPA follows a dual-layer architecture where the **Vault** serves as the source of truth for notes, and the **Palace** provides retrieval acceleration through metadata organization.\n\n```mermaid\ngraph TD\n    A[Agent Session] --> B[Ompa Core]\n    B --> C[Vault Layer]\n    B --> D[Palace Layer]\n    B --> E[Knowledge Graph]\n    B --> F[Semantic Index]\n    C --> G[brain/ work/ org/ perf/]\n    D --> H[Wings → Rooms → Drawers]\n    E --> I[SQLite Triples]\n    F --> J[Local Embeddings]\n```\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## Core Components\n\n### Package Structure\n\nThe codebase is organized into modular components, each handling a specific responsibility.\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| Core | `core.py` | Main class, lifecycle management, dual-vault support |\n| Vault | `vault.py` | Note CRUD, folder structure, path traversal guards |\n| Palace | `palace.py` | Wings/rooms/drawers metadata, tunnel navigation |\n| Knowledge Graph | `knowledge_graph.py` | Temporal SQLite triples with validity windows |\n| Semantic | `semantic.py` | Local embedding-based search with lazy model loading |\n| Classifier | `classifier.py` | 15 message types with auto-routing |\n| Hooks | `hooks.py` | 5 lifecycle hooks with HookManager |\n| MCP Server | `mcp_server.py` | JSON-RPC protocol over stdin/stdout |\n| CLI | `cli.py` | 14 typer commands |\n| Config | `config.py` | DualVaultConfig, IsolationMode, VaultTarget |\n\n资料来源：[README.md:70-83](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## Installation Options\n\nOMPA offers tiered installation to accommodate different use cases.\n\n| Option | Command | Included Features |\n|--------|---------|-------------------|\n| Core | `pip install ompa` | Vault, palace, KG, CLI, MCP server |\n| Full | `pip install ompa[all]` | Core + sentence-transformers + numpy (semantic search) |\n| Dev | `pip install ompa[dev]` | Development dependencies |\n| Source | `pip install -e \".[all]\"` | Latest features from main branch |\n\n资料来源：[README.md:52-60](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### Environment Variables\n\n| Variable | Default | Description |\n|---|---|---|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n## Dual-Vault Architecture\n\nOMPA supports isolating team/organization content from personal or private notes through a dual-vault architecture.\n\n### Isolation Modes\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified to shared or personal vault based on message type |\n| `MANUAL` | Explicit `VaultTarget` routing per operation |\n| `STRICT` | Enforced separation with sanitization on export |\n\n资料来源：[CHANGELOG.md:2026-04-10](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n### Configuration\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\nao = Ompa(config=config)\n```\n\n资料来源：[README.md:28-36](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### Dual-Vault MCP Tools\n\n| Tool | Purpose |\n|------|---------|\n| `ao_dual_vault_*` | Shared vault operations |\n| Export | Cross-vault export with sanitization |\n| Import | Cross-vault import |\n\n资料来源：[CHANGELOG.md:2026-04-10](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Message Classification\n\nThe classifier categorizes incoming agent messages into 15 types with auto-routing.\n\n### Message Types\n\n| Type | Detected Patterns | Suggested Folder |\n|------|-------------------|------------------|\n| `DECISION` | ADR, agreed to, settled on, defer | org/decisions |\n| `INCIDENT` | incident, outage, bug, crash, debug | work/incidents |\n| `WIN` | won, shipped, launched, deployed | org/wins |\n| `ONE_ON_ONE` | 1:1, check-in, feedback, career | personal/1on1 |\n| `MEETING` | meeting, agenda, takeaways | work/meetings |\n| `PROJECT_UPDATE` | project, initiative, blocked on | work/projects |\n| `PERSON_INFO` | teammate, joined, role change | org/people |\n| `QUESTION` | how do, what is, explain | brain/questions |\n| `TASK` | task, todo, action item | work/tasks |\n| `ARCHITECTURE` | architecture, design, ADR | org/architecture |\n| `CODE` | function, class, PR, commit | work/code |\n| `BRAIN_DUMP` | dump, stream, btw | brain/dumps |\n| `WRAP_UP` | wrap up, end session | brain/sessions |\n| `STANDUP` | standup, daily, morning | work/standups |\n| `GENERAL` | Fallback for unmatched | brain/misc |\n\n资料来源：[ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n\n## CLI Commands\n\nThe `ao` CLI provides 14 commands for vault operations.\n\n| Command | Description |\n|---------|-------------|\n| `ao init` | Initialize a new vault |\n| `ao status` | Health check and statistics |\n| `ao session-start` | Inject memory context (~2K tokens) |\n| `ao classify <msg>` | Classify and route a message |\n| `ao search <query>` | Semantic search |\n| `ao orphans` | Detect orphaned notes |\n| `ao wrap-up` | Session summary and save |\n| `ao wings` | List palace wings |\n| `ao rooms <wing>` | List rooms in a wing |\n| `ao tunnel` | Create/traverse cross-wing tunnel |\n| `ao kg-query <entity>` | Query knowledge graph |\n| `ao kg-timeline <entity>` | Entity timeline |\n| `ao kg-stats` | Knowledge graph statistics |\n| `ao validate` | Validate vault structure |\n| `ao rebuild-index` | Rebuild the semantic index |\n\n资料来源：[README.md:42-57](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## MCP Server Tools\n\nThe MCP server exposes 15 tools via JSON-RPC protocol over stdin/stdout.\n\n### Tool List\n\n| Tool | Category | Purpose |\n|------|----------|---------|\n| `ao_session_start` | Lifecycle | Session initialization |\n| `ao_classify` | Classifier | Message classification |\n| `ao_search` | Search | Semantic search in vault |\n| `ao_kg_query` | KG | Entity query |\n| `ao_kg_add` | KG | Add triple |\n| `ao_kg_stats` | KG | KG statistics |\n| `ao_kg_timeline` | KG | Entity timeline |\n| `ao_kg_populate` | KG | Populate from vault |\n| `ao_palace_wings` | Palace | List wings |\n| `ao_palace_rooms` | Palace | List rooms |\n| `ao_palace_tunnel` | Palace | Cross-wing navigation |\n| `ao_validate` | Vault | Validate structure |\n| `ao_wrap_up` | Lifecycle | Session wrap-up |\n| `ao_status` | Vault | Health status |\n| `ao_orphans` | Vault | Orphan detection |\n\n资料来源：[ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n\n### MCP Protocol Version\n\n| Property | Value |\n|----------|-------|\n| Protocol Version | `2024-11-05` |\n| Server Name | `ompa` |\n| Transport | stdin/stdout JSON-RPC |\n\n## Framework Compatibility\n\nOMPA is designed to be framework-agnostic with no agent SDK dependencies.\n\n| Agent Framework | Integration Method |\n|---|---|\n| Claude Code | Python API + MCP server |\n| OpenClaw | Python API + MCP server |\n| Codex | Python API + MCP server |\n| Gemini CLI | Python API + MCP server |\n| LangChain | Python API (adapters) |\n\n资料来源：[README.md:88-94](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### MCP Desktop Integration\n\n| Desktop IDE | Configuration File |\n|-------------|-------------------|\n| Claude Desktop | `~/.claude/claude_desktop_config.json` |\n| Cursor | `.cursor/mcp.json` |\n| Windsurf | `.windsurf/mcp.json` |\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n## Lifecycle Hooks\n\nOMPA provides 5 lifecycle hooks for extensibility.\n\n| Hook | Trigger | Token Budget | Purpose |\n|------|---------|--------------|---------|\n| `session_start` | Session begin | 2000 | Context injection |\n| `user_message` | Each user message | 100 | Pre-process hints |\n| `post_tool` | After tool execution | 100 | Result capture |\n| `pre_compact` | Before context compaction | 500 | Summary generation |\n| `stop` | Session end | 200 | Persist and cleanup |\n\n资料来源：[ompa/hooks.py](https://github.com/jmiaie/ompa/blob/main/ompa/hooks.py)\n\n### Hook Data Structures\n\n```python\nHookResult(hook_name, success, output, tokens_hint, error)\nHookContext(vault_path, session_id, timestamp, agent_name, memory)\n```\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n\n## Knowledge Graph\n\n### Data Model\n\n```mermaid\ngraph LR\n    A[Subject] -->|Predicate| B[Object]\n    B -->|valid_from| C[Start Date]\n    B -->|valid_to| D[End Date]\n    B -->|confidence| E[Score]\n    B -->|source| F[File]\n```\n\n### API Methods\n\n| Method | Description |\n|--------|-------------|\n| `kg.add_triple()` | Add temporal triple |\n| `kg.query_entity()` | Query entity relationships |\n| `kg.timeline()` | Query entity history |\n| `kg.populate_from_vault()` | Extract from notes |\n\n资料来源：[ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n\n## Semantic Search\n\n### Features\n\n| Feature | Description |\n|---------|-------------|\n| Incremental indexing | Tracks file modification times, re-embeds only changed notes |\n| Lazy model loading | Model download deferred until first access |\n| Local embeddings | No API calls required |\n\n资料来源：[CHANGELOG.md:2026-04-08](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Stable APIs\n\nThe following APIs are guaranteed stable within major versions.\n\n### Data Classes\n\n```python\nHookResult(hook_name, success, output, tokens_hint, error)\nClassification(message_type, confidence, suggested_action, routing_hints)\nSearchResult(path, content_excerpt, score, match_type)\nTriple(subject, predicate, object, valid_from, valid_to, confidence, source_file)\nSyncResult(success, backend, direction, files_changed, message, error, details)\n```\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n\n### Enums\n\n```python\nMessageType      # 15 values: DECISION, INCIDENT, WIN, ...\nIsolationMode    # AUTO, STRICT, MANUAL\nVaultTarget      # SHARED, PERSONAL\n```\n\n## Security Features\n\n| Feature | Implementation |\n|---------|----------------|\n| Path traversal protection | All vault file operations resolve and boundary-check paths |\n| Dual-vault isolation | Content separation with sanitization |\n| UTF-8 enforcement | Explicit encoding for all file writes |\n| Security audit | 8/10 rating with 59/59 tests passing |\n\n资料来源：[CHANGELOG.md:2026-04-11](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Python Version Requirements\n\n| Version | Status |\n|---------|--------|\n| Python 3.10+ | Required |\n| Earlier versions | Not supported |\n\n资料来源：[README.md:65](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n---\n\n<a id='three-layer-architecture'></a>\n\n## Three-Layer Architecture\n\n### 相关页面\n\n相关主题：[Vault System](#vault-system), [Palace System](#palace-system), [Knowledge Graph](#knowledge-graph)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [ompa/vault.py](https://github.com/jmiaie/ompa/blob/main/ompa/vault.py)\n- [ompa/palace.py](https://github.com/jmiaie/ompa/blob/main/ompa/palace.py)\n- [ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n- [ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n- [ompa/config.py](https://github.com/jmiaie/ompa/blob/main/ompa/config.py)\n- [ompa/cli.py](https://github.com/jmiaie/ompa/blob/main/ompa/cli.py)\n</details>\n\n# Three-Layer Architecture\n\nOMPA implements a three-layer architecture designed for AI agent memory management. Each layer serves a distinct purpose while maintaining loose coupling through well-defined interfaces. This architecture separates storage (Vault), retrieval acceleration (Palace), and temporal relationship tracking (Knowledge Graph).\n\n## Overview\n\nThe three layers work in concert to provide comprehensive memory capabilities for AI agents:\n\n| Layer | Primary Role | Technology | Purpose |\n|-------|--------------|------------|---------|\n| **Vault** | Source of truth | File system (Markdown) | Persistent storage of notes and context |\n| **Palace** | Retrieval acceleration | Metadata + indexing | Fast navigation through spatial metaphors |\n| **Knowledge Graph** | Temporal relationships | SQLite | Track entity relationships over time |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)  \n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## Architecture Diagram\n\n```mermaid\ngraph TB\n    subgraph \"Layer 1: Vault\"\n        V[Vault Manager]\n        VF[Vault Folders<br/>brain/work/org/perf]\n        VP[Path Traversal Guards]\n    end\n    \n    subgraph \"Layer 2: Palace\"\n        P[Palace Manager]\n        PW[Wings/Rooms/Drawers]\n        PT[Tunnels]\n    end\n    \n    subgraph \"Layer 3: Knowledge Graph\"\n        KG[Knowledge Graph]\n        KGS[SQLite Triples]\n        KGT[Temporal Validity Windows]\n    end\n    \n    A[Agent/AI] --> C[Ompa Core]\n    C --> V\n    C --> P\n    C --> KG\n    \n    V --> VF\n    P --> PW\n    KG --> KGS\n    \n    C --> CI[Classifier]\n    CI --> VF\n    \n    style V fill:#e1f5fe\n    style P fill:#fff3e0\n    style KG fill:#e8f5e9\n```\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## Layer 1: Vault\n\nThe Vault layer serves as the source of truth for all memory content. Notes are stored as Markdown files with YAML frontmatter on the file system.\n\n### Purpose and Scope\n\nThe Vault layer handles all CRUD operations for notes, enforces path security boundaries, and organizes content into logical folders based on message type classification. Every piece of information stored in OMPA ultimately lives in the Vault.\n\n资料来源：[ompa/vault.py](https://github.com/jmiaie/ompa/blob/main/ompa/vault.py)\n\n### Folder Structure\n\nNotes are automatically routed to appropriate folders based on the `MessageType` classifier:\n\n| Folder | Message Types | Content Category |\n|--------|---------------|------------------|\n| `brain/` | Brain-related | Core memories, session context |\n| `work/` | Work-related | Professional decisions, projects |\n| `org/` | Organization-related | Team information, processes |\n| `perf/` | Performance-related | Metrics, evaluations |\n\n资料来源：[CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n\n### Security Features\n\nAll Vault file operations implement path traversal protection:\n\n```python\ndef _safe_resolve(vault_root: str, file_path: str) -> Path:\n    # Resolves path and validates it stays within vault boundary\n    # Raises SecurityError if traversal detected\n```\n\nPath boundaries are checked before any file read or write operation, preventing unauthorized access to files outside the vault directory. 资料来源：[CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n### Dual-Vault Mode\n\nThe Vault layer supports dual-vault isolation for separating personal and shared content:\n\n```python\nfrom ompa import DualVaultConfig, IsolationMode, VaultTarget\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\n```\n\n**Isolation Modes:**\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified based on message type |\n| `MANUAL` | Explicit `VaultTarget` routing per operation |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## Layer 2: Palace\n\nThe Palace layer provides spatial organization and retrieval acceleration using the memory palace metaphor. It adds metadata structure on top of the Vault for fast navigation.\n\n### Purpose and Scope\n\nThe Palace layer enables agents to navigate memories using spatial concepts (wings, rooms, drawers). This mirrors the ancient method of loci technique, proven effective for memory retrieval.\n\n> \"Verbatim storage: No summarization (proven 96.6% R@5 by MemPalace)\"\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n### Palace Components\n\n| Component | Description | Purpose |\n|-----------|-------------|---------|\n| **Wing** | Top-level organizational unit | Group related rooms |\n| **Room** | Contains drawers and notes | Thematic organization |\n| **Drawer** | Container within rooms | Fine-grained categorization |\n| **Hall** | Cross-cutting collection | Shared resources |\n| **Tunnel** | Connections between wings | Navigate across domains |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n### Palace Operations\n\n```python\n# Create organizational structure\nao.palace.create_wing(\"Orion\")\nao.palace.create_room(\"Orion\", \"decisions\")\nao.palace.create_drawer(\"Orion\", \"decisions\", \"auth\")\n\n# Navigate with tunnels\nao.palace.create_tunnel(\"Orion\", \"Phoenix\", room=\"shared\")\n```\n\n### Relationship to Vault\n\nThe Palace layer does not store content directly—it maintains metadata references to Vault notes. This separation allows the Palace structure to evolve independently of note content.\n\n```mermaid\ngraph LR\n    V[Vault Notes] --> P[Palace Metadata]\n    P --> P1[Wings/Rooms Index]\n    P --> P2[Note References]\n    \n    S[Search Query] --> P\n    P --> R[Matched Notes]\n```\n\n资料来源：[ompa/palace.py](https://github.com/jmiaie/ompa/blob/main/ompa/palace.py)\n\n## Layer 3: Knowledge Graph\n\nThe Knowledge Graph layer maintains temporal relationships between entities using SQLite-backed triple storage.\n\n### Purpose and Scope\n\nThe Knowledge Graph tracks facts about entities (subjects) and their relationships (predicates) to other entities (objects), with validity time windows for temporal queries.\n\n> \"Temporal KG: SQLite triples with validity windows\"\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n### Data Model\n\nEach triple consists of:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `subject` | string | Source entity |\n| `predicate` | string | Relationship type |\n| `object` | string | Target entity |\n| `valid_from` | datetime | Start of validity period |\n| `valid_to` | datetime | End of validity period (nullable) |\n| `source` | string | Origin of the fact |\n\n### Knowledge Graph Operations\n\n```python\n# Add a fact with temporal validity\nao.kg.add_triple(\n    subject=\"Kai\",\n    predicate=\"works_on\",\n    object=\"Orion\",\n    valid_from=\"2025-06-01\"\n)\n\n# Query entity history\ntriples = ao.kg.query_entity(\"Kai\")\n\n# Get entity timeline\ntimeline = ao.kg.timeline(\"Orion\")\n```\n\n### Temporal Queries\n\nThe Knowledge Graph supports querying state as of a specific point in time:\n\n```python\n# Query historical state\ntriples = ao.kg.query_entity(\"Kai\", as_of=\"2025-07-15\")\n```\n\nThis enables agents to reason about past states of knowledge without needing to track version history manually.\n\n## Layer Interactions\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant A as Agent\n    participant C as Ompa Core\n    participant CL as Classifier\n    participant V as Vault\n    participant P as Palace\n    participant KG as Knowledge Graph\n    \n    A->>C: handle_message(\"We decided...\")\n    C->>CL: classify(content)\n    CL-->>C: Classification(WorkDecision)\n    C->>V: save_note(WorkDecision)\n    V-->>C: Note saved\n    C->>P: update_structure(content)\n    C->>KG: extract_entities(content)\n    \n    Note over C: Dual-vault routing<br/>applies if configured\n```\n\n### Content Lifecycle\n\n1. **Ingestion**: Message arrives at `Ompa.handle_message()`\n2. **Classification**: `Classifier` determines message type and routing\n3. **Storage**: Note saved to appropriate Vault (shared or personal)\n4. **Organization**: Palace metadata updated\n5. **Relationship**: Entities extracted and added to Knowledge Graph\n\n```mermaid\ngraph TD\n    I[Ingest Message] --> C[Classify]\n    C --> R{Routing Mode}\n    R -->|AUTO| A[Auto-classify]\n    R -->|MANUAL| M[Manual Target]\n    A --> VT{Vault Target}\n    M --> VT\n    VT -->|Shared| VS[Write to Shared Vault]\n    VT -->|Personal| VP[Write to Personal Vault]\n    \n    VS --> P[Update Palace]\n    VP --> P\n    P --> KG[Extract Entities]\n    KG --> KGA[Add to KG]\n```\n\n### Search Integration\n\n```mermaid\ngraph TD\n    SQ[Search Query] --> C[Ompa Core]\n    C -->|Semantic| SI[Semantic Index]\n    C -->|Hybrid| H[Combine]\n    C -->|KG| KGQ[KG Query]\n    \n    SI --> I[Incremental Index]\n    H --> RE[Rank Results]\n    KGQ --> RE\n    \n    RE --> R[Return Results]\n```\n\nThe Semantic Index tracks file modification times and only re-embeds changed notes. 资料来源：[CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Configuration\n\n### Constructor Parameters\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(\n    vault_path=\"./workspace\",           # Primary vault path\n    agent_name=\"agent\",                 # Scopes KG entries\n    enable_semantic=True,              # Enable local semantic search\n    embedding_backend=None,            # Custom embedding backend\n    shared_vault_path=None,            # Dual-vault shared vault\n    personal_vault_path=None,          # Dual-vault personal vault\n    isolation_mode=\"strict\",           # AUTO, MANUAL, or STRICT\n)\n```\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n## CLI Commands by Layer\n\n| Command | Layer | Description |\n|---------|-------|-------------|\n| `ao init` | Vault | Initialize vault structure |\n| `ao status` | Vault | Health check and stats |\n| `ao classify <msg>` | Classifier | Classify and route message |\n| `ao search <query>` | Palace/Semantic | Semantic search |\n| `ao wings` | Palace | List palace wings |\n| `ao rooms <wing>` | Palace | List rooms in wing |\n| `ao tunnel` | Palace | Create/traverse tunnel |\n| `ao kg-query <entity>` | Knowledge Graph | Query entity history |\n| `ao kg-timeline <entity>` | Knowledge Graph | Entity timeline |\n| `ao kg-stats` | Knowledge Graph | KG statistics |\n| `ao orphans` | Vault | Detect orphaned notes |\n| `ao validate` | Vault | Validate vault structure |\n| `ao rebuild-index` | Palace/Semantic | Rebuild semantic index |\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## Design Principles\n\nThe three-layer architecture adheres to the following principles documented in the project:\n\n| Principle | Implementation |\n|-----------|-----------------|\n| **Lazy semantic loading** | `SemanticIndex._model` loaded on first access |\n| **Framework-agnostic** | Pure Python, no agent SDK dependencies |\n| **Verbatim storage** | No summarization—proven 96.6% R@5 on LongMemEval |\n| **Path traversal guards** | All vault file ops resolve + boundary-check paths |\n| **Context managers** | All SQLite connections use `with` for leak-free operation |\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## See Also\n\n- [API Stability](STABILITY.md) — Public API guarantees\n- [MCP Server](ompa/mcp_server.py) — MCP protocol integration\n- [CLI Reference](README.md) — Command reference\n- [Contributing Guide](CONTRIBUTING.md) — Development setup\n\n---\n\n<a id='lifecycle-hooks'></a>\n\n## Lifecycle Hooks\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Python API Reference](#python-api)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/hooks.py](https://github.com/jmiaie/ompa/blob/main/ompa/hooks.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n</details>\n\n# Lifecycle Hooks\n\n## Overview\n\nLifecycle Hooks provide a plugin-based extensibility mechanism for the OMPA memory system. They allow developers to intercept and respond to key events during an agent session, such as session initialization, message handling, tool execution, context compaction, and shutdown.\n\nHooks operate as an event-driven layer between the `Ompa` core class and the underlying vault, knowledge graph, and palace subsystems. Each hook receives a `HookContext` containing session metadata and returns a `HookResult` with execution status and token budget information.\n\n## Architecture\n\n### Component Hierarchy\n\n```mermaid\ngraph TD\n    subgraph \"Ompa Core\"\n        A[Ompa Instance] --> B[HookManager]\n    end\n    \n    subgraph \"Hook System\"\n        B --> C[SessionStartHook]\n        B --> D[UserMessageHook]\n        B --> E[PostToolHook]\n        B --> F[PreCompactHook]\n        B --> G[StopHook]\n        B --> H[Custom Hooks]\n    end\n    \n    subgraph \"Hook Infrastructure\"\n        C --> I[HookContext]\n        D --> I\n        E --> I\n        F --> I\n        G --> I\n        I --> J[HookResult]\n    end\n```\n\n### Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant Ompa as Ompa Core\n    participant HookManager\n    participant Hook as Concrete Hook\n    \n    Agent->>Ompa: session_start()\n    Ompa->>HookManager: run_session_start(memory)\n    HookManager->>HookContext: create context\n    HookManager->>Hook: execute(context, **kwargs)\n    Hook-->>HookManager: HookResult\n    HookManager-->>Ompa: HookResult\n    Ompa-->>Agent: context string (~2K tokens)\n    \n    Agent->>Ompa: handle_message(msg)\n    Ompa->>HookManager: run_user_message(message)\n    HookManager->>Hook: execute(context, message)\n    Hook-->>HookManager: HookResult\n```\n\n## Core Data Models\n\n### HookContext\n\nPassed to every hook execution, providing runtime context.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `vault_path` | `Path` | Absolute path to the active vault |\n| `session_id` | `str` | Session identifier in `YYYYMMDD_HHMMSS` format |\n| `timestamp` | `datetime` | Session start time |\n| `agent_name` | `str` | Name of the agent (default: `\"agent\"`) |\n| `memory` | `dict` | Optional memory/context dictionary |\n\n资料来源：[ompa/hooks.py:10-17]()\n\n### HookResult\n\nReturn type from all hook executions.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `hook_name` | `str` | Name of the hook that produced this result |\n| `success` | `bool` | Whether hook execution succeeded |\n| `output` | `str` | Hook output (e.g., context string, summary) |\n| `tokens_hint` | `int` | Estimated token count for LLM context |\n| `error` | `str` | Optional error message if `success=False` |\n\n资料来源：[ompa/hooks.py:19-23]()\n\n### Hook (Base Class)\n\n```python\nclass Hook(ABC):\n    def __init__(self, name: str, token_budget: int = 200):\n        self.name = name\n        self.token_budget = token_budget\n    \n    @abstractmethod\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        ...\n```\n\n资料来源：[ompa/hooks.py:3-12]()\n\n## Default Hooks\n\nOMPA ships with five built-in lifecycle hooks, each handling a specific phase of the agent session.\n\n| Hook | Trigger | Token Budget | Purpose |\n|------|---------|--------------|---------|\n| `session_start` | `Ompa.session_start()` | 200 | Session initialization, context injection |\n| `user_message` | `Ompa.handle_message()` | 50 | Message classification and routing |\n| `post_tool` | `Ompa.post_tool()` | 50 | Tool execution logging |\n| `pre_compact` | `Ompa.pre_compact()` | 200 | Context compression preparation |\n| `stop` | `Ompa.stop()` / `Ompa.wrap_up()` | 200 | Session summary and persistence |\n\n### SessionStartHook\n\nExecutes at session initialization. Collects vault statistics, knowledge graph status, and palace structure to build a ~2K token context for LLM injection.\n\n```python\nclass SessionStartHook(Hook):\n    def __init__(self):\n        super().__init__(\"session_start\", token_budget=200)\n    \n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        # Collect brain notes count\n        # Fetch KG stats (triple count)\n        # Gather palace wing/room structure\n        # Return context string for LLM injection\n```\n\n### StopHook\n\nExecutes during graceful shutdown. Generates a session summary, warns if the knowledge graph is empty, and persists state.\n\n```python\nclass StopHook(Hook):\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        lines = []\n        lines.append(f\"## Session {context.session_id} Summary\")\n        lines.append(f\"Agent: {context.agent_name}\")\n        lines.append(f\"Timestamp: {context.timestamp}\")\n        \n        # KG health warning\n        if kg_stats[\"triple_count\"] == 0:\n            lines.append(\"**WARNING:** KG is empty — run `ao kg-populate`\")\n        \n        return HookResult(hook_name=self.name, success=True, output=output)\n```\n\n资料来源：[ompa/hooks.py:77-119]()\n\n## HookManager\n\nThe `HookManager` class orchestrates hook registration and execution.\n\n```python\nclass HookManager:\n    def __init__(self, vault_path: str | Path, agent_name: str = \"agent\"):\n        self.vault_path = Path(vault_path)\n        self.agent_name = agent_name\n        self.session_id = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n        self.timestamp = datetime.now()\n        \n        # Register default hooks\n        self.hooks = {\n            \"session_start\": SessionStartHook(),\n            \"user_message\": UserMessageHook(),\n            \"post_tool\": PostToolHook(),\n            \"pre_compact\": PreCompactHook(),\n            \"stop\": StopHook(),\n        }\n```\n\n资料来源：[ompa/hooks.py:121-139]()\n\n### Key Methods\n\n| Method | Signature | Description |\n|--------|-----------|-------------|\n| `register_hook` | `register_hook(name: str, hook: Hook)` | Add or replace a hook |\n| `unregister_hook` | `unregister_hook(name: str)` | Remove a hook |\n| `run_session_start` | `run_session_start(memory=None)` | Execute session_start hooks |\n| `run_user_message` | `run_user_message(message: str)` | Execute user_message hooks |\n| `run_post_tool` | `run_post_tool(tool_name, tool_input)` | Execute post_tool hooks |\n| `run_pre_compact` | `run_pre_compact(transcript: str)` | Execute pre_compact hooks |\n| `run_stop` | `run_stop()` | Execute stop hooks |\n\n## Integration with Ompa Core\n\nThe `Ompa` class exposes lifecycle methods that delegate to `HookManager`.\n\n```mermaid\ngraph LR\n    A[Ompa.session_start] --> B[HookManager.run_session_start]\n    C[Ompa.handle_message] --> D[HookManager.run_user_message]\n    E[Ompa.post_tool] --> F[HookManager.run_post_tool]\n    G[Ompa.pre_compact] --> H[HookManager.run_pre_compact]\n    I[Ompa.stop] --> J[HookManager.run_stop]\n    \n    B --> K[HookResult]\n    D --> L[HookResult]\n    F --> M[HookResult]\n    H --> N[HookResult]\n    J --> O[HookResult]\n```\n\n### Ompa Lifecycle Methods\n\n| Method | Alias | Hook Triggered | Returns |\n|--------|-------|-----------------|---------|\n| `ao.session_start()` | `ao.standup()` | `session_start` | `HookResult` |\n| `ao.handle_message(msg)` | — | `user_message` | `HookResult` |\n| `ao.post_tool(name, input)` | — | `post_tool` | `HookResult` |\n| `ao.pre_compact(transcript)` | — | `pre_compact` | `HookResult` |\n| `ao.stop()` | `ao.wrap_up()` | `stop` | `HookResult` |\n\n资料来源：[ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py) (referenced in STABILITY.md)\n\n## Custom Hooks\n\n### Creating a Custom Hook\n\n```python\nfrom ompa.hooks import Hook, HookContext, HookResult\n\nclass MetricsHook(Hook):\n    def __init__(self):\n        super().__init__(\"metrics\", token_budget=50)\n    \n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        session_duration = datetime.now() - context.timestamp\n        output = f\"Session duration: {session_duration}\"\n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=output,\n            tokens_hint=50\n        )\n```\n\n### Registering Custom Hooks\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(\"./workspace\")\nao.hooks.register_hook(\"metrics\", MetricsHook())\n```\n\n### Replacing Default Hooks\n\nOverride default hooks by registering with the same name:\n\n```python\nclass CustomSessionStartHook(Hook):\n    def __init__(self):\n        super().__init__(\"session_start\", token_budget=300)  # Higher budget\n    \n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        # Custom session initialization\n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=\"Custom context...\",\n            tokens_hint=300\n        )\n\nao.hooks.register_hook(\"session_start\", CustomSessionStartHook())\n```\n\n## Hook Execution Patterns\n\n### Pattern: Always Execute\n\nHooks execute on every invocation unless an exception is raised:\n\n```python\nclass PostToolHook(Hook):\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        tool_name = kwargs.get(\"tool_name\")\n        tool_input = kwargs.get(\"tool_input\", {})\n        \n        # Always log tool execution\n        log_entry = f\"[{context.session_id}] {tool_name}: {tool_input}\"\n        append_to_log(context.vault_path / \"tools.log\", log_entry)\n        \n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=\"Tool logged\",\n            tokens_hint=50\n        )\n```\n\n### Pattern: Conditional Execution\n\nHooks can inspect context and conditionally produce output:\n\n```python\nclass UserMessageHook(Hook):\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        message = kwargs.get(\"message\", \"\")\n        \n        if is_sensitive_content(message):\n            return HookResult(\n                hook_name=self.name,\n                success=True,\n                output=\"\",  # No output for sensitive messages\n                tokens_hint=0\n            )\n        \n        # Normal processing for non-sensitive messages\n        ...\n```\n\n## Configuration\n\n### Token Budget\n\nEach hook declares a `token_budget` indicating its expected output size for context window management:\n\n| Budget | Use Case |\n|--------|----------|\n| 0-50 | Simple notifications, acknowledgments |\n| 50-100 | Tool logs, message classifications |\n| 200-300 | Session context, summaries |\n\n### Agent Name Scoping\n\nThe `agent_name` parameter scopes knowledge graph entries and session identifiers:\n\n```python\nao = Ompa(\n    vault_path=\"./workspace\",\n    agent_name=\"coding-agent\"\n)\n\n# HookContext will receive agent_name=\"coding-agent\"\n```\n\n## API Stability\n\nThe hook system follows OMPA's semantic versioning policy. The following are considered stable:\n\n- `Hook` base class (public interface)\n- `HookContext` data class\n- `HookResult` data class\n- `HookManager.register_hook()` method\n\n**Note:** Internal hook implementations (e.g., `*Hook` classes) may change. Use `HookManager.register_hook()` for custom hooks rather than subclassing internal implementations.\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n\n## CLI Integration\n\nWhile hooks operate at the Python API level, they are invoked through CLI commands:\n\n| CLI Command | Hook Invoked |\n|-------------|--------------|\n| `ao session-start` | `session_start` |\n| `ao classify <msg>` | `user_message` |\n| `ao wrap-up` | `stop` |\n| `ao status` | `session_start` (read-only) |\n\n## Error Handling\n\nHooks should return `HookResult` with `success=False` on failure:\n\n```python\ndef execute(self, context: HookContext, **kwargs) -> HookResult:\n    try:\n        result = risky_operation()\n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=str(result),\n            tokens_hint=50\n        )\n    except Exception as e:\n        logger.error(\"Hook %s failed: %s\", self.name, e)\n        return HookResult(\n            hook_name=self.name,\n            success=False,\n            output=\"\",\n            error=str(e)\n        )\n```\n\nThe `HookManager` logs hook failures but continues execution of subsequent hooks.\n\n---\n\n<a id='vault-system'></a>\n\n## Vault System\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Message Classification](#message-classification)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/vault.py](https://github.com/jmiaie/ompa/blob/main/ompa/vault.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [ompa/config.py](https://github.com/jmiaie/ompa/blob/main/ompa/config.py)\n- [ompa/semantic.py](https://github.com/jmiaie/ompa/blob/main/ompa/semantic.py)\n- [ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n</details>\n\n# Vault System\n\n## Overview\n\nThe Vault System is the core data persistence layer in OMPA (Obsidian-MemPalace-Agnostic). It provides structured storage for notes with a multi-category organization model, semantic indexing capabilities, and dual-vault isolation for separating personal and shared content.\n\n**Primary Responsibilities:**\n- Store and retrieve markdown notes with frontmatter metadata\n- Enforce path traversal security boundaries\n- Manage semantic search indices\n- Support dual-vault architecture for content isolation\n- Track knowledge graph relationships from note content\n\n**资料来源：** [README.md](README.md)()\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Vault Layer\"\n        VAULT[Ompa.vault]\n        BRAIN[Brain Notes]\n        WORK[Work Notes]\n        ORG[Org Notes]\n        PERF[Performance Notes]\n    end\n    \n    subgraph \"Dual-Vault Mode\"\n        SHARED[Shared Vault]\n        PERSONAL[Personal Vault]\n        ISOLATION[IsolationMode]\n    end\n    \n    subgraph \"Index Layer\"\n        SEMANTIC[SemanticIndex]\n        KG[KnowledgeGraph]\n    end\n    \n    VAULT --> BRAIN\n    VAULT --> WORK\n    VAULT --> ORG\n    VAULT --> PERF\n    \n    VAULT --> SEMANTIC\n    VAULT --> KG\n    \n    VAULT --> SHARED\n    VAULT --> PERSONAL\n    SHARED --> ISOLATION\n    PERSONAL --> ISOLATION\n```\n\n## Note Categories\n\nThe vault organizes notes into four primary categories based on content type and access patterns.\n\n### Brain Notes\n\nPersonal knowledge, insights, and unstructured information. Brain notes form the foundation of the memory palace and are typically used for capturing ideas, learnings, and personal context.\n\n**资料来源：** [ompa/vault.py](ompa/vault.py)()\n\n### Work Notes\n\nNotes related to professional activities, projects, and work-related decisions. These notes often contain sensitive business information.\n\n**资料来源：** [ompa/vault.py](ompa/vault.py)()\n\n### Org Notes\n\nOrganizational-level notes containing team decisions, processes, and shared knowledge that may be exported to the shared vault.\n\n**资料来源：** [ompa/vault.py](ompa/vault.py)()\n\n### Performance Notes\n\nTime-bounded notes tracking performance metrics, goals, and accomplishments. These notes support the temporal knowledge graph features.\n\n**资料来源：** [ompa/vault.py](ompa/vault.py)()\n\n## Dual-Vault Architecture\n\nThe dual-vault architecture enables isolation between personal and shared content using `DualVaultConfig` and `IsolationMode`.\n\n### Isolation Modes\n\n| Mode | Behavior | Use Case |\n|------|----------|----------|\n| `AUTO` | Content auto-classified based on message type | Automated routing based on classifier results |\n| `MANUAL` | Explicit `VaultTarget` routing per operation | User-controlled content placement |\n| `STRICT` | Strict separation, no cross-vault operations | Maximum isolation requirements |\n\n**资料来源：** [ompa/config.py](ompa/config.py)()\n\n### Vault Targets\n\n```mermaid\ngraph LR\n    MSG[Message] --> CLASSIFY[Classifier]\n    CLASSIFY --> TARGET{IsolationMode}\n    TARGET -->|AUTO| AUTO[Auto-classify]\n    TARGET -->|MANUAL| MANUAL[Manual VaultTarget]\n    TARGET -->|STRICT| STRICT[Strict Mode]\n    \n    AUTO --> SHARED[Shared Vault]\n    AUTO --> PERSONAL[Personal Vault]\n    MANUAL --> SHARED\n    MANUAL --> PERSONAL\n```\n\n### Configuration\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\nao = Ompa(config=config)\n```\n\n**资料来源：** [README.md](README.md)()\n\n### Export/Sanitization\n\nWhen exporting content from personal to shared vault, OMPA automatically sanitizes sensitive information:\n\n- `sk-*` (OpenAI-style API keys)\n- `AKIA*` (AWS access key IDs)\n- `token:`, `password:`, `secret:`, `api_key:`, `api-key:` patterns\n\n**资料来源：** [SECURITY_AUDIT.md](SECURITY_AUDIT.md)()\n\n## Security: Path Traversal Protection\n\nAll vault file operations resolve and boundary-check paths against the vault root before proceeding. This prevents malicious or accidental file access outside the designated vault directory.\n\n### Implementation\n\n| Function | Purpose |\n|----------|---------|\n| `_safe_resolve(vault_root, user_path)` | Resolves path and validates boundaries |\n| Path boundary checks | Raise `ValueError` if path escapes vault root |\n\n**Flow:**\n```mermaid\ngraph TD\n    INPUT[User Path Input] --> RESOLVE[_safe_resolve]\n    RESOLVE --> CHECK{Within Vault Root?}\n    CHECK -->|Yes| PROCEED[Proceed with Operation]\n    CHECK -->|No| REJECT[Raise ValueError]\n```\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)(), [SECURITY_AUDIT.md](SECURITY_AUDIT.md)()\n\n## Note Storage Format\n\nNotes are stored as Markdown files with YAML frontmatter.\n\n### Frontmatter Structure\n\n```yaml\n---\ndate: 2025-06-01\ntags: [tag1, tag2]\nvault: shared  # or \"personal\"\n---\n```\n\n**Content follows frontmatter**\n\n**资料来源：** [ompa/core.py](ompa/core.py)()\n\n### File Naming\n\nWhen creating notes automatically, the system:\n1. Uses the classifier to determine the appropriate folder\n2. Sanitizes content for filename generation\n3. Creates a kebab-case filename from the first 40 characters\n\n**资料来源：** [ompa/core.py](ompa/core.py)()\n\n## Semantic Index\n\nThe `SemanticIndex` class provides local semantic search capabilities using sentence transformers.\n\n### Lazy Initialization\n\nThe embedding model is not loaded until first access, preventing unnecessary downloads during import.\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)()\n\n### Incremental Updates\n\nThe semantic index tracks file modification times and only re-embeds changed notes during rebuilds.\n\n```mermaid\ngraph TD\n    REBUILD[Rebuild Index] --> CHECK{File Changed?}\n    CHECK -->|Modified| RE_EMBED[Re-embed Content]\n    CHECK -->|Unchanged| SKIP[Skip File]\n    RE_EMBED --> UPDATE[Update Index]\n```\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)()\n\n## Knowledge Graph Integration\n\nThe vault integrates with the temporal knowledge graph through automatic population from note content.\n\n### Population Sources\n\n| Source | Description |\n|--------|-------------|\n| Frontmatter tags | Extracted as entities |\n| Folder paths | Used for context |\n| Wikilinks `[[...]]` | Resolved as entity relationships |\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)()\n\n### Triple Extraction\n\nNotes automatically contribute triples to the knowledge graph with:\n- Subject: Extracted entity\n- Predicate: Relationship type\n- Object: Related entity\n- Validity window: Based on note dates\n\n**资料来源：** [ompa/knowledge_graph.py](ompa/knowledge_graph.py)()\n\n## CLI Commands\n\n### Vault Operations\n\n| Command | Description |\n|---------|-------------|\n| `ao init` | Initialize a new vault with required structure |\n| `ao status` | Display vault health check and statistics |\n| `ao validate` | Validate vault structure integrity |\n| `ao orphans` | Detect notes with broken wikilinks |\n| `ao rebuild-index` | Rebuild the semantic search index |\n\n**资料来源：** [README.md](README.md)()\n\n### Index and Search\n\n| Command | Description |\n|---------|-------------|\n| `ao search <query>` | Perform semantic search across notes |\n| `ao kg-query <entity>` | Query knowledge graph for entity |\n| `ao kg-stats` | Display knowledge graph statistics |\n\n**资料来源：** [README.md](README.md)()\n\n## Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n\n**资料来源：** [examples/mcp_desktop/README.md](examples/mcp_desktop/README.md)()\n\n## MCP Server Integration\n\nThe vault is accessible through MCP (Model Context Protocol) tools when integrated with AI assistants.\n\n### Available Tools\n\n```python\nao_init         # Initialize vault\nao_status       # Health check\nao_write        # Write note to vault\nao_export       # Export between vaults\nao_import       # Import into vault\nao_orphans      # Detect orphaned notes\nao_validate     # Validate structure\n```\n\n**资料来源：** [ompa/mcp_server.py](ompa/mcp_server.py)()\n\n## Encoding and Storage\n\nAll vault file writes explicitly enforce UTF-8 encoding to ensure cross-platform compatibility and proper handling of international characters.\n\n**资料来源：** [CHANGELOG.md](CHANGELOG.md)()\n\n## Class Hierarchy\n\n```mermaid\nclassDiagram\n    class Vault {\n        +vault_path: str\n        +notes: list~Note~\n        +create_note()\n        +read_note()\n        +update_note()\n        +delete_note()\n        +list_notes()\n    }\n    \n    class Note {\n        +path: Path\n        +frontmatter: dict\n        +content: str\n        +save()\n        +load()\n    }\n    \n    class SemanticIndex {\n        +_model: EmbeddingModel\n        +embed()\n        +search()\n        +rebuild()\n    }\n    \n    class KnowledgeGraph {\n        +add_triple()\n        +query_entity()\n        +populate_from_vault()\n    }\n    \n    Vault --> Note\n    Vault --> SemanticIndex\n    Vault --> KnowledgeGraph\n```\n\n## Workflow: Session Lifecycle\n\n```mermaid\ngraph TD\n    START[Session Start] --> CONTEXT[ao.session_start]\n    CONTEXT --> CLASSIFY[Message Classification]\n    CLASSIFY --> HANDLE[ao.handle_message]\n    HANDLE --> WRITE[Write to Vault]\n    WRITE --> INDEX[Update Semantic Index]\n    INDEX --> KG[Update Knowledge Graph]\n    KG --> TOOL[Post-tool Hook]\n    TOOL --> WRAP[ao.wrap_up]\n    WRAP --> STOP[ao.stop]\n```\n\n**资料来源：** [ompa/core.py](ompa/core.py)(), [README.md](README.md)()\n\n## Related Documentation\n\n- [Core System](ompa/core.py) — Main Ompa class integrating vault\n- [Classifier System](ompa/classifier.py) — Message classification and routing\n- [Knowledge Graph](ompa/knowledge_graph.py) — Temporal triple storage\n- [Semantic Search](ompa/semantic.py) — Local embedding-based search\n- [MCP Server](ompa/mcp_server.py) — Protocol integration for AI assistants\n\n---\n\n<a id='palace-system'></a>\n\n## Palace System\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Vault System](#vault-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/palace.py](https://github.com/jmiaie/ompa/blob/main/ompa/palace.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n- [ompa/cli.py](https://github.com/jmiaie/ompa/blob/main/ompa/cli.py)\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n</details>\n\n# Palace System\n\nThe Palace System is a metadata layer within OMPA (Obsidian-MemPalace-Agnostic) that provides retrieval acceleration for information stored in the vault. It operates on top of the Vault layer, which serves as the source of truth for all notes, to enable efficient navigation and traversal of memory structures.\n\n## Overview\n\nThe Palace System implements a spatial metaphor for organizing and accessing notes, inspired by the memory palace technique. It provides hierarchical organizational structures (wings, rooms, drawers, halls) and traversal mechanisms (tunnels) that allow agents to navigate complex information spaces efficiently.\n\nThe system follows the architecture decision that the Vault serves as the source of truth while the Palace provides retrieval acceleration. This dual-layer design ensures data persistence alongside fast access patterns.\n\n资料来源：[CLAUDE.md:3]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph OMPA[\"OMPA Core\"]\n        subgraph VaultLayer[\"Vault Layer\"]\n            V[Vault - Source of Truth]\n        end\n        subgraph PalaceLayer[\"Palace Layer - Retrieval Acceleration\"]\n            W[Wings]\n            R[Rooms]\n            D[Drawers]\n            H[Halls]\n            T[Tunnels]\n        end\n    end\n    U[User/Agent] --> API\n    API[CLI / MCP / Python API]\n    API --> PalaceLayer\n    PalaceLayer --> VaultLayer\n```\n\n### Core Components\n\n| Component | Purpose | Storage |\n|-----------|--------|---------|\n| Wings | Top-level organizational units | SQLite metadata |\n| Rooms | Sub-categories within wings | SQLite metadata |\n| Drawers | Fine-grained containers | SQLite metadata |\n| Halls | High-traffic connection paths | SQLite metadata |\n| Tunnels | Cross-wing navigation shortcuts | SQLite metadata |\n\n资料来源：[README.md:1]()\n\n## Palace Metadata Storage\n\nThe Palace System uses SQLite for storing all metadata, with connections managed via context managers to prevent leaks. All temporal data supports validity windows, allowing the system to track how structures evolve over time.\n\n```python\n# Temporal KG with validity windows\n# From ompa/knowledge_graph.py pattern\n```\n\nThe architecture follows lazy semantic loading principles, where palace structures are initialized on first access rather than at import time.\n\n资料来源：[CLAUDE.md:3]()\n\n## Wing Management\n\nWings represent the top-level organizational units in the Palace System. Each wing can contain multiple rooms and serves as a primary navigation anchor.\n\n### Creating Wings\n\n```python\nao.palace.create_wing(\"Orion\")\n```\n\n### Listing Wings\n\n```python\nwings = ao.palace.list_wings()\n```\n\n### Wing Operations via CLI\n\n```bash\nao wings  # List all palace wings\n```\n\n资料来源：[README.md:1]()\n资料来源：[ompa/cli.py](https://github.com/jmiaie/ompa/blob/main/ompa/cli.py)\n\n## Room Management\n\nRooms are sub-categories that belong to specific wings. They provide a second level of hierarchy for organizing palace structures.\n\n### Listing Rooms in a Wing\n\n```python\nrooms = ao.palace.list_rooms(\"Orion\")\n```\n\n### Room Operations via CLI\n\n```bash\nao rooms <wing>  # List rooms in a specific wing\n```\n\n资料来源：[README.md:1]()\n\n## Tunnel System\n\nTunnels enable cross-wing navigation, creating shortcuts between different wings of the palace. This allows agents to traverse between seemingly unrelated areas efficiently.\n\n### Creating Tunnels\n\n```python\nao.palace.create_tunnel(wing_a, wing_b, room=\"shared\")\n```\n\n### Tunnel Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| wing_a | str | Yes | Source wing identifier |\n| wing_b | str | Yes | Target wing identifier |\n| room | str | No | Room through which tunnel passes (default: \"shared\") |\n\n### CLI Tunnel Command\n\n```bash\nao tunnel  # Create/traverse cross-wing tunnel\n```\n\n资料来源：[README.md:1]()\n\n## MCP Server Integration\n\nThe Palace System is exposed via the MCP (Model Context Protocol) server, allowing integration with AI agents like Claude Code, Cursor, and Windsurf.\n\n### Available MCP Tools\n\n| Tool Name | Function | Source |\n|-----------|----------|--------|\n| `ao_palace_wings` | List all palace wings | mcp_server.py:70-73 |\n| `ao_palace_rooms` | List rooms in a wing | mcp_server.py:75-79 |\n| `ao_palace_tunnel` | Create tunnel between wings | mcp_server.py:81-89 |\n\n### MCP Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"/path/to/vault\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[examples/mcp_desktop/README.md:1]()\n\n## CLI Commands\n\nThe Palace System can be accessed through the `ao` CLI utility:\n\n```bash\n# List all palace wings\nao wings\n\n# List rooms in a specific wing\nao rooms <wing>\n\n# Create or traverse a tunnel\nao tunnel\n```\n\n资料来源：[README.md:1]()\n\n## Integration with Core OMPA\n\nThe Palace System is instantiated as part of the main `Ompa` class:\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(vault_path=\"./workspace\")\n# Palace is available at ao.palace\nwings = ao.palace.list_wings()\n```\n\nThe `Ompa` class manages the lifecycle of the Palace instance, ensuring it shares the same vault path and configuration.\n\n资料来源：[ompa/core.py:1]()\n\n## Statistics and Monitoring\n\nThe Palace System provides statistics about its current state:\n\n```python\n# Via Python API\nstats = ao.palace.stats()\n\n# Via MCP\nresult = ao_palace_stats(vault_path)\n\n# Via CLI (combined with vault and KG stats)\nao status\n```\n\nThe status command returns a combined view of vault health, palace metadata, and knowledge graph statistics.\n\n资料来源：[ompa/mcp_server.py:70-73]()\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI\n    participant MCP\n    participant Ompa\n    participant Palace\n    participant Vault\n    participant SQLite\n    \n    User->>CLI: ao wings\n    CLI->>Ompa: list_wings()\n    Ompa->>Palace: list_wings()\n    Palace->>SQLite: Query wings metadata\n    SQLite-->>Palace: Wing list\n    Palace-->>Ompa: Wing list\n    Ompa-->>CLI: Wing list\n    CLI-->>User: Display wings\n    \n    User->>MCP: ao_palace_rooms(wing=\"Orion\")\n    MCP->>Ompa: list_rooms(\"Orion\")\n    Ompa->>Palace: list_rooms()\n    Palace->>SQLite: Query rooms WHERE wing=\"Orion\"\n    SQLite-->>Palace: Room list\n    Palace-->>Ompa: Room list\n    Ompa-->>MCP: Room list\n    MCP-->>User: Display rooms\n```\n\n## Design Principles\n\n1. **Vault + Palace Dual-Layer**: The vault serves as the source of truth while the palace provides retrieval acceleration\n2. **Context Managers**: All SQLite connections use `with` statements for leak-free operation\n3. **Lazy Initialization**: Palace structures are loaded on first access rather than at import time\n4. **Temporal Support**: Palace metadata supports validity windows for tracking structural changes over time\n\n资料来源：[CLAUDE.md:3]()\n\n## See Also\n\n- [Vault System](vault.md) - Source of truth layer\n- [Knowledge Graph](knowledge_graph.md) - Temporal triple storage\n- [Classifier](classifier.md) - Message type classification and routing\n- [MCP Server Setup](examples/mcp_desktop/README.md) - Agent integration guide\n\n---\n\n<a id='knowledge-graph'></a>\n\n## Knowledge Graph\n\n### 相关页面\n\n相关主题：[Three-Layer Architecture](#three-layer-architecture), [Palace System](#palace-system)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n- [ompa/mcp_server.py](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n</details>\n\n# Knowledge Graph\n\nThe Knowledge Graph (KG) is a core temporal data storage component in OMPA that maintains structured relationships between entities using SQLite-backed triple storage. It enables agents to query historical information, track entity validity windows, and maintain a persistent memory of facts across sessions.\n\n## Overview\n\nThe Knowledge Graph stores facts as **triples** (subject, predicate, object) with temporal validity windows, allowing queries like \"What was the state of X at time Y?\" or \"Show me all relationships involving entity Z.\"\n\n| Property | Value |\n|----------|-------|\n| Storage Backend | SQLite |\n| Data Model | RDF-like triples with validity windows |\n| Temporal Support | `valid_from` / `valid_to` timestamps |\n| Location | `~/.ompa/knowledge_graph.db` |\n| Population | Auto-populates from vault notes and wikilinks |\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Vault Notes] --> B[populate_from_vault]\n    C[User Message] --> D[add_triple]\n    B --> E[(SQLite DB)]\n    D --> E\n    E --> F[query_entity]\n    E --> G[timeline]\n    E --> H[get_predicates]\n    E --> I[stats]\n    F --> J[Triple Results]\n    G --> K[Timeline View]\n    I --> L[Statistics]\n```\n\nThe KG operates as a layer above the vault, extracting structured data from unstructured notes and providing temporal query capabilities.\n\n资料来源：[ompa/core.py:1-50](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n\n## Core Data Model\n\n### Triple Structure\n\nEach fact in the Knowledge Graph is stored as a triple with temporal metadata:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `subject` | str | Entity name (e.g., \"Kai\", \"Orion\") |\n| `predicate` | str | Relationship type (e.g., \"works_on\", \"owns\") |\n| `object` | str | Target entity or value |\n| `valid_from` | datetime | Start of validity period (nullable) |\n| `valid_to` | datetime | End of validity period (nullable) |\n| `source` | str | Note path that contained this fact |\n\n### Temporal Validity Windows\n\nThe KG supports temporal reasoning through validity windows:\n\n- **Point-in-time facts**: Both `valid_from` and `valid_to` set\n- **Current facts**: Only `valid_from` set (open-ended)\n- **Historical facts**: Both timestamps set to past dates\n\nThis enables queries like retrieving the state of relationships at any past point.\n\n资料来源：[ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n\n## KnowledgeGraph API\n\n### Constructor\n\n```python\nclass KnowledgeGraph:\n    def __init__(self, vault_path: str = \"~/.ompa\"):\n        self.db_path = Path(vault_path) / \"knowledge_graph.db\"\n```\n\nInitializes the KG with a database path under the OMPA config directory. The SQLite database is created automatically on first access.\n\n资料来源：[ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n\n### add_triple\n\nAdds a new fact to the knowledge graph:\n\n```python\ndef add_triple(\n    self,\n    subject: str,\n    predicate: str,\n    object_: str,\n    valid_from: str | None = None,\n    source: str | None = None,\n) -> Triple:\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `subject` | str | Yes | Source entity |\n| `predicate` | str | Yes | Relationship verb |\n| `object_` | str | Yes | Target entity/value |\n| `valid_from` | str | No | ISO date string for start validity |\n| `source` | str | No | Source note path |\n\n**Example:**\n```python\nkg.add_triple(\n    subject=\"Kai\",\n    predicate=\"works_on\",\n    object_=\"Orion\",\n    valid_from=\"2025-06-01\",\n    source=\"brain/people/Kai.md\"\n)\n```\n\n资料来源：[ompa/knowledge_graph.py](https://github.com/jmiaie/ompa/blob/main/ompa/knowledge_graph.py)\n\n### query_entity\n\nRetrieves all triples involving a specific entity:\n\n```python\ndef query_entity(self, entity: str) -> list[Triple]:\n```\n\nReturns all triples where the entity appears as subject or object. Results are ordered by validity window.\n\n### timeline\n\nGets temporal history for an entity:\n\n```python\ndef timeline(self, entity: str) -> list[dict]:\n```\n\nReturns a chronological view of all facts involving the entity, including temporal metadata for each relationship.\n\n### get_predicates\n\nLists all relationship types in the graph:\n\n```python\ndef get_predicates(self, subject: str | None = None) -> list[str]:\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `subject` | str | No | Filter predicates by subject |\n\n### stats\n\nReturns knowledge graph statistics:\n\n```python\ndef stats(self) -> dict:\n```\n\nReturns:\n| Stat | Description |\n|------|-------------|\n| `total_triples` | Total number of stored facts |\n| `unique_subjects` | Count of unique source entities |\n| `unique_predicates` | Count of unique relationship types |\n| `unique_objects` | Count of unique target entities |\n\n### populate_from_vault\n\nScans existing vault notes and extracts structured facts:\n\n```python\ndef populate_from_vault(self, vault_path: str) -> dict:\n```\n\nExtracts entities from:\n- Frontmatter tags\n- Folder paths\n- `[[wikilinks]]` cross-references\n\nThis enables automatic KG initialization from existing note content.\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)\n\n## MCP Server Integration\n\nThe Knowledge Graph is exposed through MCP tools for agent integration:\n\n```mermaid\ngraph LR\n    A[MCP Client] -->|ao_kg_add| B[Add Triple]\n    A -->|ao_kg_query| C[Query Entity]\n    A -->|ao_kg_stats| D[Get Stats]\n    A -->|ao_kg_populate| E[Populate from Vault]\n    B --> F[KnowledgeGraph]\n    C --> F\n    D --> F\n    E --> F\n```\n\n### Available MCP Tools\n\n| Tool | Parameters | Description |\n|------|------------|-------------|\n| `ao_kg_add` | `subject`, `predicate`, `object_`, `valid_from?`, `source?` | Add a fact |\n| `ao_kg_query` | `entity` | Query entity relationships |\n| `ao_kg_stats` | — | Get KG statistics |\n\n资料来源：[ompa/mcp_server.py:1-50](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n\n### MCP Tool Implementation\n\n```python\ndef ao_kg_add(arguments: dict, vault_path: str = \".\") -> dict:\n    \"\"\"Add a triple to the knowledge graph.\"\"\"\n    ao = Ompa(vault_path=vault_path, enable_semantic=False)\n    ao.kg.add_triple(\n        subject=arguments[\"subject\"],\n        predicate=arguments[\"predicate\"],\n        object_=arguments[\"object\"],\n        valid_from=arguments.get(\"valid_from\"),\n        source=arguments.get(\"source\"),\n        vault_path=vault_path,\n    )\n    return {\"success\": True, \"added\": f\"{subject} --{predicate}--> {object_}\"}\n\ndef ao_kg_stats(vault_path: str = \".\") -> dict:\n    \"\"\"Get knowledge graph statistics.\"\"\"\n    ao = Ompa(vault_path=vault_path, enable_semantic=False)\n    return ao.kg.stats()\n```\n\n资料来源：[ompa/mcp_server.py:50-100](https://github.com/jmiaie/ompa/blob/main/ompa/mcp_server.py)\n\n## Usage Examples\n\n### Python API\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(vault_path=\"./workspace\")\n\n# Add facts\nao.kg.add_triple(\"Kai\", \"works_on\", \"Orion\", valid_from=\"2025-06-01\")\nao.kg.add_triple(\"Orion\", \"has_status\", \"active\")\nao.kg.add_triple(\"Kai\", \"reports_to\", \"Sarah\")\n\n# Query entity\ntriples = ao.kg.query_entity(\"Kai\")\n# Returns: [Triple(subject='Kai', predicate='works_on', object_='Orion', ...), ...]\n\n# Get timeline\ntimeline = ao.kg.timeline(\"Kai\")\n# Returns chronological history of all Kai-related facts\n\n# Get statistics\nstats = ao.kg.stats()\n# Returns: {'total_triples': 3, 'unique_subjects': 2, 'unique_predicates': 3, ...}\n```\n\n### CLI Usage\n\n```bash\n# Query entity in knowledge graph\nao kg-query Kai\n\n# Get entity timeline\nao kg-timeline Orion\n\n# Get knowledge graph statistics\nao kg-stats\n```\n\n### MCP Integration\n\nIn Claude Desktop or Cursor, the KG tools are available as:\n\n```json\n{\n  \"mcpServers\": {\n    \"ompa\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"ompa.mcp_server\"],\n      \"env\": {\n        \"OMPA_VAULT_PATH\": \"/absolute/path/to/vault\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[examples/mcp_desktop/README.md](https://github.com/jmiaie/ompa/blob/main/examples/mcp_desktop/README.md)\n\n## Relationship to Other Components\n\n```mermaid\ngraph TD\n    subgraph OMPA Core\n        A[Ompa Class] --> B[KnowledgeGraph]\n        A --> C[Vault]\n        A --> D[SemanticIndex]\n        A --> E[Palace]\n    end\n    \n    B --> F[(SQLite DB)]\n    C --> G[Markdown Notes]\n    D --> H[Sentence Embeddings]\n    E --> I[Metadata Cache]\n    \n    J[MCP Server] --> B\n    J --> C\n    J --> D\n    J --> E\n```\n\n| Component | Relationship | Data Flow |\n|-----------|--------------|-----------|\n| **Vault** | Source of truth | KG populates from vault wikilinks and tags |\n| **SemanticIndex** | Companion retrieval | KG + Index together enable hybrid search |\n| **Palace** | Metadata layer | Palace stores spatial metadata for navigation |\n| **Classifier** | Auto-tagging | Classifier helps route content to vault locations |\n\nThe Knowledge Graph complements the vault by adding structure to unstructured note content.\n\n资料来源：[ompa/core.py:1-100](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n\n## Security Considerations\n\n- **Path traversal guards**: All vault file operations resolve and boundary-check paths\n- **SQLite isolation**: Each KG instance uses separate database file\n- **Source tracking**: Every triple records its source note for auditability\n\n资料来源：[CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n## Changelog\n\n| Version | Date | Change |\n|---------|------|--------|\n| 0.4.0 | 2026-04-10 | Added `populate_from_vault()` for auto-extraction |\n| 0.3.0 | 2026-04-08 | Initial KG implementation with temporal windows |\n| 0.3.1 | 2026-04-09 | Bug fixes in wikilink resolution |\n\n资料来源：[CHANGELOG.md](https://github.com/jmiaie/ompa/blob/main/CHANGELOG.md)\n\n---\n\n<a id='message-classification'></a>\n\n## Message Classification\n\n### 相关页面\n\n相关主题：[Vault System](#vault-system), [Python API Reference](#python-api)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/classifier.py](https://github.com/jmiaie/ompa/blob/main/ompa/classifier.py)\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/jmiaie/ompa/blob/main/CONTRIBUTING.md)\n- [STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)\n</details>\n\n# Message Classification\n\nMessage Classification is a core feature of OMPA that automatically categorizes incoming messages into 15 distinct types and routes them to appropriate locations within the vault structure. This system enables intelligent, automated memory management for AI agents working across different contexts.\n\n## Overview\n\nThe classifier uses regex pattern matching to identify message types based on linguistic cues, then provides routing hints to guide content placement. It integrates deeply with the vault architecture, suggesting target folders and actions for each classified message type.\n\n资料来源：[ompa/classifier.py:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Incoming Message] --> B[Classifier.classify]\n    B --> C{Pattern Matching}\n    C -->|Decision| D[MessageType.DECISION]\n    C -->|Incident| E[MessageType.INCIDENT]\n    C -->|Meeting| F[MessageType.MEETING]\n    C -->|Win| G[MessageType.WIN]\n    C -->|...| H[Other Types]\n    \n    D --> I[Routing Hints]\n    E --> I\n    F --> I\n    G --> I\n    H --> I\n    \n    I --> J[Suggested Folder]\n    I --> K[Suggested Action]\n    \n    J --> L[Vault Storage]\n    K --> M[Knowledge Graph]\n```\n\n资料来源：[ompa/classifier.py:60-120]()\n\n## Message Types\n\nOMPA defines 15 distinct `MessageType` values for classifying different kinds of agent communications:\n\n| Message Type | Purpose | Suggested Folder |\n|--------------|---------|------------------|\n| `DECISION` | Architectural or team decisions | `brain/` |\n| `INCIDENT` | Outages, bugs, failures, debugging | `work/incidents/` |\n| `WIN` | Achievements, successes, milestones | `perf/` |\n| `ONE_ON_ONE` | Manager/peer check-ins | `work/1-1/` |\n| `MEETING` | Meeting notes and takeaways | `work/meetings/` |\n| `PROJECT_UPDATE` | Project status changes | `work/active/` |\n| `PERSON_INFO` | Team member information | `org/people/` |\n| `QUESTION` | Clarifying questions | `brain/questions/` |\n| `TASK` | Action items and todos | `work/tasks/` |\n| `ARCHITECTURE` | System design decisions | `brain/architecture/` |\n| `CODE` | Code-related discussions | `work/code/` |\n| `BRAIN_DUMP` | Stream of consciousness notes | `brain/dumps/` |\n| `WRAP_UP` | Session end summaries | `brain/sessions/` |\n| `STANDUP` | Daily standup entries | `work/standups/` |\n| `GENERAL` | Uncategorized content | `brain/` |\n\n资料来源：[ompa/classifier.py:1-30]()\n资料来源：[CLAUDE.md:1-20]()\n\n## Pattern Matching System\n\nThe classifier uses regex patterns to identify message types. Each `MessageType` has an associated list of regex patterns:\n\n```python\nPATTERNS = {\n    MessageType.DECISION: [\n        r\"\\b(decided|decision|made a choice|going with|settled on|agreed to)\\b\",\n        r\"\\b(defer|postpone|push to|revisit)\\b.*\\b(Q\\d|quarter|sprint)\\b\",\n        r\"(?:ADR|decision record)\",\n    ],\n    MessageType.INCIDENT: [\n        r\"\\b(incident|outage|bug|crash|failure|error|broken)\\b\",\n        r\"\\b(debug|root cause|RCA|mitigation|hotfix)\\b\",\n        r\"(?:on-call|pagerduty|statuspage)\",\n    ],\n    MessageType.WIN: [\n        r\"\\b(won|praised|success|achieved|shipped|launched|deployed)\\b\",\n        r\"\\b(great work|nice job|excellent|well done)\\b\",\n        r\"\\b(milestone|feature complete|released)\\b\",\n    ],\n    # ... additional patterns\n}\n```\n\n资料来源：[ompa/classifier.py:30-100]()\n\n### Pattern Priority\n\nPatterns are evaluated in order, and the first matching pattern determines the message type. This allows for specific patterns to take precedence over general ones.\n\n## Routing Hints\n\nEach message type includes `ROUTING_HINTS` that provide guidance on how to handle classified content:\n\n```python\nROUTING_HINTS = {\n    MessageType.DECISION: [\n        \"This is a decision. Record it in brain/Key Decisions.md\",\n        \"Update relevant project notes with the decision\",\n        \"Add to Decision Log if formal ADR needed\",\n    ],\n    MessageType.INCIDENT: [\n        \"Create incident note in work/incidents/\",\n        \"Run /om-incident-capture for structured capture\",\n        \"Update brain/Gotchas.md with lessons learned\",\n    ],\n    MessageType.WIN: [\n        \"Add to perf/Brag Doc.md immediately\",\n        \"This is a win worth capturing for performance review\",\n        \"Update relevant competency notes with evidence\",\n    ],\n    # ... additional hints\n}\n```\n\n资料来源：[ompa/classifier.py:100-180]()\n\n## Classification API\n\n### Core Classification Method\n\n```python\nfrom ompa.classifier import Classifier, Classification\n\nclassifier = Classifier()\nresult: Classification = classifier.classify(\"We decided to go with Postgres\")\n```\n\n### Return Type\n\nThe `classify()` method returns a `Classification` object containing:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `message_type` | `MessageType` | The identified message type |\n| `confidence` | `float` | Confidence score (0.0 - 1.0) |\n| `routing_hints` | `List[str]` | Actionable suggestions |\n| `suggested_folder` | `str` | Target folder for storage |\n\n资料来源：[ompa/classifier.py:120-150]()\n资料来源：[STABILITY.md:10-20]()\n\n## Dual-Vault Integration\n\nWhen running in dual-vault mode, the classifier also supports content classification for vault routing:\n\n```python\nfrom ompa.config import DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\n\ntarget = config.classify_content(content, tags=tags, file_path=path)\n```\n\n资料来源：[ompa/core.py:50-80]()\n\n### Classification Factors\n\nContent is classified to shared or personal vaults based on:\n\n1. **Content analysis** - Keywords indicating personal vs. work content\n2. **Tags** - Frontmatter tags that may indicate classification\n3. **File path** - Existing location hints in vault structure\n\n## Adding Custom Message Types\n\nTo extend the classifier with new message types, follow this process:\n\n### Step 1: Add Enum Value\n\n```python\n# ompa/classifier.py\nclass MessageType(str, Enum):\n    # ... existing types\n    YOUR_NEW_TYPE = \"your_new_type\"\n```\n\n### Step 2: Add Regex Patterns\n\n```python\nPATTERNS[MessageType.YOUR_NEW_TYPE] = [\n    r\"\\b(keyword1|keyword2)\\b\",\n    r\"\\b(phrase pattern)\\b\",\n]\n```\n\n### Step 3: Add Routing Hints\n\n```python\nROUTING_HINTS[MessageType.YOUR_NEW_TYPE] = [\n    \"Action hint 1\",\n    \"Action hint 2\",\n]\n```\n\n### Step 4: Add Folder Mapping\n\n```python\nFOLDER_MAP[MessageType.YOUR_NEW_TYPE] = \"brain/your-type/\"\n```\n\n### Step 5: Add Tests\n\n```python\n# tests/test_ompa.py\nclass TestClassifier:\n    def test_your_new_type(self):\n        # Add test cases\n```\n\n资料来源：[CONTRIBUTING.md:20-40]()\n\n## CLI Integration\n\nThe classifier is accessible via the CLI:\n\n```bash\n# Classify a single message\nao classify \"We decided to go with Postgres\"\n\n# Classify with context\nao classify \"The deployment failed with a timeout error\"\n```\n\n## MCP Tools\n\nThe following MCP tools expose classification functionality:\n\n| Tool | Purpose |\n|------|---------|\n| `ao_classify` | Classify a message and return routing hints |\n\n资料来源：[ompa/mcp_server.py:1-30]()\n\n## Confidence Scoring\n\nThe classifier assigns confidence scores based on:\n\n1. **Pattern match count** - More pattern matches = higher confidence\n2. **Pattern specificity** - More specific patterns score higher\n3. **Keyword density** - Higher density of type-specific keywords\n\nConfidence is normalized to a 0.0-1.0 range for downstream processing.\n\n## Extensibility Points\n\nThe classification system can be extended through:\n\n1. **Custom patterns** - Add regex patterns per message type\n2. **Custom routing hints** - Extend action suggestions\n3. **Custom folders** - Define target locations per type\n4. **Hook integration** - Execute hooks on classification events\n\n资料来源：[CLAUDE.md:30-50]()\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI as CLI/API\n    participant Classifier\n    participant Vault\n    participant KG as Knowledge Graph\n    \n    User->>CLI: ao classify \"message\"\n    CLI->>Classifier: classify(message)\n    Classifier->>Classifier: Pattern matching\n    Classifier-->>CLI: Classification result\n    CLI-->>User: Type + routing hints\n    \n    User->>CLI: ao handle_message \"message\"\n    CLI->>Classifier: classify(message)\n    Classifier-->>CLI: Classification + folder\n    CLI->>Vault: Save to suggested folder\n    CLI->>KG: Add extracted entities\n    Vault-->>CLI: Note saved\n    KG-->>CLI: Triples added\n```\n\nThis comprehensive classification system enables OMPA to automatically organize agent communications, maintain structured memory, and provide intelligent routing for all types of work content.\n\n---\n\n<a id='python-api'></a>\n\n## Python API Reference\n\n### 相关页面\n\n相关主题：[Lifecycle Hooks](#lifecycle-hooks)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)\n- [ompa/__init__.py](https://github.com/jmiaie/ompa/blob/main/ompa/__init__.py)\n- [ompa/config.py](https://github.com/jmiaie/ompa/blob/main/ompa/config.py)\n- [ompa/async_api.py](https://github.com/jmiaie/ompa/blob/main/ompa/async_api.py)\n</details>\n\n# Python API Reference\n\nThe Python API provides programmatic access to OMPA's core functionality, enabling integration with AI agents, custom workflows, and external applications. The API is designed around the `Ompa` class as the primary entry point, offering lifecycle management, semantic search, knowledge graph operations, and dual-vault isolation.\n\n---\n\n## Installation and Setup\n\n```bash\n# Core package\npip install ompa\n\n# With semantic search (sentence-transformers)\npip install ompa[all]\n\n# Development installation\npip install ompa[dev]\n```\n\nRequires Python 3.10 or higher.\n\n---\n\n## Core Class: `Ompa`\n\nThe `Ompa` class is the main interface for all OMPA operations. It manages the vault, palace, knowledge graph, and lifecycle hooks.\n\n### Constructor\n\n```python\nfrom ompa import Ompa\n\nao = Ompa(\n    vault_path=\"./workspace\",\n    agent_name=\"agent\",\n    enable_semantic=True,\n    embedding_backend=None,\n    shared_vault_path=None,\n    personal_vault_path=None,\n    isolation_mode=\"strict\",\n)\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `vault_path` | `str` | `\".\"` | Absolute path to vault directory |\n| `agent_name` | `str` | `\"agent\"` | Agent identifier for KG scoping |\n| `enable_semantic` | `bool` | `True` | Enable semantic search functionality |\n| `embedding_backend` | `EmbeddingBackend \\| None` | `None` | Custom embedding backend |\n| `shared_vault_path` | `str \\| None` | `None` | Path for shared vault (dual-vault mode) |\n| `personal_vault_path` | `str \\| None` | `None` | Path for personal vault (dual-vault mode) |\n| `isolation_mode` | `IsolationMode \\| str` | `\"strict\"` | Vault isolation mode |\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)()\n\n### Alternative Constructor: Dual-Vault Configuration\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\nao = Ompa(config=config)\n```\n\n---\n\n## Lifecycle Methods\n\nThe lifecycle API manages session boundaries and hook execution for AI agent memory integration.\n\n```mermaid\ngraph TD\n    A[session_start] --> B[handle_message / post_tool]\n    B --> C[pre_compact]\n    C --> D[stop / wrap_up]\n    D --> E[Session Complete]\n```\n\n### `session_start()`\n\nInjects memory context at the start of an agent session.\n\n```python\nresult = ao.session_start()\n```\n\n**Returns:** `HookResult` — Contains `success`, `output`, and `tokens_hint` fields.\n\n**Output:** Approximately 2,000 token context string with session history.\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)()\n\n### `handle_message(message: str)`\n\nProcess and classify an incoming message.\n\n```python\nresult = ao.handle_message(\"We decided to go with Postgres\")\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `message` | `str` | The message content to classify |\n\n**Returns:** `HookResult`\n\n资料来源：[ompa/core.py](https://github.com/jmiaie/ompa/blob/main/ompa/core.py)()\n\n### `post_tool(tool_name: str, tool_input: dict)`\n\nExecute after a tool call to record the action.\n\n```python\nresult = ao.post_tool(\"write\", {\"file_path\": \"work/active/auth.md\"})\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `tool_name` | `str` | Name of the executed tool |\n| `tool_input` | `dict` | Tool input parameters |\n\n**Returns:** `HookResult`\n\n### `pre_compact(transcript: str)`\n\nCalled before context compaction (context window reduction).\n\n```python\nresult = ao.pre_compact(transcript)\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `transcript` | `str` | Full session transcript |\n\n**Returns:** `HookResult`\n\n### `stop()` / `wrap_up()`\n\nEnd the session and persist state. `wrap_up()` is an alias for `stop()`.\n\n```python\nresult = ao.stop()\n# or\nresult = ao.wrap_up()\n```\n\n**Returns:** `HookResult` with session summary and persistence status.\n\n### `standup()`\n\nAlias for `session_start()`. Provides symmetry with `wrap_up()`.\n\n```python\nresult = ao.standup()\n```\n\n---\n\n## Search API\n\n### `search(query, limit, hybrid, wing, room, vaults)`\n\nPerform semantic search across vault notes.\n\n```python\nresults = ao.search(\n    \"authentication decisions\",\n    limit=10,\n    hybrid=True,\n    wing=\"Orion\",\n    room=None,\n    vaults=None\n)\n```\n\n**Parameters:**\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `query` | `str` | Required | Search query string |\n| `limit` | `int` | `5` | Maximum results to return |\n| `hybrid` | `bool` | `False` | Enable hybrid keyword + semantic search |\n| `wing` | `str \\| None` | `None` | Filter by palace wing |\n| `room` | `str \\| None` | `None` | Filter by palace room |\n| `vaults` | `list[str] \\| None` | `None` | Target specific vaults |\n\n**Returns:** `list[SearchResult]` — List of matching notes with relevance scores.\n\n**Cost:** Zero API cost (local semantic search).\n\n资料来源：[README.md](https://github.com/jmiaie/ompa/blob/main/README.md)()\n\n### `rebuild_index()`\n\nRebuild the semantic index from vault contents.\n\n```python\ncount = ao.rebuild_index()\n```\n\n**Returns:** `int` — Number of notes indexed.\n\n---\n\n## Classification API\n\n### `classify(message: str)`\n\nClassify a message into one of 15 message types.\n\n```python\nclassification = ao.classify(\"We decided to go with Postgres\")\n```\n\n**Returns:** `Classification` — Contains `message_type`, `confidence`, `suggested_folder`, and routing hints.\n\n### `get_routing_hint(message: str)`\n\nGet routing hints for a message.\n\n```python\nhint = ao.get_routing_hint(\"We won the enterprise deal!\")\n```\n\n**Returns:** `str` — Routing hint for vault placement.\n\n---\n\n## Knowledge Graph API\n\nThe temporal knowledge graph stores entity relationships with validity windows.\n\n```mermaid\ngraph LR\n    A[Subject] -->|Predicate| B[Object]\n    B -->|valid_from| C[Start Date]\n    B -->|valid_to| D[End Date]\n```\n\n### `kg.add_triple(subject, predicate, object, valid_from, source)`\n\nAdd a triple to the knowledge graph.\n\n```python\nao.kg.add_triple(\n    \"Kai\",\n    \"works_on\",\n    \"Orion\",\n    valid_from=\"2025-06-01\",\n    source=\"session\"\n)\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `subject` | `str` | Source entity |\n| `predicate` | `str` | Relationship type |\n| `object` | `str` | Target entity |\n| `valid_from` | `str \\| None` | Validity start date (YYYY-MM-DD) |\n| `valid_to` | `str \\| None` | Validity end date (YYYY-MM-DD) |\n| `source` | `str \\| None` | Source of this knowledge |\n\n### `kg.query_entity(entity, as_of)`\n\nQuery an entity's history at a point in time.\n\n```python\ntriples = ao.kg.query_entity(\"Kai\")\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `entity` | `str` | Entity name to query |\n| `as_of` | `str \\| None` | Point-in-time filter (YYYY-MM-DD) |\n\n**Returns:** `list[Triple]` — All triples involving the entity.\n\n### `kg.timeline(entity)`\n\nGet timeline of an entity's relationships.\n\n```python\ntimeline = ao.kg.timeline(\"Orion\")\n```\n\n**Returns:** `list[dict]` — Chronological relationship history.\n\n### `kg.stats()`\n\nGet knowledge graph statistics.\n\n```python\nstats = ao.kg.stats()\n```\n\n**Returns:** `dict` — Contains `triple_count`, `entity_count`, `predicate_types`, etc.\n\n---\n\n## Palace API\n\nThe palace provides spatial organization for memories using a metaphor of wings, rooms, drawers, halls, and tunnels.\n\n### `palace.create_wing(name)`\n\nCreate a new wing.\n\n```python\nao.palace.create_wing(\"Orion\")\n```\n\n### `palace.list_wings()`\n\nList all wings.\n\n```python\nwings = ao.palace.list_wings()\n```\n\n### `palace.create_tunnel(wing_a, wing_b, room)`\n\nCreate a cross-wing tunnel for navigation.\n\n```python\nao.palace.create_tunnel(\"Alpha\", \"Beta\", \"Central Hub\")\n```\n\n### `palace.stats()`\n\nGet palace statistics.\n\n```python\nstats = ao.palace.stats()\n```\n\n---\n\n## Vault API\n\n### `get_stats()`\n\nGet vault statistics.\n\n```python\nstats = ao.get_stats()\n```\n\n**Returns:** `dict` containing:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `total_notes` | `int` | Total note count |\n| `brain_notes` | `int` | Brain note count |\n| `by_folder` | `dict` | Notes per folder |\n\n### `write(content, file_path, tags, vault)`\n\nWrite a note to the vault.\n\n```python\nresult = ao.write(\n    content=\"# Decision\\n\\nUsing PostgreSQL\",\n    file_path=\"work/active/db-choice.md\",\n    tags=[\"decision\", \"database\"],\n    vault=None\n)\n```\n\n### `export_to_shared(note_path, confirm, sanitize)`\n\nExport a note from personal vault to shared vault.\n\n```python\nresult = ao.export_to_shared(\n    note_path=\"work/active/auth.md\",\n    confirm=True,\n    sanitize=True\n)\n```\n\n### `import_to_personal(note_path, link_back)`\n\nImport a note from shared vault to personal vault.\n\n```python\nresult = ao.import_to_personal(\n    note_path=\"work/active/auth.md\",\n    link_back=True\n)\n```\n\n### `find_orphans()`\n\nDetect orphaned notes (notes not linked from anywhere).\n\n```python\norphans = ao.find_orphans()\n```\n\n**Returns:** `list[Note]` — Orphaned note objects.\n\n---\n\n## Hooks System\n\nCustom hooks can be registered for lifecycle events.\n\n```python\nfrom ompa.hooks import Hook, HookContext, HookResult\n\nclass MyHook(Hook):\n    def __init__(self):\n        super().__init__(\"my_hook\", token_budget=50)\n\n    def execute(self, context: HookContext, **kwargs) -> HookResult:\n        return HookResult(\n            hook_name=self.name,\n            success=True,\n            output=\"...\",\n            tokens_hint=50\n        )\n\nao = Ompa(\"./workspace\")\nao.hooks.register_hook(\"my_hook\", MyHook())\n```\n\n### Available Hooks\n\n| Hook | Token Budget | Purpose |\n|------|--------------|---------|\n| `session_start` | ~2000 | Context injection at session start |\n| `handle_message` | ~200 | Message processing |\n| `post_tool` | ~100 | Tool execution recording |\n| `pre_compact` | ~500 | Pre-compaction processing |\n| `stop` | ~200 | Session termination |\n\n资料来源：[CLAUDE.md](https://github.com/jmiaie/ompa/blob/main/CLAUDE.md)()\n\n---\n\n## Dual-Vault Configuration\n\nThe dual-vault system separates shared and personal notes.\n\n```python\nfrom ompa.config import DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n    default_vault=VaultTarget.PERSONAL\n)\n```\n\n### Isolation Modes\n\n| Mode | Behavior |\n|------|----------|\n| `AUTO` | Content auto-classified to shared or personal vault based on message type |\n| `MANUAL` | Explicit `VaultTarget` routing per operation |\n| `STRICT` | Enforce isolation boundaries |\n\n### VaultTarget Enum\n\n```python\nfrom ompa.config import VaultTarget\n\nVaultTarget.SHARED    # Team/organizational content\nVaultTarget.PERSONAL # Private/personal content\n```\n\n---\n\n## Async API\n\nFor async applications, use `ompa/async_api.py`:\n\n```python\nfrom ompa.async_api import AsyncOmpa\n\nasync with AsyncOmpa(vault_path=\"./workspace\") as ao:\n    await ao.session_start()\n    result = await ao.search(\"authentication\")\n    await ao.stop()\n```\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)()\n\n---\n\n## Configuration Options\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `OMPA_VAULT_PATH` | `.` | Absolute path to vault |\n| `OMPA_ENABLE_SEMANTIC` | `false` | Enable local semantic search |\n| `OMPA_AGENT_NAME` | `agent` | Agent name (scopes KG entries) |\n| `OMPA_SHARED_VAULT` | — | Shared vault path (dual-vault mode) |\n| `OMPA_PERSONAL_VAULT` | — | Personal vault path (dual-vault mode) |\n\n---\n\n## Return Types\n\n### `HookResult`\n\n```python\n@dataclass\nclass HookResult:\n    success: bool\n    output: str\n    tokens_hint: int\n    hook_name: str\n```\n\n### `Classification`\n\n```python\n@dataclass\nclass Classification:\n    message_type: MessageType\n    confidence: float\n    suggested_folder: str\n    routing_hint: str\n```\n\n### `SearchResult`\n\n```python\n@dataclass\nclass SearchResult:\n    path: Path\n    content: str\n    score: float\n    frontmatter: dict\n```\n\n### `Triple`\n\n```python\n@dataclass\nclass Triple:\n    subject: str\n    predicate: str\n    object: str\n    valid_from: str | None\n    valid_to: str | None\n    source: str | None\n```\n\n---\n\n## Usage Examples\n\n### Basic Session Workflow\n\n```python\nfrom ompa import Ompa\n\n# Initialize\nao = Ompa(vault_path=\"./workspace\")\n\n# Start session\ncontext = ao.session_start()\nprint(context.output)\n\n# Process messages\nao.handle_message(\"We decided to go with Postgres\")\nao.post_tool(\"write\", {\"file_path\": \"work/active/db-choice.md\"})\n\n# Search\nresults = ao.search(\"authentication decisions\")\n\n# End session\nao.stop()\n```\n\n### Dual-Vault Workflow\n\n```python\nfrom ompa import Ompa, DualVaultConfig, IsolationMode\n\nconfig = DualVaultConfig(\n    shared_vault=\"./team-vault\",\n    personal_vault=\"./private-vault\",\n    mode=IsolationMode.AUTO,\n)\n\nao = Ompa(config=config)\n\n# Auto-routed writes\nao.write(\"Team decision about API design\", tags=[\"decision\"])\n\n# Manual routing\nfrom ompa.config import VaultTarget\nao.write(\"Personal note\", vault=VaultTarget.PERSONAL)\n\n# Export to shared vault\nao.export_to_shared(\"personal/note.md\", sanitize=True)\n```\n\n### Knowledge Graph Usage\n\n```python\nao = Ompa(vault_path=\"./workspace\")\n\n# Add relationships\nao.kg.add_triple(\"Kai\", \"works_on\", \"Orion\", valid_from=\"2025-06-01\")\nao.kg.add_triple(\"Orion\", \"uses\", \"PostgreSQL\", valid_from=\"2025-06-15\")\n\n# Query history\ntriples = ao.kg.query_entity(\"Kai\")\ntimeline = ao.kg.timeline(\"Orion\")\n\n# Get stats\nprint(ao.kg.stats())\n```\n\n---\n\n## Stable Public API\n\nThe following API surface is stable per Semantic Versioning:\n\n- `Ompa` class and all public methods\n- `DualVaultConfig`, `IsolationMode`, `VaultTarget`\n- `HookResult`, `Classification`, `SearchResult`, `Triple`\n- `SemanticIndex`, `SyncBackend`, adapters\n- `count_tokens()` utility\n\nInternal implementation details may change in minor versions.\n\n资料来源：[STABILITY.md](https://github.com/jmiaie/ompa/blob/main/STABILITY.md)()\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: jmiaie/ompa\n\nSummary: Found 11 potential pitfall items; 0 are high/blocking. Highest priority: installation - 来源证据：OMPA v0.2.0 — The Big Rename.\n\n## 1. installation · 来源证据：OMPA v0.2.0 — The Big Rename\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OMPA v0.2.0 — The Big Rename\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ac771ab081be444ab18c5c1963becb64 | https://github.com/jmiaie/ompa/releases/tag/v0.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. configuration · 来源证据：[P0] agent_integration.py race condition — session.memory attribute not available on cold start\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[P0] agent_integration.py race condition — session.memory attribute not available on cold start\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_db65ef8ac28c41048d74c03c80cbed28 | https://github.com/jmiaie/ompa/issues/6 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1207151629 | https://github.com/jmiaie/ompa | README/documentation is current enough for a first validation pass.\n\n## 4. runtime · 社区讨论暴露的待验证问题：I did an analysis of 44 AI agent frameworks, sharing the result\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: I did an analysis of 44 AI agent frameworks, sharing the result 18 Feb 2026 · One thing missing from most framework comparisons is how they handle failures during agent execution. Tool call retries, error recovery, and ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:reddit | ssig_33233a78090343098fbddbeab9bc927d | https://www.reddit.com/r/LocalLLaMA/comments/1r84o6p/i_did_an_analysis_of_44_ai_agent_frameworks/ | I did an analysis of 44 AI agent frameworks, sharing the result\n\n## 5. runtime · 社区讨论暴露的待验证问题：Your self-hosted AI agents can match closed-source models - I ... - Reddit\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Your self-hosted AI agents can match closed-source models - I ... - Reddit 24 Nov 2025 · Looking for open-source knowledge management tool ... Let's compare 5 Open-Source AI Agent Tools that everyone cannot stop talking about on Reddit.\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:reddit | ssig_4fefa11ceedb46d4af5e2ff44e7709e1 | https://www.reddit.com/r/selfhosted/comments/1p5q8f1/your_selfhosted_ai_agents_can_match_closedsource/ | Your self-hosted AI agents can match closed-source models - I ... - Reddit\n\n## 6. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | last_activity_observed missing\n\n## 7. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium\n\n## 8. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium\n\n## 9. security_permissions · 来源证据：OMPA v0.2.1 — Security & Reliability Hardening\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：OMPA v0.2.1 — Security & Reliability Hardening\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ab0ad6b963354f2096bef6783c95c289 | https://github.com/jmiaie/ompa/releases/tag/v0.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 10. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | issue_or_pr_quality=unknown\n\n## 11. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | release_recency=unknown\n\n<!-- canonical_name: jmiaie/ompa; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "Human Manual"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log\n\nProject: jmiaie/ompa\n\nSummary: Found 11 potential pitfall items; 0 are high/blocking. Highest priority: installation - 来源证据：OMPA v0.2.0 — The Big Rename.\n\n## 1. installation · 来源证据：OMPA v0.2.0 — The Big Rename\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OMPA v0.2.0 — The Big Rename\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ac771ab081be444ab18c5c1963becb64 | https://github.com/jmiaie/ompa/releases/tag/v0.2.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. configuration · 来源证据：[P0] agent_integration.py race condition — session.memory attribute not available on cold start\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[P0] agent_integration.py race condition — session.memory attribute not available on cold start\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_db65ef8ac28c41048d74c03c80cbed28 | https://github.com/jmiaie/ompa/issues/6 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1207151629 | https://github.com/jmiaie/ompa | README/documentation is current enough for a first validation pass.\n\n## 4. runtime · 社区讨论暴露的待验证问题：I did an analysis of 44 AI agent frameworks, sharing the result\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: I did an analysis of 44 AI agent frameworks, sharing the result 18 Feb 2026 · One thing missing from most framework comparisons is how they handle failures during agent execution. Tool call retries, error recovery, and ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:reddit | ssig_33233a78090343098fbddbeab9bc927d | https://www.reddit.com/r/LocalLLaMA/comments/1r84o6p/i_did_an_analysis_of_44_ai_agent_frameworks/ | I did an analysis of 44 AI agent frameworks, sharing the result\n\n## 5. runtime · 社区讨论暴露的待验证问题：Your self-hosted AI agents can match closed-source models - I ... - Reddit\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Your self-hosted AI agents can match closed-source models - I ... - Reddit 24 Nov 2025 · Looking for open-source knowledge management tool ... Let's compare 5 Open-Source AI Agent Tools that everyone cannot stop talking about on Reddit.\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:reddit | ssig_4fefa11ceedb46d4af5e2ff44e7709e1 | https://www.reddit.com/r/selfhosted/comments/1p5q8f1/your_selfhosted_ai_agents_can_match_closedsource/ | Your self-hosted AI agents can match closed-source models - I ... - Reddit\n\n## 6. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | last_activity_observed missing\n\n## 7. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium\n\n## 8. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1207151629 | https://github.com/jmiaie/ompa | no_demo; severity=medium\n\n## 9. security_permissions · 来源证据：OMPA v0.2.1 — Security & Reliability Hardening\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：OMPA v0.2.1 — Security & Reliability Hardening\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ab0ad6b963354f2096bef6783c95c289 | https://github.com/jmiaie/ompa/releases/tag/v0.2.1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 10. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | issue_or_pr_quality=unknown\n\n## 11. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1207151629 | https://github.com/jmiaie/ompa | release_recency=unknown\n",
      "summary": "Identity, installation, configuration, runtime, and safety pitfalls before user trial.",
      "title": "Pitfall Log"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# ompa - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for jmiaie/ompa.\n\nProject:\n- Name: ompa\n- Repository: https://github.com/jmiaie/ompa\n- Summary: Universal AI agent memory layer — vault + palace + temporal knowledge graph\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Universal AI agent memory layer — vault + palace + temporal knowledge graph\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Universal AI agent memory layer — vault + palace + temporal knowledge graph\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. introduction: Introduction to OMPA. Produce one small intermediate artifact and wait for confirmation.\n2. quickstart: Quick Start Guide. Produce one small intermediate artifact and wait for confirmation.\n3. three-layer-architecture: Three-Layer Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. lifecycle-hooks: Lifecycle Hooks. Produce one small intermediate artifact and wait for confirmation.\n5. vault-system: Vault System. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/jmiaie/ompa\n- https://github.com/jmiaie/ompa#readme\n- README.md\n- ompa/__init__.py\n- ompa/cli.py\n- pyproject.toml\n- ompa/vault.py\n- ompa/palace.py\n- ompa/knowledge_graph.py\n- ompa/hooks.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start\n\nProject: jmiaie/ompa\n\n## Official Entry Points\n\n### Python / pip · 官方安装入口\n\n```bash\npip install ompa\n```\n\nSource：https://github.com/jmiaie/ompa#readme\n\n## Sources\n\n- repo: https://github.com/jmiaie/ompa\n- docs: https://github.com/jmiaie/ompa#readme\n",
      "summary": "Entry points extracted from official README or installation documentation.",
      "title": "Quick Start"
    }
  },
  "validation_id": "dval_f36a29492d3047ee85d07d51a5cc5d62"
}
